示例#1
0
        def post(self, request, *args, **kwargs):

            def update_aliases(boundary, new_aliases):
                # for now, nuke and recreate all aliases
                BoundaryAlias.objects.filter(boundary=boundary, org=org).delete()
                for new_alias in new_aliases.split('\n'):
                    if new_alias:
                        BoundaryAlias.objects.create(boundary=boundary, org=org, name=new_alias,
                                                     created_by=self.request.user, modified_by=self.request.user)

            # try to parse our body
            json_string = request.body
            org = request.user.get_org()

            try:
                json_dict = json.loads(json_string)
            except Exception as e:
                return build_json_response(dict(status="error", description="Error parsing JSON: %s" % str(e)), status=400)

            # this can definitely be optimized
            for state in json_dict:
                state_boundary = AdminBoundary.objects.filter(osm_id=state['osm_id']).first()
                state_aliases = state.get('aliases', '')
                if state_boundary:
                    update_aliases(state_boundary, state_aliases)
                    if 'children' in state:
                        for district in state['children']:
                            district_boundary = AdminBoundary.objects.filter(osm_id=district['osm_id']).first()
                            district_aliases = district.get('aliases', '')
                            update_aliases(district_boundary, district_aliases)

            return build_json_response(json_dict)
示例#2
0
        def post(self, request, *args, **kwargs):
            json_string = request.body
            user = request.user
            org = user.get_org()

            try:
                json_dict = json.loads(json_string)
            except Exception as e:
                return build_json_response(dict(
                    status="error",
                    description="Error parsing JSON: %s" % str(e)),
                                           status=400)

            try:
                report = Report.create_report(org, user, json_dict)
            except Exception as e:  # pragma: needs cover
                traceback.print_exc(e)
                return build_json_response(dict(
                    status="error",
                    description="Error creating report: %s" % str(e)),
                                           status=400)

            return build_json_response(dict(status="success",
                                            description="Report Created",
                                            report=report.as_json()),
                                       status=200)
示例#3
0
    def post(self, request, *args, **kwargs):
        call = IVRCall.objects.filter(pk=kwargs['pk']).first()

        if not call:
            return HttpResponse("Not found", status=404)

        client = call.channel.get_ivr_client()
        if request.REQUEST.get('hangup', 0):
            if not request.user.is_anonymous():
                user_org = request.user.get_org()
                if user_org and user_org.pk == call.org.pk:
                    client.calls.hangup(call.external_id)
                    return HttpResponse(json.dumps(dict(status='Canceled')),
                                        content_type="application/json")
                else:
                    return HttpResponse("Not found", status=404)

        if client.validate(request):
            status = request.POST.get('CallStatus', None)
            duration = request.POST.get('CallDuration', None)
            call.update_status(status, duration)

            # update any calls we have spawned with the same
            for child in call.child_calls.all():
                child.update_status(status, duration)
                child.save()

            call.save()

            # figure out if this is a callback due to an empty gather
            is_empty = '1' == request.GET.get('empty', '0')
            user_response = request.POST.copy()

            # if the user pressed pound, then record no digits as the input
            if is_empty:
                user_response['Digits'] = ''

            hangup = 'hangup' == user_response.get('Digits', None)

            if call.status in [IN_PROGRESS, RINGING] or hangup:
                if call.is_flow():
                    response = Flow.handle_call(call,
                                                user_response,
                                                hangup=hangup)
                    return HttpResponse(unicode(response))
            else:
                if call.status == COMPLETED:
                    # if our call is completed, hangup
                    run = FlowRun.objects.filter(call=call).first()
                    if run:
                        run.set_completed()
                return build_json_response(dict(message="Updated call status"))

        else:  # pragma: no cover
            # raise an exception that things weren't properly signed
            raise ValidationError("Invalid request signature")

        return build_json_response(dict(message="Unhandled"))
示例#4
0
    def post(self, request, *args, **kwargs):
        call = IVRCall.objects.filter(pk=kwargs['pk']).first()

        if not call:
            return HttpResponse("Not found", status=404)

        client = call.channel.get_ivr_client()
        if request.REQUEST.get('hangup', 0):
            if not request.user.is_anonymous():
                user_org = request.user.get_org()
                if user_org and user_org.pk == call.org.pk:
                    client.calls.hangup(call.external_id)
                    return HttpResponse(json.dumps(dict(status='Canceled')), content_type="application/json")
                else:
                    return HttpResponse("Not found", status=404)

        if client.validate(request):
            status = request.POST.get('CallStatus', None)
            duration = request.POST.get('CallDuration', None)
            call.update_status(status, duration)

            # update any calls we have spawned with the same
            for child in call.child_calls.all():
                child.update_status(status, duration)
                child.save()

            call.save()

            # figure out if this is a callback due to an empty gather
            is_empty = '1' == request.GET.get('empty', '0')
            user_response = request.POST.copy()

            # if the user pressed pound, then record no digits as the input
            if is_empty:
                user_response['Digits'] = ''

            hangup = 'hangup' == user_response.get('Digits', None)

            if call.status == IN_PROGRESS or hangup:
                if call.is_flow():
                    response = Flow.handle_call(call, user_response, hangup=hangup)
                    return HttpResponse(unicode(response))
            else:

                if call.status == COMPLETED:
                    # if our call is completed, hangup
                    run = FlowRun.objects.filter(call=call).first()
                    if run:
                        run.set_completed()
                return build_json_response(dict(message="Updated call status"))

        else:  # pragma: no cover
            # raise an exception that things weren't properly signed
            raise ValidationError("Invalid request signature")

        return build_json_response(dict(message="Unhandled"))
