Exemple #1
0
 def create_chat(self, sender_id, thread_id, text):
     serializer = ChatSerializer(data={
         'sender': sender_id,
         'thread': thread_id,
         'text': text
     },
                                 context={'sender': self.sender})
     if serializer.is_valid():
         serializer.save()
         # return json.dumps({"messsage" : serializer.data})
         return json.dumps(serializer.data)
         # return text
     return serializer.errors
Exemple #2
0
    def post(self, request):
        data = {**request.data, **{'sender': request.user.user_token}}
        serializer = ChatSerializer(data=data)

        if serializer.is_valid():
            chat = serializer.save()
            message = chat.sender.username + ': ' + chat.message
            send_push_message(token=chat.receiver.device_token,
                              message=message,
                              notification_type='message-received',
                              data=ChatSerializer(chat).data)
            return Response(status=status.HTTP_200_OK)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)
Exemple #3
0
    def add_member(self, request, username, pk=None):
        """
        Adds user by username to a specified by id chat

        :param request:
        :param username:
        :param pk:
        :return:
        """
        try:
            user = User.objects.get(username=username)
            chat = self.get_object()
        except User.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        except Chat.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        if chat.is_member(user):
            return Response(data={"errors": ["User is already in the chat"]},
                            status=status.HTTP_409_CONFLICT)
        try:
            membership = Membership.objects.get(user=user, chat=chat)
            if membership.is_banned:
                return Response(data={
                    "errors": ["User is not in the chat. User is banned."]
                },
                                status=status.HTTP_409_CONFLICT)
        except Membership.DoesNotExist:
            pass
        if chat.is_dialog:
            return Response(data={"errors": ["Chat is a dialog"]},
                            status=status.HTTP_405_METHOD_NOT_ALLOWED)
        chat.users.add(user)
        chat.save()
        return Response(ChatSerializer(chat).data)
Exemple #4
0
 def chats(self, request, pk=None):
     user = self.get_object()
     response = []
     for chat in get_objects_for_user(user,
                                      'chat.view_chat').order_by('-date'):
         response.append(ChatSerializer(chat).data)
     return Response(response)
Exemple #5
0
    def unban_member(self, request, username, pk=None):
        """
        Unbans user by username in the specified by id chat

        :param request:
        :param username:
        :param pk:
        :return:
        """
        try:
            user = User.objects.get(username=username)
            chat = self.get_object()
        except User.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        except Chat.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        if chat.creator != request.user:
            return Response(status=status.HTTP_403_FORBIDDEN)
        if chat.is_dialog:
            return Response(data={"errors": ["Chat is a dialog"]},
                            status=status.HTTP_405_METHOD_NOT_ALLOWED)
        if not chat.is_member(user):
            return Response(data={"errors": ["User is not in the chat"]},
                            status=status.HTTP_409_CONFLICT)
        if chat.creator == user:
            return Response(data={"errors": ["User is the owner of the chat"]},
                            status=status.HTTP_409_CONFLICT)
        membership = Membership.objects.get(user=user, chat=chat)
        membership.is_banned = False
        membership.save()
        return Response(ChatSerializer(chat).data)
Exemple #6
0
    def delete_member(self, request, pk=None):
        """
        Deletes current user from the specified by id chat

        :param request:
        :param pk:
        :return:
        """
        try:
            chat = self.get_object()
        except User.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        except Chat.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        if chat.is_dialog:
            return Response(data={"errors": ["Chat is a dialog"]},
                            status=status.HTTP_405_METHOD_NOT_ALLOWED)

        if chat.creator == request.user:
            return Response(data={
                "errors":
                ["User is the owner of the chat. Chat may be deleted."]
            },
                            status=status.HTTP_409_CONFLICT)
        membership = Membership.objects.get(user=request.user, chat=chat)
        if membership.is_banned:
            return Response(
                data={"errors": ["User is not in the chat. User is banned."]},
                status=status.HTTP_409_CONFLICT)

        chat.users.remove(request.user)
        chat.save()
        return Response(ChatSerializer(chat).data)
