Beispiel #1
0
    def get(self):
        """
        Determine whether the user correctly spelled the key word during
        her wakeup call.
        
        For instance, 'W-A-L-R-U-S' is correct.
        """
        digits = self.request.get('Digits')
        the_number = self.request.get('To')

        try:
            the_user = User.all().filter('phone_number =',
                                         the_number).fetch(1)[0]
        except IndexError:
            return 'FAIL'

        stop = (digits == chars_to_digits('stop'))
        correct = (digits == chars_to_digits(TODAYS_KEYWORD['word']))

        call_record = Call(user=the_user, correct_response=correct)
        call_record.put()

        if correct:
            res = YOU_SPELLED_THE_WALRUS
        else:
            if stop:
                the_user.delete()
                res = UNSUBSCRIBE
            else:
                res = THATS_NOT_HOW_YOU_SPELL_WALRUS % {
                    'keyword': TODAYS_KEYWORD['word'],
                    'domain': WALRUS_DOMAIN
                }
        return self.return_XML(res)
Beispiel #2
0
    def retrieve_api_call(self, product, api_id):
        temp_call = getattr(g.db, product.db_name).find_one(
            {'_id': ObjectId(api_id)})
        if temp_call:
            return Call(temp_call)

        return temp_call
Beispiel #3
0
 def init_call(self, mobile_number):
     call_url = self.initiate_call_urlformat.format(sid=self.sid)
     flow_url = self.flow_urlformat.format(flow_id=self.flow_id)
     #TODO create a call object. add the id to the CustomField. save the call object
     props = self.init_props()
     post_data = {
         'From': int(mobile_number),
         'CallerId': self.caller_id,
         'Url': flow_url,
         'TimeLimit': self.time_limit,
         'TimeOut': self.time_out,
         'CallType': self.call_type,
         'StatusCallback': reverse(self.ServiceCallEndView.get_name()),
         'CustomField': json.dumps(props),
     }
     r = requests.post(call_url,
                       auth=(self.sid, self.token),
                       data=post_data)
     response_data = json.loads(r.text)
     call_sid = response_data['Call']['Sid']
     call = Call(exotel_call_id=call_sid)
     call.state = json.dumps(self.init_state())
     call.props = json.dumps(self.init_props())
     call.save()
     #return {"id": call.id, "exotel_id": call_sid}
     return {"exotel_id": call_sid}
    def parse_metadata(self, metadata, stack):
        if self.indent is None:
            self.indent = metadata.indent

        if metadata.indent < self.indent:
            self.close(metadata, stack)
            return

        match = regex_jump.match(metadata.line)
        if match:
            label = match["label"]
            jump = Jump(label, metadata)
            self.context.add_child(jump)
            return
        
        match = regex_call.match(metadata.line)
        if match:
            label = match["label"]
            call = Call(label, metadata)
            self.context.add_child(call)
            return
        
        match = regex_script.match(metadata.line)
        if match:
            script_code = match["script"]
            script = Script(script_code, metadata)
            self.context.add_child(script)
            return
        
        match = regex_condition.match(metadata.line)
        if match:
            parser = ConditionParser(self, metadata)
            stack.push(parser)
            stack.parse_metadata(metadata)
            return
        
        match = regex_menu.match(metadata.line)
        if match:
            parser = MenuParser(self, metadata)
            stack.push(parser)
            return
        
        match = regex_python_block.match(metadata.line)
        if match:
            parser = PythonScriptParser(self, metadata)
            stack.push(parser)
            return
        
        self.context.add_child(Text(metadata.line, metadata))
Beispiel #5
0
def create():
    form = RegistrationForm()
    if form.validate() is False:
        return render_template('calls/new.html', form=form)
    else:
        call = Call()
        call.title = form.title.data
        call.link = form.link.data
        call.active = 0

        db.session.add(call)
        db.session.commit()

        message = u'Muito obrigado! sua Chamada foi submetida com sucesso!'
        flash(message, 'success')
        return redirect(url_for('calls.admin'))
Beispiel #6
0
    def _handle_create(self, e):
        '''Handle channel create events by building local
        `Session` and `Call` objects for state tracking.
        '''
        uuid = e.getHeader('Unique-ID')
        self.log.debug("channel created for session '{}'".format(uuid))
        # Record the newly activated session
        # TODO: pass con as weakref?
        con = self._tx_con if not self._shared else None
        sess = Session(event=e, con=con)
        sess.cid = self.get_id(e, 'default')
        # note the start time and current load
        # TODO: move this to Session __init__??
        sess.create_time = get_event_time(e)

        # Use our special Xheader to try and associate sessions into calls
        # (assumes that x-headers are forwarded by the proxy/B2BUA)
        call_uuid = e.getHeader('variable_{}'.format(self.call_corr_xheader))
        # If that fails then try using the freeswitch 'variable_call_uuid'
        # (only works if bridging takes place locally)
        if call_uuid is None:
            call_uuid = e.getHeader(self.call_corr_var)  # could be 'None'
            if not call_uuid:
                self.log.warn("Unable to associate session '{}' into calls"
                              .format(sess.uuid))

        # associate sessions into a call
        # (i.e. set the relevant sessions to reference each other)
        if call_uuid in self.calls:
            call = self.calls[call_uuid]
            self.log.debug("session '{}' is bridged to call '{}'".format(
                           uuid, call.uuid))
            # append this session to the call's set
            call.sessions.append(sess)

        else:  # this sess is not yet tracked so use its id as the 'call' id
            call = Call(call_uuid, sess)
            self.calls[call_uuid] = call
            self.log.debug("call created for session '{}'".format(call_uuid))
        sess.call = call
        self.sessions[uuid] = sess
        return True, sess