示例#5
0
        def post(self, request, *args, **kwargs):
            def update_boundary_aliases(boundary):
                level_boundary = AdminBoundary.objects.filter(
                    osm_id=boundary['osm_id']).first()
                if level_boundary:
                    boundary_aliases = boundary.get('aliases', '')
                    update_aliases(level_boundary, boundary_aliases)

            def update_aliases(boundary, new_aliases):
                # for now, nuke and recreate all aliases
                BoundaryAlias.objects.filter(boundary=boundary,
                                             org=org).delete()
                for new_alias in new_aliases.split('\n'):
                    if new_alias:
                        BoundaryAlias.objects.create(
                            boundary=boundary,
                            org=org,
                            name=new_alias.strip(),
                            created_by=self.request.user,
                            modified_by=self.request.user)

            # try to parse our body
            json_string = request.body
            org = request.user.get_org()

            try:
                json_list = json.loads(json_string)
            except Exception as e:
                return build_json_response(dict(
                    status="error",
                    description="Error parsing JSON: %s" % str(e)),
                                           status=400)

            # this can definitely be optimized
            for state in json_list:
                state_boundary = AdminBoundary.objects.filter(
                    osm_id=state['osm_id']).first()
                state_aliases = state.get('aliases', '')
                if state_boundary:
                    update_aliases(state_boundary, state_aliases)
                    if 'children' in state:
                        for district in state['children']:
                            update_boundary_aliases(district)
                            if 'children' in district:
                                for ward in district['children']:
                                    update_boundary_aliases(ward)

            return build_json_response(json_list)
示例#6
0
        def get(self, request, *args, **kwargs):
            tops = list(AdminBoundary.objects.filter(parent__osm_id=self.get_object().osm_id).order_by('name'))
            children = AdminBoundary.objects.filter(Q(parent__osm_id__in=[boundary.osm_id for boundary in tops])).order_by('parent__osm_id', 'name')

            boundaries = []
            for top in tops:
                boundaries.append(top.as_json())

            current_top = None
            match = ''
            for child in children:
                child = child.as_json()

                # find the appropriate top if necessary
                if not current_top or current_top['osm_id'] != child['parent_osm_id']:
                    for top in boundaries:
                        if top['osm_id'] == child['parent_osm_id']:
                            current_top = top
                            match = '%s %s' % (current_top['name'], current_top['aliases'])

                children = current_top.get('children', [])
                child['match'] = '%s %s %s %s' % (child['name'], child['aliases'], current_top['name'], current_top['aliases'])
                children.append(child)
                match = '%s %s %s' % (match, child['name'], child['aliases'])
                current_top['children'] = children
                current_top['match'] = match

            return build_json_response(boundaries)
示例#7
0
    def post(self, request, *args, **kwargs):
        from twilio.util import RequestValidator

        call = IVRCall.objects.filter(pk=kwargs['pk']).first()

        if not call:
            return HttpResponse("Not found", status=404)

        client = call.channel.get_ivr_client()
        if request.REQUEST.get('hangup', 0):
            if not request.user.is_anonymous():
                user_org = request.user.get_org()
                if user_org and user_org.pk == call.org.pk:
                    client.calls.hangup(call.external_id)
                    return HttpResponse(json.dumps(dict(status='Canceled')),
                                        content_type="application/json")
                else:
                    return HttpResponse("Not found", status=404)

        if client.validate(request):
            call.update_status(request.POST.get('CallStatus', None),
                               request.POST.get('CallDuration', None))
            call.save()

            hangup = 'hangup' == request.POST.get('Digits', None)

            if call.status == IN_PROGRESS or hangup:
                if call.is_flow():
                    response = Flow.handle_call(call,
                                                request.POST,
                                                hangup=hangup)
                    return HttpResponse(unicode(response))
            else:

                if call.status == COMPLETED:
                    # if our call is completed, hangup
                    run = FlowRun.objects.filter(call=call).first()
                    if run:
                        run.set_completed()
                        run.expire()
                return build_json_response(dict(message="Updated call status"))

        else:  # pragma: no cover
            # raise an exception that things weren't properly signed
            raise ValidationError("Invalid request signature")

        return build_json_response(dict(message="Unhandled"))
