コード例 #1
0
ファイル: tests.py プロジェクト: luisfsantos/LocMessServer
 def test_user_get_message_no_filter(self):
     json = [
         {
             "title": "CasaLuis",
             "text": "Arco do Cego, os parque!!",
             "fromDate": "2017-05-01T18:42:15.703112Z",
             "toDate": "2017-06-01T18:42:15.703122Z",
             "location": {
                 "id": 1
             },
             "whitelist": [],
             "blacklist": []
         },
     ]
     message_serializer = MessageSerializer(data=json, many=True)
     if message_serializer.is_valid():
         m = message_serializer.save(user=self.u)
         messages = UserLocation(
             self.u, {
                 "gps": {
                     "radius": self.location_gps[2],
                     "longitude": self.location_gps[1],
                     "latitude": self.location_gps[0]
                 },
                 "wifi": [{
                     "ssid": "edurom"
                 }],
                 "date": "2017-05-02T18:42:15.703122Z"
             }).getMessages()
         self.assertEqual(len(messages), 1)
         self.assertEqual(messages[0].title, "CasaLuis")
     else:
         self.fail(message_serializer.errors)
コード例 #2
0
ファイル: tests.py プロジェクト: luisfsantos/LocMessServer
 def test_message_creation_from_json(self):
     json = {
         "title": "Arco do Cego",
         "text": "Arco do Cego, os parque!!",
         "fromDate": "2017-05-01T18:42:15.703112Z",
         "toDate": "2017-06-01T18:42:15.703122Z",
         "location": {
             "id": 1
         },
         "whitelist": [{
             "key": "clube",
             "value": "benfica"
         }],
         "blacklist": []
     }
     message_serializer = MessageSerializer(data=json)
     if message_serializer.is_valid():
         m = message_serializer.save(user=self.u)
         self.assertEqual(m.title, "Arco do Cego", "Title matches!")
         self.assertEqual(m.text, "Arco do Cego, os parque!!")
         self.assertEqual(m.author.username, "luissantos")
         for item in m.whitelist.all():
             self.assertEqual(item.key.id, 1)
     else:
         self.fail(message_serializer.errors)
コード例 #3
0
ファイル: test_serializers.py プロジェクト: Tsuribori/rbback
 def test_message_nested(self):
     thread = ThreadFactory()
     message = MessageFactory(thread=thread)
     thread_serializer = ThreadSerializer(instance=thread)
     message_serializer = MessageSerializer(instance=message)
     self.assertEqual(thread_serializer.data['messages'][0],
                      message_serializer.data)
コード例 #4
0
    def master_list(self, request):
        '''
        Endpoint: api/message/
        Use Cases: Get all Message instances
        :param request: HttpRequest object
        :return:
            JsonResponse: all Message instances and status 200
            Http403: status 403 if unauthorized (User requesting not staff/bad token)
        '''
        user_messages = UserMessage.objects.all()
        group_messages = GroupMessage.objects.all()
        user_count = user_messages.count()
        group_count = group_messages.count()

        if user_count > 0 and group_count > 0:
            user_serialized = MessageSerializer(user_messages, many=True if user_count > 1 else False)
            group_serialized = GroupMessageSerializer(group_messages, many=True if group_count > 1 else False)
            return JsonResponse([user_serialized.data, group_serialized.data], safe=False, status=200)
        if user_count > 0:
            user_serialized = UserMessageSerializer(user_messages, many=True if user_count > 1 else False)
            return JsonResponse(user_serialized.data, safe=False, status=200)
        if group_count > 0:
            group_serialized = GroupMessageSerializer(group_messages, many=True if group_count > 1 else False)
            return JsonResponse(group_serialized.data, safe=False, status=200)
        raise Http404
コード例 #5
0
ファイル: views.py プロジェクト: mukuntha-priya/chat-api
def create_thread(request):
    data = json.loads(request.body.decode("utf-8"))
    thread_id = get_new_thread_id()
    message = create_message(data, thread_id)
    original_message_id = data['originalMessageId']
    Message.objects.filter(id=original_message_id).update(thread_id=thread_id)
    serializer = MessageSerializer(message)
    return JsonResponse(serializer.data, safe=False)
コード例 #6
0
 def test_invalid_thread_id_post(self):
     msg = MessageSerializer(instance=MessageFactory())
     data = msg.data.copy()
     data['thread'] = 'Invalid value'
     del data['media']
     data['media'] = MediaFactory().media_id
     resp = self.client.post(reverse('message-list'), data)
     self.assertEqual(resp.status_code, 400)
コード例 #7
0
 def test_thread_closed(self):
     thread = ThreadFactory(closed=True)
     data = MessageSerializer(instance=MessageFactory(
         thread=thread)).data.copy()
     data['thread'] = thread.thread_id
     del data["id"]
     del data["media"]
     resp = self.client.post(reverse('message-list'), data)
     self.assertEqual(resp.status_code, 400)
コード例 #8
0
 def test_no_media_provided_post(self):
     msg = MessageSerializer(instance=MessageFactory())
     thread = ThreadFactory()
     data = msg.data.copy()
     data['thread'] = thread.thread_id
     del data['id']
     del data['media']
     resp = self.client.post(reverse('message-list'), data)
     self.assertEqual(resp.status_code, 201)
コード例 #9
0
ファイル: views.py プロジェクト: ferily7/assignment-2-django
    def get(self, request, format=None, channel_id=0):
        channel_id = self.kwargs['channel_id']
        channels = Channel.objects.filter(id=channel_id)

        messages = Message.objects.filter(id=channel_id)

        channelIdSerializer = ChannelSerializer(channels, many=True)
        messageSerializer = MessageSerializer(messages, many=True)
        return Response(messageSerializer.data)
