Exemple #1
0
def call(request):
    """Returns TwiML instructions to Twilio's POST requests"""

    response = twiml.Response()
    phone_number = request.POST.get('phoneNumber', '').lstrip('1')

    if phone_number:
        """If the browser sent a phoneNumber param, we know this request
        is an outgoing call from the pyphone"""
        for c in '()-':
            phone_number = phone_number.replace(c, '')
        phone_number = '+1' + phone_number
        direction = 'outgoing'
        with response.dial(callerId=settings.TWILIO_NUMBER) as r:
            r.number(request.POST['phoneNumber'])
    else:
        """Otherwise we assume this request is an incoming call."""
        direction = 'incoming'
        with response.dial() as r:
            r.client('caller')
        phone_number = request.GET.get('From', '')

    try:
        contact = Contact.objects.get(number=phone_number)
    except ObjectDoesNotExist:
        contact = Contact(number=phone_number)
        contact.save()
    call = Call(
        contact=contact,
        direction=direction,
    )
    call.save()

    return HttpResponse(str(response))
Exemple #2
0
 def test_call_queryset_is_all_calls(self):
     """Call view should show all texts."""
     user1 = User()
     user1.save()
     self.client.force_login(user1)
     calls = self.client.get('/api/calls/')
     self.assertEqual(len(calls.json()), 0)
     jabba = Contact(name="Jabba", number="+12068675309")
     jabba.save()
     call1 = Call(contact=jabba, direction="outgoing", status="completed")
     call1.save()
     calls = self.client.get('/api/calls/')
     self.assertEqual(len(calls.json()), 1)
Exemple #3
0
 def test_call_queryset_returns_call_attributes_in_json(self):
     """Test that a call to the calls api contains call attributes."""
     user1 = User()
     user1.save()
     self.client.force_login(user1)
     jabba = Contact(name="Jabba", number="+12068675309")
     jabba.save()
     call1 = Call(contact=jabba, direction="outgoing", status="completed")
     call1.save()
     calls = self.client.get('/api/calls/')
     self.assertTrue("direction" in calls.content.decode())
     self.assertTrue("outgoing" in calls.content.decode())
     self.assertTrue("time" in calls.content.decode())
     self.assertTrue("status" in calls.content.decode())
     self.assertTrue("contact" in calls.content.decode())
Exemple #4
0
def call_process(request):
	# Get this request's context
	context = RequestContext(request)

	# Get objects called through the HTTP POST request
	if request.method == 'POST':

		# Get class id from the POST and associated Class object
		class_id = request.POST.get('class')
		requested_class = Class.objects.get(id=int(class_id))

		# Construct a new Call object
		call_to_add = Call(teach=requested_class)

		call_to_add.save()

		return HttpResponse("Your tutor is being requested. You will get a text when you get a match.")

	return HttpResponse("Got here.")
Exemple #5
0
def call_process(request):
    # Get this request's context
    context = RequestContext(request)

    # Get objects called through the HTTP POST request
    if request.method == 'POST':

        # Get class id from the POST and associated Class object
        class_id = request.POST.get('class')
        requested_class = Class.objects.get(id=int(class_id))

        # Construct a new Call object
        call_to_add = Call(teach=requested_class)

        call_to_add.save()

        return HttpResponse(
            "Your tutor is being requested. You will get a text when you get a match."
        )

    return HttpResponse("Got here.")
Exemple #6
0
def send_report_by_sendgrid(user, date_from, date_to):
    logger.info('Entrando a send_report_by_sendgrid')

    parameters = dict()
    parameters['date_from'] = date_from
    parameters['date_to'] = date_to
    # query
    data = Call.get_dynamic_calls_async(**parameters)
    # preparacion del reporte
    report = create_tablib(data)
    logger.info(report)

    if report is not None:
        data = {
            'name': 'reporte_llamadas.xlsx',
            'report': report.xlsx,
        }
        # preparación para enviar correo
        mail = SGEmailClient()
        mail.send_report_email(user, data)
    else:
        logger.info('no hay datos para crear excel')
Exemple #7
0
def create_calls_from_call_legs(start_date=None, end_date=None):
    date_range = date_range_from_dates(start_date, end_date)
    call_legs = CallLeg.objects.filter(timestamp__date__range=date_range)

    call_legs_to_match = {}
    for call_leg in call_legs:
        ucid = call_leg.ucid
        if ucid in call_legs_to_match.keys():
            call_legs_to_match[ucid].append(call_leg)
        else:
            call_legs_to_match[ucid] = [call_leg]

    calls_to_create = []
    for ucid, call_legs_list in call_legs_to_match.items():
        data_for_instance = prepare_call_data(call_legs_list)
        if data_for_instance:
            call_instance = Call(**data_for_instance)
            calls_to_create.append(call_instance)

    # TODO: доделать логгеры
    logging.info(f'Trying to create {len(calls_to_create)} Calls instances')
    Call.objects.bulk_create(calls_to_create, ignore_conflicts=True)
    logging.info(
        f'{len(calls_to_create)} Calls instances successfully created')