Exemple #7
0
def view_msg(request):
    if request.method == 'POST':
        data={
            'status': 'true',
            'data': ChatSerializer(Chat.objects.filter(Q(receiver=request.data['sender'],sender=request.data['receiver']) | Q(receiver=request.data['receiver'],sender=request.data['sender'])), many=True).data
        }
        return Response(data, status=status.HTTP_200_OK)
Exemple #8
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)
Exemple #9
0
def get_chat(request):
    if request.method == 'POST':
        time=datetime.datetime.now(tz=timezone.utc)- datetime.timedelta(seconds=150)
        data={
            'status': 'true',
            'data': ChatSerializer(Chat.objects.filter(time__gte=time,receiver=request.data['sender']), many=True).data
        }
        return Response(data, status=status.HTTP_200_OK)
def chat_details(request, value):

    try:
        chat = Chat.objects.get(id=value)
    except Chat.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = ChatSerializer(chat)
        return JsonResponse(serializer.data, safe=False, status=200)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = ChatSerializer(chat, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=200)
        return JsonResponse(serializer.errors, status=204)

    elif request.method == 'DELETE':
        try:
            chat.delete()
            return HttpResponse(status=200)
        except:
            return HttpResponse(status=409)
Exemple #11
0
 def list(self, request):
     '''
         Get a list of chats available for current user
         Can chat only with matched users
     '''
     profile = Profile.objects.get(user=request.user)
     chats = Chat.objects.filter(Q(user1=profile) | Q(user2=profile))
     serializer = ChatSerializer(chats, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #12
0
    def get(self, request, user_id):
        this = request.user.user_token
        that = user_id

        sent = Chat.objects.filter(sender_id=this,
                                   receiver_id=that).order_by('time')
        received = Chat.objects.filter(sender_id=that,
                                       receiver_id=this).order_by('time')

        return Response(ChatSerializer(sent | received, many=True).data,
                        status=status.HTTP_200_OK)
    def join_chat(self, request, id=None):
        chat = get_object_or_404(self.queryset, id=id)

        if not Member.objects.all().filter(chat=chat, user=request.user).exists():
            member = Member(
                chat=chat,
                user=request.user,
            )
            member.save()
        
        serializer = ChatSerializer(chat)
        return Response({'chats': {serializer.data['id']: serializer.data}}, status=status.HTTP_200_OK)
    def list_chats(self, request):
        chats = Member.objects.all().filter(user=request.user).values('chat').distinct()
        chats_id = [entry['chat'] for entry in chats]

        serializer = ChatSerializer(
            self.queryset.filter(id__in=chats_id),
            many=True)

        data = {entry['id']: entry for entry in serializer.data}

        return Response(
            {'chats': data},
            status=status.HTTP_200_OK)
Exemple #15
0
    def upload_image(self, request, pk=None):
        """
        Adds image to specified by id chat

        :param request:
        :param pk:
        :return:
        """
        try:
            chat = self.get_object()
        except Chat.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        self.post_cloudinary(request, chat)
        return Response(ChatSerializer(chat).data)
Exemple #16
0
def chat_list(request):
    if request.method == 'GET':
        chats = Chat.objects.all()
        serializer = ChatSerializer(chats, many=True)
        return JsonResponse(serializer.data, safe=False, status=200)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = ChatSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=204)
Exemple #17
0
    def create_private_chat(self, request, username):
        """
         get: Returns private chats related to user by username
        post: Creates private chat for specified user by its username

        :param request:
        :param username:
        :return:
        """
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        us1 = username
        us2 = request.user.username
        chats = Chat.objects.filter(
            Q(name=f'{us1}-{us2}')
            | Q(name=f'{us2}-{us1}') & Q(is_dialog=True))
        if chats.exists():
            if request.method == 'POST':
                return Response(data={
                    "errors": ["Chat is already existed"],
                    "data": ChatSerializer(chats, many=True).data
                },
                                status=status.HTTP_409_CONFLICT)
            elif request.method == 'GET':
                return Response(ChatSerializer(chats, many=True).data)
        if request.method == 'POST':
            chat = Chat.objects.create(name=f'{us1}-{us2}',
                                       creator=request.user,
                                       is_dialog=True)
            chat.users.add(user)
            chat.save()
            return Response(ChatSerializer(chat).data)
        elif request.method == 'GET':
            return Response(status=status.HTTP_404_NOT_FOUND)
