def message_map(request): messages = TalkMessage.getMessages() return render_to_response('geocamTalk/map.html', dict(gc_msg=messages, first_geolocation=get_first_geolocation(messages), timestamp=TalkMessage.getLargestMessageId()), context_instance=RequestContext(request))
def feed_messages(request, recipient_username=None, author_username=None): if not request.user.is_authenticated(): return HttpResponseForbidden() else: timestamp = TalkMessage.getLargestMessageId() if recipient_username is not None: recipient = get_object_or_404(User, username=recipient_username) else: recipient = None if author_username is not None: author = get_object_or_404(User, username=author_username) else: author = None since = request.GET.get("since", None) if since is not None: since_dt = since messages = TalkMessage.getMessages(recipient, author).filter(pk__gt=since_dt) message_count = TalkMessage.getMessages(request.user).filter(pk__gt=since_dt).count() else: messages = TalkMessage.getMessages(recipient, author) message_count = TalkMessage.getMessages(request.user).count() return HttpResponse( json.dumps({"ts": timestamp, "msgCnt": message_count, "ms": [msg.getJson() for msg in messages]}) )
def feed_messages(request, recipient_username=None, author_username=None): if not request.user.is_authenticated(): return HttpResponseForbidden() else: timestamp = TalkMessage.getLargestMessageId() if recipient_username is not None: recipient = get_object_or_404(User, username=recipient_username) else: recipient = None if author_username is not None: author = get_object_or_404(User, username=author_username) else: author = None since = request.GET.get('since', None) if since is not None: since_dt = since messages = TalkMessage.getMessages(recipient, author).filter(pk__gt=since_dt) message_count = TalkMessage.getMessages( request.user).filter(pk__gt=since_dt).count() else: messages = TalkMessage.getMessages(recipient, author) message_count = TalkMessage.getMessages(request.user).count() return HttpResponse( json.dumps({ 'ts': timestamp, 'msgCnt': message_count, 'ms': [msg.getJson() for msg in messages] }))
def test_MyMessageList(self): # arrange ''' This test is attempting to verify that we see messages for specified user or broadcast ''' recipient = User.objects.get(username="******") author = User.objects.all()[1] msg = TalkMessage.objects.create(content='yo dude', content_timestamp=self.now, author=author) msg.recipients.add(recipient) msg.recipients.add(User.objects.all()[2]) time_stamp = TalkMessage.objects.all().order_by('-pk')[0].pk - 2 profile = recipient.profile profile.last_viewed_mymessages = time_stamp profile.save() #self.client.login(username=recipient.username, password='******') #response = self.client.get('/talk/messages/'+recipient_path) # act response = self._get_messages_response(recipient=recipient) expectedMessages = TalkMessage.getMessages(recipient,author=None) # don't pass in author gotMessages = response.context["gc_msg"] # assert self.assertTrue(time_stamp < recipient.profile.last_viewed_mymessages) self.assertEqual(recipient, response.context["recipient"]) self.assertEqual(len(gotMessages), expectedMessages.count(), "My messages response % is not the same size as expected %s" % (len(gotMessages), expectedMessages.count())) for i in range(len(expectedMessages)): self.assertEqual(expectedMessages[i],gotMessages[i], "My messages doesn't contain an expected message: %s" % expectedMessages[i])
def test_MyMessageList(self): # arrange ''' This test is attempting to verify that we see messages for specified user or broadcast ''' recipient = User.objects.get(username="******") author = User.objects.all()[1] msg = TalkMessage.objects.create(content='yo dude', content_timestamp=self.now, author=author) msg.recipients.add(recipient) msg.recipients.add(User.objects.all()[2]) time_stamp = TalkMessage.objects.all().order_by('-pk')[0].pk - 2 profile = recipient.profile profile.last_viewed_mymessages = time_stamp profile.save() #self.client.login(username=recipient.username, password='******') #response = self.client.get('/talk/messages/'+recipient_path) # act response = self._get_messages_response(recipient=recipient) expectedMessages = TalkMessage.getMessages(recipient, author=None) # don't pass in author gotMessages = response.context["gc_msg"] # assert self.assertTrue(time_stamp < recipient.profile.last_viewed_mymessages) self.assertEqual(recipient, response.context["recipient"]) self.assertEqual(len(gotMessages), expectedMessages.count(), "My messages response % is not the same size as expected %s" % (len(gotMessages), expectedMessages.count())) for i in range(len(expectedMessages)): self.assertEqual(expectedMessages[i], gotMessages[i], "My messages doesn't contain an expected message: %s" % expectedMessages[i])
def create_message_json(request): if request.user.is_authenticated(): if request.method == 'POST': jsonstring = request.POST["message"] messageDict = json.loads(jsonstring) messageDict["userId"] = request.user.pk message = TalkMessage.fromJson(messageDict) if "audio" in request.FILES: filename = "%s%s.mp4" % ( message.author, message.content_timestamp.strftime("%H%M%S")) file_content = ContentFile(request.FILES['audio'].read()) file_format = os.path.splitext(request.FILES['audio'].name)[-1] message.audio_file.save(filename, file_content) try: print message message.save() print "SAVED" message.push_to_phone(False) print "PUSHED" return HttpResponse( json.dumps({ "messageId": "%s" % message.pk, "authorFullname": message.get_author_string(), "audioUrl": message.get_audio_url() }), 200) except: return HttpResponseServerError( ) # TODO: change the tests and here to respond with HttpResponseBadRequest else: return HttpResponseServerError() else: return HttpResponseForbidden()
def create_message_json(request): if request.user.is_authenticated(): if request.method == 'POST': jsonstring = request.POST["message"] messageDict = json.loads(jsonstring) messageDict["userId"] = request.user.pk message = TalkMessage.fromJson(messageDict) if "audio" in request.FILES: filename = "%s%s.mp4" % (message.author, message.content_timestamp.strftime("%H%M%S")) file_content = ContentFile(request.FILES['audio'].read()) _file_format = os.path.splitext(request.FILES['audio'].name)[-1] message.audio_file.save(filename, file_content) try: print message message.save() print "SAVED" message.push_to_phone(False) print "PUSHED" return HttpResponse(json.dumps( {"messageId": "%s" % message.pk, "authorFullname": message.get_author_string(), "audioUrl": message.get_audio_url() }), 200) except: # pylint: disable=W0702 return HttpResponseServerError() # TODO: change the tests and here to respond with HttpResponseBadRequest else: return HttpResponseServerError() else: return HttpResponseForbidden()
def testEnsureLastViewedMyMessages(self): # arrange user = User.objects.all()[0] latestmsgId = TalkMessage.getLargestMessageId() profile = user.profile # act profile.last_viewed_mymessages = latestmsgId profile.save() # assert self.assertEquals(latestmsgId, user.profile.last_viewed_mymessages)
def get_messages(request, recipient_username=None, author_username=None): timestamp = TalkMessage.getLargestMessageId() if recipient_username is not None: recipient = get_object_or_404(User, username=recipient_username) else: recipient = None if author_username is not None: author = get_object_or_404(User, username=author_username) else: author = None since = request.GET.get('since', None) if since is not None: since_dt = since messages = TalkMessage.getMessages(recipient, author).filter(pk__gt=since_dt) message_count = TalkMessage.getMessages(recipient).filter(pk__gt=since_dt).count() else: messages = TalkMessage.getMessages(recipient, author) message_count = TalkMessage.getMessages(recipient).count() return timestamp, messages, message_count
def testMessageListAudioPresent(self): # arrange _author = User.objects.all()[2] recipient = User.objects.all()[1] response = self.get_recipient_messages_response(recipient) recipient_messages = TalkMessage.getMessages(recipient) # act geocount = 0 for m in recipient_messages.all(): if m.audio_file: geocount += 1 # assert self.assertContains(response, 'class="media"', geocount)
def testEnsureMyMessagesAreFilteredByAuthor(self): # arrange author = User.objects.all()[0] recipient = User.objects.all()[2] recipient_messages_from_author_or_broadcast = TalkMessage.getMessages(recipient, author) # act response = self.get_recipient_messages_response_filtered_by_author(recipient, author) # assert self.assertEqual(200, response.status_code) for m in recipient_messages_from_author_or_broadcast: self.assertContains(response, m.content)
def test_MyMessageJsonFeed(self): ''' This test is attempting to verify that we see messages for specified user or broadcast ''' author = User.objects.get(username="******") self.client.login(username=author.username, password='******') ordered_messages = TalkMessage.getMessages(recipient=author).order_by("-pk") messageid = ordered_messages[0].pk - 1 response = self.client.get(reverse("talk_message_list_author_json", args=[author.username])+ '?since=%s' % messageid) self.assertContains(response, '"messageId": %s' % ordered_messages[0].pk) for msg in ordered_messages[1:]: self.assertNotContains(response, '"messageId": %s' % msg.pk)
def testEnsureMyMessageListAuthorLinksPresent(self): author = User.objects.all()[2] recipient = User.objects.all()[1] #arrange recipient_messages = TalkMessage.getMessages(recipient, author) #act response = self.get_recipient_messages_response(recipient) #assert for _ in recipient_messages: link_to_recipient_msgs_from_author = 'href="FIXME/messages/%s/%s"' % (recipient.username, author.username) #print 'didnt find %s in %s' % (link_to_recipient_msgs_from_author, response) self.assertContains(response, link_to_recipient_msgs_from_author)
def testEnsureMyMessageListAuthorLinksPresent(self): author = User.objects.all()[2] recipient = User.objects.all()[1] #arrange recipient_messages = TalkMessage.getMessages(recipient, author) #act response = self.get_recipient_messages_response(recipient) #assert for _ in recipient_messages: link_to_recipient_msgs_from_author = 'href="FIXME/messages/%s/%s"' % ( recipient.username, author.username) #print 'didnt find %s in %s' % (link_to_recipient_msgs_from_author, response) self.assertContains(response, link_to_recipient_msgs_from_author)
def test_MyMessageJsonFeed(self): ''' This test is attempting to verify that we see messages for specified user or broadcast ''' author = User.objects.get(username="******") self.client.login(username=author.username, password='******') ordered_messages = TalkMessage.getMessages(recipient=author).order_by("-pk") messageid = ordered_messages[0].pk - 1 response = self.client.get(reverse("geocamTalk_message_list_author_json", args=[author.username]) + '?since=%s' % messageid) self.assertContains(response, '"messageId": %s' % ordered_messages[0].pk) for msg in ordered_messages[1:]: self.assertNotContains(response, '"messageId": %s' % msg.pk)
def message_list(request, recipient_username=None, author_username=None): timestamp = TalkMessage.getLargestMessageId() if recipient_username is not None: recipient = get_object_or_404(User, username=recipient_username) else: recipient = None if author_username is not None: author = get_object_or_404(User, username=author_username) else: author = None if recipient is not None and recipient.pk == request.user.pk and author is None: profile = recipient.profile profile.last_viewed_mymessages = timestamp profile.save() return render_to_response('geocamTalk/message_list.html', dict(gc_msg=TalkMessage.getMessages(recipient, author), recipient=recipient, author=author, timestamp=timestamp), context_instance=RequestContext(request))
def testEnsureMyMessagesAreFilteredByAuthor(self): # arrange author = User.objects.all()[0] recipient = User.objects.all()[2] recipient_messages_from_author_or_broadcast = TalkMessage.getMessages( recipient, author) # act response = self.get_recipient_messages_response_filtered_by_author( recipient, author) # assert self.assertEqual(200, response.status_code) for m in recipient_messages_from_author_or_broadcast: self.assertContains(response, m.content)
def test_NewMessageCountJsonFeed(self): author = User.objects.get(username="******") self.client.login(username=author.username, password='******') # need to cast the query set to a list here to avoid the dynamic update # when we create the new msg #old_messages = list(TalkMessage.getMessages()) before_new_message = TalkMessage.getLargestMessageId() recipient = User.objects.get(username="******") msg = TalkMessage.objects.create(content='This is a new message', content_timestamp=datetime.now(), author=author) msg.recipients.add(recipient) msg.recipients.add(User.objects.all()[2]) msg.save() response = self.client.get(reverse("geocamTalk_message_list_author_json", args=[author.username]) + '?since=%s' % before_new_message) self.assertContains(response, '"msgCnt": 1')
def test_NewMessageCountJsonFeed(self): author = User.objects.get(username="******") self.client.login(username=author.username, password='******') # need to cast the query set to a list here to avoid the dynamic update # when we create the new msg #old_messages = list(TalkMessage.getMessages()) before_new_message = TalkMessage.getLargestMessageId() recipient = User.objects.get(username="******") msg = TalkMessage.objects.create(content='This is a new message', content_timestamp=datetime.now(), author=author) msg.recipients.add(recipient) msg.recipients.add(User.objects.all()[2]) msg.save() response = self.client.get(reverse("talk_message_list_author_json", args=[author.username])+ '?since=%s' % before_new_message) self.assertContains(response, '"msgCnt": 1')
def testEnsureFromJsonCreatesMessage(self): #arrange now = datetime.now() year = now.strftime("%Y") month = now.strftime("%m") day = now.strftime("%d") hour = now.strftime("%H") minutes = now.strftime("%H") sec = now.strftime("%H") timestamp = datetime(int(year), int(month), int(day), int(hour), int(minutes), int(sec)) message = dict(userId=User.objects.all()[0].pk, content="Sting!!!", contentTimestamp=time.mktime(timestamp.timetuple()) * 1000, latitude=1.1, longitude=222.2, accuracy=60) audioFile = 'media/geocamTalk/test/%s/%s/%s/test_ensure_from_json.mp4' % ( year, month, day) self._createFile(filename=audioFile, filesize=100 * 1024) f = open(audioFile, "rb") #act talkMessage = TalkMessage.fromJson(message) talkMessage.audio_file.save(f.name, ContentFile(f.read())) talkMessage.save() #assert self.assertEqual(talkMessage.author.pk, User.objects.all()[0].pk) self.assertEqual(talkMessage.content, "Sting!!!") self.assertEqual(talkMessage.content_timestamp, timestamp) self.assertEqual(talkMessage.latitude, 1.1) self.assertEqual(talkMessage.longitude, 222.2) self.assertEqual(talkMessage.accuracy, 60) self.assertTrue(talkMessage.has_audio()) self.assertEqual(os.path.basename(talkMessage.audio_file.name), os.path.basename(f.name)) f.close() self._clean_test_files(audioFile)
def testEnsureFromJsonCreatesMessage(self): #arrange now = datetime.now() year = now.strftime("%Y") month = now.strftime("%m") day = now.strftime("%d") hour = now.strftime("%H") minutes = now.strftime("%H") sec = now.strftime("%H") timestamp = datetime(int(year), int(month), int(day), int(hour), int(minutes), int(sec)) message = dict( userId=User.objects.all()[0].pk, content="Sting!!!", contentTimestamp=time.mktime(timestamp.timetuple()) * 1000, latitude=1.1, longitude=222.2, accuracy=60) audioFile = 'media/geocamTalk/test/%s/%s/%s/test_ensure_from_json.mp4' % (year, month, day) self._createFile(filename=audioFile, filesize=100 * 1024) f = open(audioFile, "rb") #act talkMessage = TalkMessage.fromJson(message) talkMessage.audio_file.save(f.name, ContentFile(f.read())) talkMessage.save() #assert self.assertEqual(talkMessage.author.pk, User.objects.all()[0].pk) self.assertEqual(talkMessage.content, "Sting!!!") self.assertEqual(talkMessage.content_timestamp, timestamp) self.assertEqual(talkMessage.latitude, 1.1) self.assertEqual(talkMessage.longitude, 222.2) self.assertEqual(talkMessage.accuracy, 60) self.assertTrue(talkMessage.has_audio()) self.assertEqual(os.path.basename(talkMessage.audio_file.name), os.path.basename(f.name)) f.close() self._clean_test_files(audioFile)
def test_submitFormToCreateMessageWithRecipients(self): """ submit the Talk Message through the form """ msgCnt = TalkMessage.objects.all().count() content = "Whoa man, that burning building almost collapsed on me!" author = User.objects.get(username="******") self.client.login(username=author.username, password='******') recipienta = User.objects.all()[1] recipientb = User.objects.all()[2] response = self.client.post(reverse("geocamTalk_create_message"), data={"content": content, "latitude": GeocamTalkMessageSaveTest.cmusv_lat, "longitude": GeocamTalkMessageSaveTest.cmusv_lon, "author": author.pk, "recipients": [recipienta.pk, recipientb.pk]}) # should be redirected when form post is successful: self.assertEqual(response.status_code, 302, "submitFormToCreateMessage Failed") newMsgCnt = TalkMessage.objects.all().count() self.assertEqual(msgCnt + 1, newMsgCnt, "Creating a Talk Message through view Failed.") newMsg = TalkMessage.getMessages()[0] self.assertEqual(newMsg.recipients.all().count(), 2, "Different number of recipients than expected")
def test_submitFormToCreateMessageWithRecipients(self): """ submit the Talk Message through the form """ msgCnt = TalkMessage.latest.all().count() content = "Whoa man, that burning building almost collapsed on me!" author = User.objects.get(username="******") self.client.login(username=author.username, password='******') recipienta = User.objects.all()[1] recipientb = User.objects.all()[2] response = self.client.post(reverse("talk_create_message"), data={"content":content, "latitude":GeocamTalkMessageSaveTest.cmusv_lat, "longitude":GeocamTalkMessageSaveTest.cmusv_lon, "author":author.pk, "recipients":[recipienta.pk, recipientb.pk]}) # should be redirected when form post is successful: self.assertEqual(response.status_code, 302, "submitFormToCreateMessage Failed") newMsgCnt = TalkMessage.latest.all().count() self.assertEqual(msgCnt + 1, newMsgCnt, "Creating a Talk Message through view Failed.") newMsg = TalkMessage.getMessages()[0] self.assertEqual(newMsg.recipients.all().count(), 2, "Different number of recipients than expected")
def handle(self, *args, **options): username = None if(len(args)): username = args[0] user = None recipients = [] unames = None try: user = User.objects.get(username=username) args = args[1:] if args: unames = args[1].split(",") for uname in unames: recipients.push(User.objects.get(username=uname)) except: # pylint: disable=W0702 users = User.objects.all() user = users[random.randrange(0, len(users) - 1)] if(not unames): recipients = list(User.objects.all()) random.shuffle(recipients) recipients = recipients[0:random.randrange(0, len(recipients) - 1)] messageContent = " ".join(args) if not args: messageContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec elit erat, porttitor sed tempor id, eleifend et diam. Mauris quam libero, tristique non fringilla nec, suscipit ac mauris. Curabitur sed lacus et ipsum vestibulum suscipit sed a neque. Nullam sed ipsum vitae nisi imperdiet egestas nec a nisi. Mauris pulvinar massa in felis dapibus tempus. Donec in nulla tellus, vel venenatis augue. Duis nisi tellus, vehicula at egestas et, laoreet vitae quam. Ut ullamcorper fermentum facilisis. Sed dapibus odio a mi congue interdum dapibus urna placerat. Vestibulum faucibus metus sed justo convallis mollis. Mauris lorem mauris, blandit eget faucibus nec, feugiat non risus.".split() random.shuffle(messageContent) messageContent = " ".join(messageContent[0:random.randrange(10, 30)]) contenttimestamp = datetime.now() msg = TalkMessage() msg.content_timestamp = contenttimestamp msg.content = messageContent msg.author = user cmusvlat = 37.41029 cmusvlon = -122.05944 msg.latitude = cmusvlat + (random.random() - 0.5) * 0.02 msg.longitude = cmusvlon + (random.random() - 0.5) * 0.02 msg.accuracy = random.randrange(0, 120) msg.save() msg.recipients = recipients msg.push_to_phone(True) print msg
def clear_messages(request): profile = request.user.profile profile.last_viewed_mymessages = TalkMessage.getLargestMessageId() profile.save() return HttpResponse(json.dumps({'ts': TalkMessage.getLargestMessageId()}))
def clear_messages(request): profile = request.user.profile profile.last_viewed_mymessages = TalkMessage.getLargestMessageId() profile.save() return HttpResponse(json.dumps({"ts": TalkMessage.getLargestMessageId()}))
def handle(self, *args, **options): username = None if (len(args)): username = args[0] user = None recipients = [] unames = None try: user = User.objects.get(username=username) args = args[1:] if args: unames = args[1].split(",") for uname in unames: recipients.push(User.objects.get(username=uname)) except: # pylint: disable=W0702 users = User.objects.all() user = users[random.randrange(0, len(users) - 1)] if (not unames): recipients = list(User.objects.all()) random.shuffle(recipients) recipients = recipients[0:random.randrange(0, len(recipients) - 1)] messageContent = " ".join(args) if not args: messageContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec elit erat, porttitor sed tempor id, eleifend et diam. Mauris quam libero, tristique non fringilla nec, suscipit ac mauris. Curabitur sed lacus et ipsum vestibulum suscipit sed a neque. Nullam sed ipsum vitae nisi imperdiet egestas nec a nisi. Mauris pulvinar massa in felis dapibus tempus. Donec in nulla tellus, vel venenatis augue. Duis nisi tellus, vehicula at egestas et, laoreet vitae quam. Ut ullamcorper fermentum facilisis. Sed dapibus odio a mi congue interdum dapibus urna placerat. Vestibulum faucibus metus sed justo convallis mollis. Mauris lorem mauris, blandit eget faucibus nec, feugiat non risus.".split( ) random.shuffle(messageContent) messageContent = " ".join( messageContent[0:random.randrange(10, 30)]) contenttimestamp = datetime.now() msg = TalkMessage() msg.content_timestamp = contenttimestamp msg.content = messageContent msg.author = user cmusvlat = 37.41029 cmusvlon = -122.05944 msg.latitude = cmusvlat + (random.random() - 0.5) * 0.02 msg.longitude = cmusvlon + (random.random() - 0.5) * 0.02 msg.accuracy = random.randrange(0, 120) msg.save() msg.recipients = recipients msg.push_to_phone(True) print msg