Пример #1
0
    def post(request):

        serializer = MessageSerializer(many=False, data=request.data)

        if serializer.is_valid():

            message = serializer.validated_data

            a = Application.objects.get(pk=request.data['application'])

            del message['application']

            message['author_name'] = a.name

            message['thumb_url'] = a.thumb_url

            m = Message(a, message['title'], message['text'], message['color'])

            if Slack.post_message(m):
                return Response(None, status=204)
            else:
                return Response({"error": "Something happened"}, status=500)

        else:
            return Response(serializer.errors, status=400)
Пример #2
0
    def post(self, request):

        serializer = MessageSerializer(data=request.data)
        serializer.is_valid()
        message = serializer.save()
        # 2018-09-29 15:04:34.380000+00:00
        return Response()
Пример #3
0
 def post(self, request, format=None):
     serializer = MessageSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         r = query_dialogflow(serializer.data.get('text'))
         json_response = r.json()
         response = json_response.get('result', {}).get(
             "fulfillment", {}).get("speech", "Je n'ai pas compris...")
         return Response({"speech_answer": response},
                         status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #4
0
def post_user_message(request):
    """
    post ->  dodaje poruku za odredenog usera od usera
    :param request:
    :return:
    """
    if request.method == "POST":
        serializer = MessageSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #5
0
def message_list(request):
    if request.method != 'GET':
        return JsonResponse({'message': 'Method not allowed!'}, status=405)
    if 'conversation' not in request.GET:
        return JsonResponse({'message': 'please send conversation id'},
                            status=400)
    c = Conversation.objects.get(id=request.GET['conversation'])
    messages = Messages.objects.filter(conversation=c)
    s = MessageSerializer(messages, many=True)
    # messages_list = []
    # for m in messages:
    #     messages_list.append(
    #         {
    #             'text': m.text,
    #             'sender': {
    #                 'first_name': m.sender.first_name,
    #                 'last_name': m.sender.last_name,
    #                 'id': m.sender.id
    #             },
    #             'date': m.date,
    #         }
    #     )

    d = {'messages': s.data}
    return JsonResponse(d)
Пример #6
0
    def get(self, request, id):
        try:
            user_id = request.user.id
            user = request.user
        except:
            return Response({"message": "Token is not valid."}, status=status.HTTP_401_UNAUTHORIZED)

        try:
            conversation = Conversation.objects.get(id=id)
        except:
            return Response({"message": "Conversation is not valid."}, status=HTTP_404_NOT_FOUND)

        is_user1 = conversation.user1.id == user_id
        messages = Message.objects.filter(conversation_id=id).order_by('timestamp')
        messageList = []
        for message in messages:
            serializer = MessageSerializer(message).data
            if is_user1:
                message.is_visited_by_user1 = True
                other_user = conversation.user2
                serializer["am_I_user1"] = True
            else:
                message.is_visited_by_user2 = True
                other_user = conversation.user1
                serializer["am_I_user1"] = False
            message.save()
            if is_user1 == message.is_user1:
                serializer = {**serializer, **UserSerializer(user).data}
                serializer["user_id"] = user.id
            else:
                serializer = {**serializer, **UserSerializer(other_user).data}
                serializer["user_id"] = other_user.id
            messageList.append(serializer)
        
        return Response(messageList)
class GroupSerializer(serializers.ModelSerializer):
    group_creator = AuPairUserSerializer()
    group_name = serializers.CharField(max_length=255)
    group_users = AuPairUserSerializer()
    group_chat = MessageSerializer()

    class Meta:
        app_label = 'group'
        model = Group
        fields = '__all__'

    def create(self, validated_data):
        return Group.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.date_created = validated_data.get('date_created',
                                                   instance.date_created)
        instance.group_creator = validated_data.get('group_creator',
                                                    instance.group_creator)
        instance.group_name = validated_data.get('group_name',
                                                 instance.group_name)
        instance.group_users = validated_data.get('group_users',
                                                  instance.group_users)
        instance.group_chat = validated_data.get('group_chat',
                                                 instance.group_chat)
        instance.save()
        return instance
 def get_lastMessage(self, obj):
     lastMessageQS = Message.objects.all().filter(
         chat=obj).order_by('-created')
     if lastMessageQS.exists():
         return MessageSerializer(lastMessageQS[0]).data
     else:
         return 'None'
Пример #9
0
 def test_get_valid_single_message(self):
     response = client.get(
         reverse('single_msg', kwargs={'message_id': self.message1.pk}))
     message = Message.objects.get(pk=self.message1.pk)
     serializer = MessageSerializer(message)
     self.assertEqual(response.data, serializer.data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
Пример #10
0
def see_unapproved(request):

    if request.method == 'GET':
        queryset = Message.objects.filter(approved=False, resolved=False)
        serializer = MessageSerializer(queryset, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)
 def list_messages(self, request, id=None):
     chat = get_object_or_404(self.queryset, id=id)
     serializer = MessageSerializer(
         Message.objects.filter(chat=chat),
         many=True)
     return Response(
         {'chatMessages': {chat.id: serializer.data}},
         status=status.HTTP_200_OK)
Пример #12
0
 def get(self, request):
     s = RequestGetMessageSerializer(data=request.GET)
     if s.is_valid():
         c = Conversation.objects.get(id=request.GET['conversation'])
         messages = Messages.objects.filter(conversation=c)
         s = MessageSerializer(messages, many=True)
         return Response({s.data})
     else:
         return Response(s.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #13
0
 def fetch_messages(self,data):
     
     messages = Message.objects.all().filter(chat__id=data['chat']).order_by('id')
     serializer = MessageSerializer(messages,many=True)
     content = {
         'command': 'messages',
         'messages' : serializer.data
     }
     self.send_message(content)
Пример #14
0
def get_user_unread_messages(request, message_to_user=None):
    """
    vraća sve nepročitane poruke za usera
    :param request:
    :return:
    """
    if request.method == "GET":
        messages = Message.objects.all().filter(message_to_user_id = message_to_user, is_read=False)
        serializer = MessageSerializer(messages, many=True, context={'request':request})
        return Response(serializer.data, status=status.HTTP_200_OK)
Пример #15
0
 def get(self, request):
     message = VipMessage.objects.all()
     serializer = MessageSerializer(message, many=True)
     date_str = serializer.data[0].get("message_time")[:19]
     # date_str = "2016-11-30 13:53:59"
     s = time.strptime(date_str, "%Y-%m-%dT%H:%M:%S")
     # "2016-11-30 13:53:59"
     # time.strftime("%b %d %Y %H:%M:%S", )
     print(type(s), s)
     return Response(serializer.data)
Пример #16
0
def get_user_messages(request, message_to_user=None):
    """
    vraća sve poruke koje su poslane useru
    :param request:
    :return:
    """
    if request.method == "GET":
        messages = Message.objects.all().filter(message_to_user_id = message_to_user )
        serializer = MessageSerializer(messages, many=True, context={'request':request})
        return Response(serializer.data, status=status.HTTP_200_OK)
Пример #17
0
    def post(self, request, **kwargs):
        data = request.DATA

        serializer = MessageSerializer(data=data)

        if serializer.is_valid():
            message = serializer.save()
            sender = message.sender.first_name if message.sender.first_name else message.sender.username

            # Send notification to APNS
            send_push_notification(user=message.receiver,
                                   notification="From {}: {}".format(
                                       sender, message.text),
                                   type="message",
                                   obj_id=message.thread.id)

            return Response(message.to_dict(), status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Пример #18
0
def message_list(request):
    page = request.GET.get('page', 1)
    per_page = request.GET.get('per_page', DEFAULT_MESSAGE_PER_PAGE)

    message_list = Message.objects.order_by('-created').all()
    paginator = Paginator(message_list, per_page)

    messages = paginator.get_page(page)
    serializer = MessageSerializer(messages, many=True)

    return Response(serializer.data)
Пример #19
0
    async def new_message(self, message, user, conversation):
        serializer = MessageSerializer(data={'message': message})
        serializer.context['websocket'] = True
        serializer.context['user'] = user
        serializer.context['conversation'] = conversation

        serializer.is_valid(raise_exception=True)
        await sync_to_async(serializer.save)()

        return serializer.data
Пример #20
0
 def new_message(self,data):
     message = Message(
         content= str(data['message']['content'].replace("\n", " ")),
         contact_id= int(data['message']['contact']),
         chat_id=int(data['message']['chat'])
     )
     message.save()      
     serializer = MessageSerializer(message)
     content = {
         'command': 'new_message',
         'message': serializer.data
     }
     return self.send_chat_message(content)
    def send_message(self, request, id=None):
        chat = get_object_or_404(self.queryset, id=id)
        user = get_object_or_404(Member.objects.all().filter(chat=chat), user=request.user)
        try:
            message = Message(
                user=request.user,
                chat=chat,
                text=request.data['text'],
            )
            message.save()

            serializer = MessageSerializer(message)
            return Response({'message': serializer.data}, status=status.HTTP_200_OK)
        except KeyError:
            return Response({}, status=status.HTTP_400_BAD_REQUEST)
Пример #22
0
    def message(self, request, channel_id=None):
        try:
            channel = ChannelService.get_channel_from_id(channel_id)
        except Channel.DoesNotExist:
            return Response({u'detail': u'channel不存在'},
                            status=status.HTTP_404_NOT_FOUND)

        serializer = ChatSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        content = serializer.validated_data.get('content', '')
        file = serializer.validated_data.get('file', None)
        type = serializer.validated_data['type']

        message = channel.send_message(request.user, type, content, file)
        return Response(MessageSerializer(message).data,
                        status=status.HTTP_200_OK)
Пример #23
0
 def get(self, request):
     try:
         user_id = request.user.id
     except:
         return Response({"message": "Token is not valid."}, status=status.HTTP_401_UNAUTHORIZED)
     conversations = Conversation.objects.filter(user1_id=user_id) | Conversation.objects.filter(user2_id=user_id)
     conversations = conversations.order_by('-last_message_timestamp')
     number_of_unseen = 0
     responseList = []
     for conversation in conversations:
         d = {} 
         d["id"] = conversation.id
         is_user1 = conversation.user1.id == user_id
         messages = Message.objects.filter(conversation_id=conversation.id).order_by('timestamp')
         message = messages[len(messages)-1]
         d["last_message_body"] = message.body
         d["last_message_timestamp"] = message.timestamp
         d["am_I_user1"] = is_user1
         if is_user1:
             d["user_id"] = conversation.user2.id
             d = {**d, **UserSerializer(conversation.user2).data}
             d["is_visited"] = message.is_visited_by_user1
             if not message.is_visited_by_user1:
                 number_of_unseen = number_of_unseen + 1
         else:
             d["user_id"] = conversation.user1.id
             d = {**d, **UserSerializer(conversation.user1).data}
             d["is_visited"] = message.is_visited_by_user2
             if not message.is_visited_by_user2:
                 number_of_unseen = number_of_unseen + 1
         messageList = []
         unseen_message_counter = 0
         for message_ in messages:
             if is_user1 and not message_.is_visited_by_user1:
                 unseen_message_counter = unseen_message_counter + 1
             if not is_user1 and not message_.is_visited_by_user2:
                 unseen_message_counter = unseen_message_counter + 1
             messageList.append(MessageSerializer(message_).data)
         d["new_messages_of_conversation"] = unseen_message_counter
         d["messages"] = messageList
         d["id"] = conversation.id
         responseList.append(d)
     response = {}
     response["new_messages"] = number_of_unseen
     response["conversations"] = responseList
     return Response(response)
Пример #24
0
    def to_representation(self, value):

        if isinstance(value, Post):
            serializer = PostSerializer(value)
        elif isinstance(value, Comment):
            serializer = CommentSerializer(value)
        elif isinstance(value, Like):
            serializer = LikeSerializer(value)
        elif isinstance(value, Blog):
            serializer = BlogSerializer(value)
        elif isinstance(value, Submission):
            serializer = SubmissionSerializer(value)
        elif isinstance(value, Message):
            serializer = MessageSerializer(value)
        else:
            return value.__str__()

        return serializer.data
Пример #25
0
def message_detail(request, pk):
    '''Recebe requisições do tipo GET para recuperar uma mensagem, ou PUT, para atualizar seu estado.

    Caso a requisição seja do tipo PUT (para atualizar mensagem), os únicos estados que se pode alterar é se a mensagem foi lida
    ou recebida.

    Args:
        request: Requisição HTTP do tipo GET ou PUT, para recuperar ou atualizar uma mensagem, respectivamente.
        pk: Primary Key - chave primária da mensagem a ser recuperada ou alterada

    Returns:
        JSon com informações sobre a mensagem recuperada ou alterada, com código HTTP 200
        ou possíveis erros e seus respectivos código HTTP
    '''

    # verifica se a mensagem existe
    try:
        message = Message.objects.get(pk=pk)

    except:
        content = {'error': 'Message not found.'}
        return Response(content, status=status.HTTP_404_NOT_FOUND)

    # caso a requisição seja do tipo GET, a retorna como JSon para o cliente que a requeriu
    if request.method == 'GET':

        #transforma a instância de mensagem em json
        serialized_message = MessageSerializer(message).data
        return Response(serialized_message, status=status.HTTP_200_OK)

    # A requisição é do tipo PUT
    else:

        # request.data é um dicionário que possui os dados a serem alterados da mensagem, o condicional abaixo
        # corrige valores de campos do dicionário vindos como lista (ocorre na biblioteca requests do python)
        if type(request.data) == QueryDict:
            data = request.data.dict()

        else:
            data = request.data

        # verifica se a requisição recebida é para atualizar o estado da mensagem para "read"
        if data.get('read'):
            # registra se a mensagem foi recebida, se necessário
            if not message.received_at:
                message.received_at = timezone.now()

            # registra o horário que a mensagem foi lida
            message.read_at = timezone.now()
            message.save()

            # Notifica ao usuário que enviou a mensagem que seu estado foi atualizado para "lida"
            port = User.objects.get(username=message.sender).port
            notify_user_read(message.id, port)

            # transforma a instância de mensagem em json
            serialized_message = MessageSerializer(message).data
            return Response(serialized_message, status=status.HTTP_200_OK)

        # Mensagens só podem ser atualizadas para "received" ou "read"
        else:
            content = {'error': 'Use this only to update message status for received or read.'}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)
Пример #26
0
 def messages(self, request, pk=None):
     chat = self.get_object()
     response = []
     for message in Message.objects.filter(chat=chat).order_by('date'):
         response.append(MessageSerializer(message).data)
     return Response(response)    
Пример #27
0
    def create(self, data):
        db = DataBase()
        serializer = MessageSerializer(db.save(data))

        return serializer.data