Exemple #18
0
def sendChatPushNotification(user, message):
    device = FCMDevice.objects.filter(user__id=user.id).first()

    if not device is None:
        serializer = ChatSerializer(message)

        json_r = json.dumps(serializer.data)
        json_r = json.loads(json_r)

        info = {}

        info["data"] = {}
        info["data"]["messages"] = []
        info["data"]["message_sent"] = json_r

        info["message"] = ""
        info["type"] = ""
        info["title"] = ""
        info["success"] = True
        info["number"] = 1
        info["extra"] = 0

        response = json.dumps(info)

        title = str(message.user).join(_(" sent a message"))

        simple_notify = textwrap.shorten(strip_tags(message.text),
                                         width=30,
                                         placeholder="...")

        if message.image:
            simple_notify += " ".join(_("[Photo]"))

        device.send_message(
            title=str(message.user),
            body=simple_notify,
            data={
                "response": response,
                "title": title,
                "body": simple_notify,
                "user_from": message.user.email,
                "user_name": str(message.user),
                "user_img": message.user.image_url,
                "type": "chat",
                "click_action": "FLUTTER_NOTIFICATION_CLICK",
            },
        )
Exemple #19
0
    def chats(self, request, pk=None):
        """
        /api/users/<id>/chats/
            GET - Returns a list of chats associated with the user
        /api/users/<id>/chats/<id>
            POST - Creates a new chat with the users sent in the body
        """

        user = self.get_object()
        if request.method == 'GET':
            chats = Chat.objects.filter(users=user)
            context = {'request': request}
            serializer = ChatSerializer(chats, many=True, context=context)
            return Response(serializer.data)
        if request.method == 'POST':
            serializer = ChatSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response(serializer.data, status=201)
Exemple #20
0
    def retrieve(self, request, *args, **kwargs):
        chat = self.get_object()

        if READ_ALL_MESSAGES_RETRIEVE_CHAT:
            read_messages(request.user, chat)

        chat_serializer = ChatSerializer(chat, context={'request': request})
        queryset = chat.messages.all()
        page = self.paginate_queryset(queryset)
        if page is not None:
            message_serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(
                message_serializer.data,
                chat_serializer.data,
            )

        serializer = self.get_serializer(queryset, many=True)
        return response.Response(serializer.data)
    def create_chat(self, request):
        user=request.user
        try:
            chat = Chat(
                creator=request.user,
                chat_label=request.data['chat_label'],)
            chat.save()

            member = Member(
                chat=chat,
                user=request.user,
            )
            member.save()

            serializer = ChatSerializer(chat)
            return Response({'chats': {serializer.data['id']: serializer.data}}, status=status.HTTP_200_OK)
        except KeyError:
            return Response({}, status=status.HTTP_400_BAD_REQUEST)
Exemple #22
0
 def get_chat(self, thread_id):
     chat = Thread.objects.get(id=thread_id).messages
     serializer = ChatSerializer(chat,
                                 many=True,
                                 context={'sender': self.sender})
     return json.dumps({"messages": serializer.data})
