# Path: chat/utils.py
# def date_handler(obj):
#     if hasattr(obj, 'isoformat'):
#         return obj.isoformat()
#     else:
#         raise TypeError
# 
# Path: chat/constants.py
# MESSAGES_PAGE_SIZE = 50
# CHAT_ALREADY_EXISTS = 'CHAT_ALREADY_EXISTS';
# CHAT_NEW = 'CHAT_NEW'
# SEND_MESSAGE = 'SEND_MESSAGE'
# READ_MESSAGE = 'READ_MESSAGE'
# IS_USER_TYPING = 'IS_USER_TYPING'
# DISPLAY_CHAT_ON_RECIPIENT_SIDE = 'DISPLAY_CHAT_ON_RECIPIENT_SIDE'
# 
# Path: chat/models.py
# class Chat(models.Model):
#     id = models.AutoField(primary_key=True, editable=False)
#     participants = models.ManyToManyField(User)
#     messages = models.ManyToManyField(Message)
#     timestamp = models.DateTimeField(auto_now_add=True)
# 
#     @property
#     def last_message_text(self):
#         return self.messages.latest('timestamp').text
# 
#     @property
#     def last_message_sender_id(self):
#         return self.messages.latest('timestamp').sender.id
# 
#     @property
#     def last_message_timestamp(self):
#         return self.messages.latest('timestamp').timestamp
# 
#     @property
#     def last_message_is_read(self):
#         return self.messages.latest('timestamp').is_read
# 
#     def __str__(self):
#         return str(self.id)
# 
#     class Meta:
#         verbose_name = 'Chat'
#         ordering = ['-timestamp']


import os.path
import json
import tornado.httpserver
import tornado.web
import tornado.websocket
import tornado.ioloop
import tornado.gen
import tornadoredis
from datetime import datetime
from urllib.parse import urlencode
from importlib import import_module
from chat.utils import date_handler
from chat import constants
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from chat.models import Chat

        yield tornado.gen.Task(self.client.subscribe, 'chat_{}'.format(chat_id))
        self.client.listen(self.show_new_message)

    def check_origin(self, origin):
        if origin == 'http://127.0.0.1:8000' or 'http://127.0.0.1:8888':
            return True
        else:
            return False

    def handle_request(self, response):
        pass

    def on_message(self, msg):
        msg = json.loads(msg)
        http_client = tornado.httpclient.AsyncHTTPClient()
        if msg['type'] == constants.SEND_MESSAGE:
            message = {
                'type': msg['type'],
                'chat_id': self.chat_id,
                'sender_id': self.user_id,
                'message': {
                    'text': msg['message'],
                    'sender_username': self.username,
                    'timestamp': datetime.now(),
                    'is_read': False
                }
            }

            c.publish('user_{}'.format(self.user_id), json.dumps(message, default=date_handler))

# Path: chat/utils.py
# def date_handler(obj):
#     if hasattr(obj, 'isoformat'):
#         return obj.isoformat()
#     else:
#         raise TypeError
# 
# Path: chat/constants.py
# MESSAGES_PAGE_SIZE = 50
# CHAT_ALREADY_EXISTS = 'CHAT_ALREADY_EXISTS';
# CHAT_NEW = 'CHAT_NEW'
# SEND_MESSAGE = 'SEND_MESSAGE'
# READ_MESSAGE = 'READ_MESSAGE'
# IS_USER_TYPING = 'IS_USER_TYPING'
# DISPLAY_CHAT_ON_RECIPIENT_SIDE = 'DISPLAY_CHAT_ON_RECIPIENT_SIDE'
# 
# Path: chat/models.py
# class Chat(models.Model):
#     id = models.AutoField(primary_key=True, editable=False)
#     participants = models.ManyToManyField(User)
#     messages = models.ManyToManyField(Message)
#     timestamp = models.DateTimeField(auto_now_add=True)
# 
#     @property
#     def last_message_text(self):
#         return self.messages.latest('timestamp').text
# 
#     @property
#     def last_message_sender_id(self):
#         return self.messages.latest('timestamp').sender.id
# 
#     @property
#     def last_message_timestamp(self):
#         return self.messages.latest('timestamp').timestamp
# 
#     @property
#     def last_message_is_read(self):
#         return self.messages.latest('timestamp').is_read
# 
#     def __str__(self):
#         return str(self.id)
# 
#     class Meta:
#         verbose_name = 'Chat'
#         ordering = ['-timestamp']


# Path: chat/tornado_chat.py
import os.path
import json
import tornado.httpserver
import tornado.web
import tornado.websocket
import tornado.ioloop
import tornado.gen
import tornadoredis
from datetime import datetime
from urllib.parse import urlencode
from importlib import import_module
from chat.utils import date_handler
from chat import constants
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from chat.models import Chat


        yield tornado.gen.Task(self.client.subscribe, 'chat_{}'.format(chat_id))
        self.client.listen(self.show_new_message)

    def check_origin(self, origin):
        if origin == 'http://127.0.0.1:8000' or 'http://127.0.0.1:8888':
            return True
        else:
            return False

    def handle_request(self, response):
        pass

    def on_message(self, msg):
        msg = json.loads(msg)
        http_client = tornado.httpclient.AsyncHTTPClient()
        if msg['type'] == constants.SEND_MESSAGE:
            message = {
                'type': msg['type'],
                'chat_id': self.chat_id,
                'sender_id': self.user_id,
                'message': {
                    'text': msg['message'],
                    'sender_username': self.username,
                    'timestamp': datetime.now(),
                    'is_read': False
                }
            }

            c.publish('user_{}'.format(self.user_id), json.dumps(message, default=date_handler))

            c.publish('user_{}'.format(msg['interlocutorId']), json.dumps(message, default=date_handler))