Exemple #8
0
    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            call = Call()
            call.save()

            try:
                call_start = serializer.save(call_id=call)
            except ValidationError as err:
                call.delete()
                return Response(data=err, status=status.HTTP_400_BAD_REQUEST)

            serializer = CallAfterStartSerializer({
                'call_id': call.pk,
                'source': call_start.source,
                'destination': call_start.destination,
                'time': call_start.timestamp
            })

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
		print "No Beat found for %s" % row[ "Beat" ]
		beat = Beat()
		beat.name = row[ "Beat" ]
		beat.jurisdiction = juri
		beat.save()
	try:
		call_type = CallType.objects.get( name__iexact=row[ "CallType" ].strip().upper() )
		#print "FOUND call_type: %s" % call_type
	except:
		print bail()
	
	try:
		call = Call.objects.get( event_num__iexact = row[ "EventNum" ].strip() )
		action = "UPDATE"
	except:
		call = Call()
		action = "INSERT"
		
	call.description = row[ "Description" ]
	call.event_num = row[ "EventNum" ]
	call.report_num = row[ "ReportNum" ]
	call.response = row[ "Response" ]
	call.address = row[ "Address" ]
	call.zip_code = row[ "Zip" ]
	call.call_time = row[ "CallTime" ]
	call.call_type = call_type
	call.calltype_id = call_type.id
	call.beat = beat
	if ( row[ "Lng" ] is not None or row[ "Lng" ] != "" ) and ( row[ "Lat" ] is not None or row[ "Lng" ] != "" ):
		try:
			call.geom = fromstr('POINT(' + row[ "Lng"] + " " + row[ "Lat" ] +')', srid=4326)
Exemple #10
0
 def test_queryset_returns_multiple_calls_when_in_db(self):
     """Test that queryset returns all calls if there are many in db."""
     user1 = User()
     user1.save()
     self.client.force_login(user1)
     calls = self.client.get('/api/calls/')
     self.assertEqual(len(calls.json()), 0)
     jabba = Contact(name="Jabba", number="+12068675309")
     jabba.save()
     call1 = Call(contact=jabba, direction="outgoing", status="completed")
     call1.save()
     han = Contact(name="Han", number="+15555555555")
     han.save()
     call2 = Call(contact=han, direction="incoming", status="busy")
     call2.save()
     nerfherder = Contact(name="Nerf Herder", number="+16666666666")
     nerfherder.save()
     call3 = Call(contact=nerfherder,
                  direction="outgoing",
                  status="completed")
     call3.save()
     calls = self.client.get('/api/calls/')
     self.assertEqual(len(calls.json()), 3)
Exemple #11
0
				#updated = True
			#if( (new_call.report_num == None or new_call.report_num == "" ) and ( call[ "report_num" ] != None or call[ "report_num" ] != "" ) ):
				#print "Report_num changed! db record is %s, website record is %s" % new_call.report_num, call[ "report_num" ]
				#new_call.report_num = call[ "report_num" ]
				#updated = True
			#if updated is True:
				#new_call.save()
				#print "UPDATING call: %s" % call[ "event_num" ]
				#update_count += 1
			#else:
			skip_count +=1 
			print "SKIPPING call: %s" % call[ "event_num" ]

		except:
			try:
				new_call = Call()
				print "creating call for " + call[ "event_num" ]
				#call was created. lets set all our shit about it
				new_call.calltype = calltype
				new_call.beat = beat
				new_call.jurisdiction = juri
				new_call.event_num = call[ "event_num" ]
				new_call.response = call[ "response" ]
				new_call.description = call[ "description" ]
				if call[ "address" ] != "" and call[ "address" ] is not None:
					call[ "address" ] = call[ "address" ].replace( "&", " & ")
					call[ "address" ] = call[ "address" ].replace( "US65", "US 65" )
					call[ "address" ] = call[ "address" ].replace( "JRF","James River Freeway" )
					#for some reason there is a bunch of addresses that are like "N; Boonville instead of just N Boonville"
					call[ "address" ] = call[ "address" ].replace( ";", "" )