コード例 #10
0
ファイル: views.py プロジェクト: luisfsantos/LocMessServer
def create_message(request):
    if request.data["data"]:
        message_serializer = MessageSerializer(data=request.data["data"])
        if message_serializer.is_valid():
            m = message_serializer.save(user=request.user)
            return Response(JSONResponse().addData(
                "Message",
                message_serializer.data).addData("status",
                                                 "Message created!").send(),
                            status=status.HTTP_201_CREATED)
        else:
            return Response(JSONResponse().addError(
                0, "Message could not be created").addError(
                    1, message_serializer.errors).send(),
                            status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response(JSONResponse().addError(0,
                                                "No data in request").send(),
                        status=status.HTTP_400_BAD_REQUEST)
コード例 #11
0
    def new_message(cls, message):
        thread = message.thread
        event = cls.MESSAGE
        data = MessageSerializer(message).data
        print "Publish message %s to thread %s " % (message, thread)

        threads_comm.server_publish(
            threads_comm.thread_channel_name(thread),
            event,
            data
        )
コード例 #12
0
ファイル: views.py プロジェクト: mukuntha-priya/chat-api
def get_group_messages(request, group_id):
    last_seen_message = None
    messages = Message.objects.filter(
        group__id=group_id).order_by('-created_at')
    if len(messages) > 0:
        last_seen_message = messages[0]
    history = GroupHistory.objects.filter(group__id=group_id,
                                          user__id=request.GET['user'])
    if len(history) > 0:
        history.update(last_seen_message=last_seen_message)
    else:
        user = User.objects.get(id=request.GET['user'])
        group = Group.objects.get(id=group_id)
        history = GroupHistory(user=user,
                               group=group,
                               last_seen_message=last_seen_message)
        history.save()

    messages = Message.objects.filter(
        group__id=group_id).order_by('created_at')
    serializer = MessageSerializer(messages, many=True)
    return JsonResponse(serializer.data, safe=False)
コード例 #13
0
ファイル: views.py プロジェクト: luisfsantos/LocMessServer
def user_update_location(request):
    if request.data["data"]:
        user_location_serializer = UserLocationSerializer(
            data=request.data['data'])
        if user_location_serializer.is_valid():
            messages = UserLocation(
                request.user,
                user_location_serializer.validated_data).getMessages()
            messages_serializer = MessageSerializer(messages, many=True)
            return Response(JSONResponse().addData(
                "Location", user_location_serializer.data).addData(
                    "Messages", messages_serializer.data).send(),
                            status=status.HTTP_201_CREATED)
        else:
            return Response(JSONResponse().addError(
                0, "User location could not be loaded").addError(
                    1, user_location_serializer.errors).send(),
                            status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response(JSONResponse().addError(0,
                                                "No data in request").send(),
                        status=status.HTTP_400_BAD_REQUEST)
コード例 #14
0
    def create(self, request, **kwargs):
        thread = self._get_message_thread(request, **kwargs)
        logger.debug("Preparing to create a message in thread %r", thread)

        sender = get_user_from_request(request)
        context = {
            'request': request,
            'user': sender,
        }

        data = dict(request.data)

        if thread is not None:
            data['thread'] = thread.pk

        message_serializer = MessageSerializer(data=data, context=context)
        message_serializer.is_valid(raise_exception=True)
        sent_message = message_serializer.save()

        return Response(MessageSerializer(sent_message, context=context).data)
コード例 #15
0
ファイル: views.py プロジェクト: luisfsantos/LocMessServer
def list_messages(request):
    serializer = MessageSerializer(Message.objects.filter(author=request.user),
                                   many=True)
    return Response(JSONResponse().addData("Messages", serializer.data).send(),
                    status=status.HTTP_200_OK)
コード例 #16
0
ファイル: views.py プロジェクト: mukuntha-priya/chat-api
def add_to_thread(request):
    data = json.loads(request.body.decode("utf-8"))
    message = create_message(data, data['threadId'])
    serializer = MessageSerializer(message)
    return JsonResponse(serializer.data, safe=False)
コード例 #17
0
    def handle_channel_message(self, channel, data):
        payload_type = data['type']

        try:
            thread = self._get_thread(channel)
        except ObjectDoesNotExist:
            return

        user = self._get_user()

        if payload_type == 'listening':
            TuneManager.get().tune(user, thread)

        elif payload_type == 'message':
            message_data = data["payload"]

            print "Message"
            print message_data

            try:
                TuneManager.get().tune(user, thread)
            except UnauthorizedAction as unauthorizedAction:
                raise

            tags = message_data.pop("tags", [])

            try:
                sent_message = thread.send(Message(**message_data),
                                           sender=user,
                                           tags=tags)
            except ValueError as valueError:
                raise
            except MessageAlreadySent as alreadySent:
                raise
            except UnauthorizedAction as unauthorizedAction:
                raise
            except IncorrectTags as incorrectTags:
                raise
            except Exception as exception:
                raise

            serializer = MessageSerializer(sent_message,
                                           context={'user': user})
            message_data = serializer.data

            print "Message data"
            print message_data

#            self.publish(channel, "message", message_data)

        elif payload_type == 'message_checked':
            payload = data["payload"]
            seen_date = data.pop("seen_date", timezone.now())

            try:
                checked_message = data.pop("last_message_id")
            except KeyError:
                raise

            Thread.objects.see_thread(user,
                                      thread,
                                      seen_date,
                                      last_seen_message=checked_message)
コード例 #18
0
ファイル: test_serializers.py プロジェクト: Tsuribori/rbback
 def test_thread_write_only(self):
     serializer = MessageSerializer(instance=MessageFactory())
     self.assertFalse('thread' in serializer.data)