Example #1
0
def retrieve_updates(request):
	"""
	Request handler to update client model after receiving a push notification
	1. Check queue to see if the client has any updates on standby
	2. Send the client their update
	3. Get ack from client
	4. Empty the queue
	"""
	if request.method == 'POST':
		json_data = json.loads(request.body)

		try:
			device_id = json_data['device_id']
		except KeyError:
			print "Error: A posted response did not have a JSON object with the required properties"
		else:

			# try sending the updates to the user
			# if this fails in any way (IOError) then make sure the updates
			# are back on the updates stack (else they won't reach the client).
			try:
				print device_id
				all_devices = Device.objects.all()
				device = all_devices.filter(device_id=device_id)[0]
				
				question_updates = QuestionUpdates.remove_updates(device)
				thread_updates = ThreadUpdates.remove_updates(device)
				response_updates = ResponseUpdates.remove_updates(device)
				serializer = Serializer()
				
				serialized_question_updates = serializer.serialize(question_updates)
				
				serialized_thread_updates = serializer.serialize(thread_updates)
				serialized_response_updates = serializer.serialize(response_updates)
				print serialized_question_updates
				
				
				all_updates = '{ "question_updates" : ' + serialized_question_updates + ', "thread_updates" : ' + serialized_thread_updates+ ', "response_updates" : ' + serialized_response_updates+ '}'
							
				return HttpResponse(all_updates, content_type="application/json")
			except IOError:
				# put back all updates into the update stack
				# This doesn't look like it would actually work
				for update in question_updates:
					QuestionUpdates.add_update(device, update)
					
				for update in thread_updates:
					ThreadUpdates.add_update(device, update)

				for update in response_updates:
					ResponseUpdates.add_update(device, update)

				print "Error: failed to send updates to client"