Exemple #23
0
	def get_messages(self, request):
		username = request.data['email']
		user_two = request.data['user_two']
		n_page = int(request.data['page'])
		messages_by_page = int(request.data['page_size'])
		#messages_by_page = 15

		user = User.objects.get(email = username)

		messages = None

		response = ""

		if not user_two == "":
			user2 = User.objects.get(email = user_two)

			messages = TalkMessages.objects.filter((Q(talk__user_one__email = username) & Q(talk__user_two__email = user_two)) | (Q(talk__user_one__email = user_two) & Q(talk__user_two__email = username))).order_by('-create_date')

			ChatVisualizations.objects.filter(Q(user = user) & Q(message__talk__user_two__email = user_two) & Q(viewed = False)).update(viewed = True)

			page = []

			for i in range(messages_by_page*(n_page - 1), (n_page*messages_by_page)):
				if i >= messages.count():
					break;
				else:
					page.append(messages[i])

			serializer = ChatSerializer(page, many = True, context = {"request_user": user})

			json_r = json.dumps(serializer.data)
			json_r = json.loads(json_r)
			
			info = {}

			info["data"] = {}
			info["data"]["messages"] = json_r
			info["data"]["message_sent"] = {}

			info["message"] = ""
			info["type"] = ""
			info["title"] = ""
			info["success"] = True
			info["number"] = 1
			info['extra'] = 0

			response = json.dumps(info)

			try:
				talk = Conversation.objects.get((Q(user_one__email = username) & Q(user_two__email = user_two)) | (Q(user_two__email = username) & Q(user_one__email = user_two)))
				self.log_context['talk_id'] = talk.id
			except Conversation.DoesNotExist:
				pass
			
			self.log_context['user_id'] = user2.id
			self.log_context['user_name'] = str(user2)
			self.log_context['user_email'] = user_two

			super(ChatViewset, self).createLog(user, self.log_component, self.log_action, self.log_resource, self.log_context)

		return HttpResponse(response)
Exemple #24
0
    def send_message(self, request):
        self.log_action = "send"
        self.log_resource = "message"
        self.log_context = {}

        if "file" in request.data:
            file = request.FILES["file"]

            data = json.loads(request.data["data"])

            username = data["email"]
            user_two = data["user_two"]
            subject = data["subject"]
            msg_text = data["text"]
            create_date = data["create_date"]
        else:
            file = None
            data = (
                request.data
                if request.data
                else json.loads(request.body.decode("utf-8"))
            )
            username = data["email"]
            user_two = data["user_two"]
            subject = data["subject"]
            msg_text = data["text"]
            create_date = data["create_date"]

        info = {}

        if not user_two == "" and not username == "":
            user = User.objects.get(email=username)
            user_to = User.objects.get(email=user_two)

            talks = Conversation.objects.filter(
                (Q(user_one__email=username) & Q(user_two__email=user_two))
                | (Q(user_two__email=username) & Q(user_one__email=user_two))
            )

            if talks.count() > 0:
                talk = talks[0]
            else:
                talk = Conversation()
                talk.user_one = user
                talk.user_two = user_to

                talk.save()

            if subject != "":
                subject = Subject.objects.get(slug=subject)
                space = subject.slug
                space_type = "subject"

                self.log_context["subject_id"] = subject.id
                self.log_context["subject_slug"] = space
                self.log_context["subject_name"] = subject.name
            else:
                subject = None
                space = 0
                space_type = "general"

            message = TalkMessages()
            message.text = "<p>" + msg_text + "</p>"
            message.user = user
            message.talk = talk
            message.subject = subject

            if not file is None:
                message.image = file

            message.save()

            self.log_context["talk_id"] = talk.id
            self.log_context["user_id"] = user_to.id
            self.log_context["user_name"] = str(user_to)
            self.log_context["user_email"] = user_two

            if not message.pk is None:
                simple_notify = textwrap.shorten(
                    strip_tags(message.text), width=30, placeholder="..."
                )

                notification = {
                    "type": "chat",
                    "subtype": space_type,
                    "space": space,
                    "user_icon": message.user.image_url,
                    "notify_title": str(message.user),
                    "simple_notify": simple_notify,
                    "view_url": reverse(
                        "chat:view_message", args=(message.id,), kwargs={}
                    ),
                    "complete": render_to_string(
                        "chat/_message.html", {"talk_msg": message}, request
                    ),
                    "container": "chat-" + str(message.user.id),
                    "last_date": _("Last message in %s")
                    % (
                        formats.date_format(
                            message.create_date, "SHORT_DATETIME_FORMAT"
                        )
                    ),
                }

                notification = json.dumps(notification)

                Group("user-%s" % user_to.id).send({"text": notification})

                ChatVisualizations.objects.create(
                    viewed=False, message=message, user=user_to
                )

                serializer = ChatSerializer(message)

                json_r = json.dumps(serializer.data)
                json_r = json.loads(json_r)

                info["data"] = {}
                info["data"]["message_sent"] = json_r

                info["message"] = _("Message sent successfully!")
                info["success"] = True
                info["number"] = 1

                sendChatPushNotification(user_to, message)

                super(ChatViewset, self).createLog(
                    user,
                    self.log_component,
                    self.log_action,
                    self.log_resource,
                    self.log_context,
                )
            else:
                info["message"] = _("Error while sending message!")
                info["success"] = False
                info["number"] = 0
        else:
            info["data"] = {}
            info["data"]["message_sent"] = {}

            info["message"] = _("No information received!")
            info["success"] = False
            info["number"] = 0

        info["data"]["messages"] = []
        info["type"] = ""
        info["title"] = _("Amadeus")
        info["extra"] = 0

        response = json.dumps(info)

        return HttpResponse(response)