示例#8
0
文件: views.py 项目: Ebaneck/rapidpro
        def post(self, request, *args, **kwargs):
            json_string = request.body
            user = request.user
            org = user.get_org()

            try:
                json_dict = json.loads(json_string)
            except Exception as e:
                return build_json_response(dict(status="error", description="Error parsing JSON: %s" % str(e)), status=400)

            try:
                report = Report.create_report(org, user, json_dict)
            except Exception as e:
                traceback.print_exc(e)
                return build_json_response(dict(status="error", description="Error creating report: %s" % str(e)), status=400)

            return build_json_response(dict(status="success", description="Report Created", report=report.as_json()), status=200)
示例#9
0
    def post(self, request, *args, **kwargs):
        from twilio.util import RequestValidator

        call = IVRCall.objects.filter(pk=kwargs['pk']).first()

        if not call:
            return HttpResponse("Not found", status=404)

        client = call.channel.get_ivr_client()
        if request.REQUEST.get('hangup', 0):
            if not request.user.is_anonymous():
                user_org = request.user.get_org()
                if user_org and user_org.pk == call.org.pk:
                    client.calls.hangup(call.external_id)
                    return HttpResponse(json.dumps(dict(status='Canceled')), content_type="application/json")
                else:
                    return HttpResponse("Not found", status=404)

        if client.validate(request):
            call.update_status(request.POST.get('CallStatus', None),
                               request.POST.get('CallDuration', None))
            call.save()

            hangup = 'hangup' == request.POST.get('Digits', None)

            if call.status == IN_PROGRESS or hangup:
                if call.is_flow():
                    response = Flow.handle_call(call, request.POST, hangup=hangup)
                    return HttpResponse(unicode(response))
            else:

                if call.status == COMPLETED:
                    # if our call is completed, hangup
                    run = FlowRun.objects.filter(call=call).first()
                    if run:
                        run.set_completed()
                        run.expire()
                return build_json_response(dict(message="Updated call status"))

        else:  # pragma: no cover
            # raise an exception that things weren't properly signed
            raise ValidationError("Invalid request signature")

        return build_json_response(dict(message="Unhandled"))
示例#10
0
    def post(self, request, *args, **kwargs):
        from twilio.util import RequestValidator

        call = IVRCall.objects.filter(pk=kwargs['pk']).first()

        if not call:
            return HttpResponse("Not found", status=404)

        client = call.channel.get_ivr_client()
        if request.REQUEST.get('hangup', 0):
            if not request.user.is_anonymous():
                user_org = request.user.get_org()
                if user_org and user_org.pk == call.org.pk:
                    client.calls.hangup(call.external_id)
                    return HttpResponse(json.dumps(dict(status='Canceled')), content_type="application/json")
                else:
                    return HttpResponse("Not found", status=404)

        validator = RequestValidator(client.auth[1])
        signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '')

        base_url = settings.TEMBA_HOST
        url = "https://%s%s" % (base_url, request.get_full_path())

        # make sure this is coming from twilio
        if validator.validate(url, request.POST, signature):
            call.update_status(request.POST.get('CallStatus', None),
                               request.POST.get('CallDuration', None))
            call.save()

            if call.status == IN_PROGRESS:
                if call.is_flow():
                    response = Flow.handle_call(call, request.POST)
                    return HttpResponse(unicode(response))
            else:
                return build_json_response(dict(message="Updated call status"))

        else:  # pragma: no cover
            # raise an exception that things weren't properly signed
            raise ValidationError("Invalid request signature")

        return build_json_response(dict(message="Unhandled"))
示例#11
0
        def get(self, request, *args, **kwargs):
            tops = list(
                AdminBoundary.objects.filter(
                    parent__osm_id=self.get_object().osm_id).order_by('name'))

            tops_children = AdminBoundary.objects.filter(
                Q(parent__osm_id__in=[boundary.osm_id
                                      for boundary in tops])).order_by(
                                          'parent__osm_id', 'name')

            boundaries = [top.as_json() for top in tops]

            current_top = None
            match = ''
            for child in tops_children:
                child = child.as_json()
                # find the appropriate top if necessary
                if not current_top or current_top['osm_id'] != child[
                        'parent_osm_id']:
                    for top in boundaries:
                        if top['osm_id'] == child['parent_osm_id']:
                            current_top = top
                            match = '%s %s' % (current_top['name'],
                                               current_top['aliases'])
                            current_top['match'] = match

                children = current_top.get('children', [])
                child['match'] = '%s %s' % (child['name'], child['aliases'])

                child_children = list(
                    AdminBoundary.objects.filter(
                        Q(parent__osm_id=child['osm_id'])).order_by('name'))
                sub_children = child.get('children', [])
                for sub_child in child_children:
                    sub_child = sub_child.as_json()
                    sub_child['match'] = '%s %s %s %s %s' % (
                        sub_child['name'], sub_child['aliases'], child['name'],
                        child['aliases'], match)

                    sub_children.append(sub_child)
                    child['match'] = '%s %s %s' % (child['match'],
                                                   sub_child['name'],
                                                   sub_child['aliases'])

                child['children'] = sub_children
                children.append(child)
                current_top['children'] = children
                current_top['match'] = '%s %s' % (current_top['match'],
                                                  child['match'])

            return build_json_response(boundaries)