Beispiel #7
0
    def create_call(payload):
        body = request.get_json()
        if not body:
            abort(400, 'Request body is missing.')
        if body.get('question') is None:
            abort(400, '"question" is required in the request body.')

        # Create a new record
        c = Call(
            question=body.get('question'),
            description=body.get('description', ''),
            topics=[get_topic(name=t) for t in body.get('topics', [])]
        )
        try:
            c.insert()
            call_id = c.id
        except Exception:
            abort(422, 'Database error: Insertion failed.')

        return jsonify({
            'success': True,
            'message': 'Call record has been created successfully.',
            'id': call_id
        }), 201
Beispiel #8
0
def twilio_call(request):

    #    if request.method is not 'GET':
    #        return HttpResponse(status=400)

    account_sid = secrets.TWILIO_ACCOUNT_SID  # Your Account SID from www.twilio.com/console
    auth_token = secrets.TWILIO_ACCOUNT_SECRET  # Your Auth Token from www.twilio.com/console

    required = ['name', 'npeople', 'datetime', 'resid', 'cusphone', 'lang']
    for req in required:
        if req not in request.GET:
            return JSONResponse(status=400)

    name = request.GET.get('name')
    num_people = request.GET.get('npeople')
    timestamp = request.GET.get('datetime')
    jptz = pytz.timezone('Asia/Tokyo')
    dt = datetime.datetime.fromtimestamp(float(timestamp), tz=jptz)
    shopid = request.GET.get('resid')
    if request.GET.get('lang') == "ja":
        language = Call.JAPANESE
    else:
        language = Call.ENGLISH
    cus_phone = request.GET.get('cusphone')

    shop_info = Venue.objects.get(pk=shopid)
    #res_phone = shop_info.phone
    res_phone = secrets.TEST_PHONE
    res_name = shop_info.name

    call_info = Call()
    call_info.name = name
    call_info.num_people = num_people
    call_info.date_time = dt
    call_info.res_phone = res_phone
    call_info.cus_phone = cus_phone
    call_info.language_opt = language
    call_info.res_name = res_name
    call_info.save()

    # After save, I have this id.
    pk = call_info.pk

    # Make request to Twilio.
    url = "http://tjr.tonny.me/reservation/" + str(pk) + '/'
    client = TwilioRestClient(account_sid, auth_token)

    try:
        call = client.calls.create(
            url=url,
            to=res_phone,
            from_=secrets.TWILIO_PHONE,
            status_callback="http://tjr.tonny.me/callingstatus/" + str(pk) +
            '/',
            status_callback_method="POST",
        )
    except TwilioRestException as e:
        print(e)

    serializer = CallSerializer(call_info)
    return JSONResponse(serializer.data)
Beispiel #9
0
    def manage_add_edit_call(self, product, api_id=None):
        edit, count, title = False, 1, 'Add API Call'
        api_settings = g.db.api_settings.find_one()
        found_product = self.retrieve_product(product)
        if type(found_product) is str:
            flash('Product not found, please check the URL and try again')
            return redirect('/')

        if api_id:
            found_call = self.retrieve_api_call(found_product, api_id)
            if not found_call:
                flash('API Call was not found', 'error')
                return redirect('/%s/manage/api' % product)

            title = 'Edit API Call'
            edit = True
            post_url = "/%s/manage/api/edit/%s" % (product, api_id)
            form, count = helper.generate_edit_call_form(
                found_product, found_call, api_id)
        else:
            post_url = "/%s/manage/api/add" % product
            form = helper.add_fields_to_form(count)
            for i in range(count):
                temp = getattr(form, 'variable_%i' % i)
                temp.form.id_value.data = i

        form.verb.choices = [(verb.get('name'), verb.get('name'))
                             for verb in api_settings.get('verbs')]
        form.group.choices = helper.generate_group_choices(found_product)
        form.product.data = product
        if request.method == 'POST' and form.validate_on_submit():
            api_call = Call(request.form.to_dict())
            api_call.variables = helper.get_vars_for_call(
                list(request.form.iterlists()))
            if api_id:
                getattr(g.db, found_product.db_name).update(
                    {'_id': ObjectId(api_id)}, {'$set': api_call.__dict__})
                flash('API Call was successfully updated', 'success')
            else:
                try:
                    getattr(g.db,
                            found_product.db_name).insert(api_call.__dict__)
                    flash('API Call was added successfully', 'success')
                except Exception:
                    flash(
                        'There was an issue storing the API Call. Check '
                        'the product and ensure the db_name is specified',
                        'error')

            return redirect('/%s/manage/api' % product)
        else:
            if request.method == 'POST':
                flash(
                    'Form validation error, please check the '
                    'form and try again', 'error')

            return render_template(
                'manage/manage_call_add_edit.html',
                title=title,
                form=form,
                count=count,
                edit=edit,
                post_url=post_url,
                cancel_return='/%s/manage/api' % product,
            )