Exemple #25
0
    def get_messages(self, request):
        json_data = (
            request.data if request.data else json.loads(request.body.decode("utf-8"))
        )

        username = json_data["email"]
        user_two = json_data["user_two"]
        n_page = int(json_data["page"])
        messages_by_page = int(json_data["page_size"])

        user = User.objects.get(email=username)

        messages = None

        response = ""

        if not user_two == "":
            user2 = User.objects.get(email=user_two)

            messages = TalkMessages.objects.filter(
                (Q(talk__user_one__email=username) & Q(talk__user_two__email=user_two))
                | (
                    Q(talk__user_one__email=user_two)
                    & Q(talk__user_two__email=username)
                )
            ).order_by("-create_date")

            views = ChatVisualizations.objects.filter(
                Q(user=user)
                & (
                    Q(message__talk__user_two__email=user_two)
                    | Q(message__talk__user_one__email=user_two)
                )
                & Q(viewed=False)
            )

            views.update(viewed=True, date_viewed=datetime.now())

            page = []

            for i in range(
                messages_by_page * (n_page - 1), (n_page * messages_by_page)
            ):
                if i >= messages.count():
                    break
                else:
                    page.append(messages[i])

            serializer = ChatSerializer(page, many=True, context={"request_user": user})

            json_r = json.dumps(serializer.data)
            json_r = json.loads(json_r)

            info = {}

            info["data"] = {}
            info["data"]["messages"] = json_r
            info["data"]["message_sent"] = {}

            info["message"] = ""
            info["type"] = ""
            info["title"] = ""
            info["success"] = True
            info["number"] = 1
            info["extra"] = 0

            response = json.dumps(info)

            try:
                talk = Conversation.objects.get(
                    (Q(user_one__email=username) & Q(user_two__email=user_two))
                    | (Q(user_two__email=username) & Q(user_one__email=user_two))
                )
                self.log_context["talk_id"] = talk.id
            except Conversation.DoesNotExist:
                pass

            self.log_context["user_id"] = user2.id
            self.log_context["user_name"] = str(user2)
            self.log_context["user_email"] = user_two

            super(ChatViewset, self).createLog(
                user,
                self.log_component,
                self.log_action,
                self.log_resource,
                self.log_context,
            )

        return HttpResponse(response)
Exemple #26
0
 def get(self, request):
     room = request.GET.get('room')
     chat = Chat.objects.filter(room=room)
     serializer = ChatSerializer(chat, many=True)
     return Response({'data': serializer.data})
Exemple #27
0
 def get(self, request, pk):
     room = Room.objects.get(pk=pk)
     chat = Chat.objects.filter(room=room)
     serializer = ChatSerializer(chat, many=True)
     return Response(data=serializer.data)