├── .gitignore ├── README.md ├── chat-app.gif ├── requirements.txt └── src ├── chat ├── __init__.py ├── consumers.py ├── helpers.py ├── migrations │ └── __init__.py ├── routing.py ├── templates │ └── chat │ │ ├── chat_ui.html │ │ ├── index.html │ │ ├── login.html │ │ └── room.html ├── urls.py └── views.py ├── manage.py └── mysite ├── __init__.py ├── asgi.py ├── routing.py ├── settings.py ├── urls.py └── wsgi.py /.gitignore: -------------------------------------------------------------------------------- 1 | # These files will be ignored from git 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # Environments 83 | .env 84 | .venv 85 | env/ 86 | venv/ 87 | ENV/ 88 | 89 | # Spyder project settings 90 | .spyderproject 91 | .spyproject 92 | 93 | # Rope project settings 94 | .ropeproject 95 | 96 | # mkdocs documentation 97 | /site 98 | 99 | # mypy 100 | .mypy_cache/ 101 | .idea/ 102 | /prototype/testing_scripts/ 103 | .DS_Store 104 | 105 | db.sqlite3 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | django-channels-chat 2 | === 3 | 4 | Group chat using django channels 5 | 6 | ![](chat-app.gif) 7 | 8 | 9 | ### Installation 10 | ``` 11 | $ pip install -U channels 12 | ``` 13 | 14 | >Note: Recommended to install this in a virtualenv 15 | 16 | 17 | ### flow 18 | ``` 19 | login ----> add chat room ---> start chatting 20 | ``` 21 | 22 | 23 | ### Run the following using: 24 | ``` 25 | $ python manage.py runserver 26 | ``` 27 | 28 | >Note: redis is used as channel backend and mongoDB is used for message persistence. 29 | Make sure they are installed and running in background 30 | 31 | 32 | ### Goal 33 | To understand the working of channels. 34 | Hence haven't concentrated much on frontend. 35 | 36 | 37 | ### TODOs 38 | 39 | 1. better login UI (just plain html now) 40 | 2. better frontend code 41 | 42 | -------------------------------------------------------------------------------- /chat-app.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adihat/django-channels-chat/0ff2decfd5bc7df1e0c60a8592f29d9aa6185bec/chat-app.gif -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | asgiref==2.3.2 2 | async-timeout==3.0.0 3 | attrs==18.2.0 4 | autobahn==18.9.2 5 | Automat==0.7.0 6 | channels==2.0.0 7 | constantly==15.1.0 8 | daphne==2.2.2 9 | Django==2.1.1 10 | hyperlink==18.0.0 11 | idna==2.7 12 | incremental==17.5.0 13 | PyHamcrest==1.9.0 14 | pytz==2018.5 15 | six==1.11.0 16 | Twisted==18.7.0 17 | txaio==18.8.1 18 | zope.interface==4.5.0 19 | -------------------------------------------------------------------------------- /src/chat/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adihat/django-channels-chat/0ff2decfd5bc7df1e0c60a8592f29d9aa6185bec/src/chat/__init__.py -------------------------------------------------------------------------------- /src/chat/consumers.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import json 3 | 4 | from asgiref.sync import async_to_sync 5 | from channels.db import database_sync_to_async 6 | from channels.generic.websocket import AsyncWebsocketConsumer, JsonWebsocketConsumer 7 | 8 | from mysite.settings import MONGO_CLIENT 9 | 10 | 11 | @database_sync_to_async 12 | def save_to_database(db, collection, chat_message): 13 | print('inside save_to_database====>', db, collection, chat_message) 14 | r = MONGO_CLIENT[db][collection].insert_one(chat_message) 15 | return True, r.inserted_id 16 | 17 | 18 | class ChatConsumer(AsyncWebsocketConsumer): 19 | async def connect(self): 20 | print('inside ChatConsumer connect()') 21 | self.username = self.scope['session'].get('username', 'server') 22 | self.room_name = self.scope['url_route']['kwargs']['room_name'] 23 | self.room_group_name = 'chat_%s' % self.room_name 24 | # for multicast 25 | await self.channel_layer.group_add(self.room_group_name, self.channel_name) 26 | # for broadcast 27 | await self.channel_layer.group_add('server_announcements', self.channel_name) 28 | await self.accept() 29 | chat_data = {'username': self.username, 'online': True, 'type': 'chat_message'} 30 | await self.channel_layer.group_send(self.room_group_name, chat_data) 31 | 32 | async def disconnect(self, close_code): 33 | print('inside ChatConsumer disconnect()') 34 | # send offline broadcast 35 | offline_data = {'username': self.username, 'online': False, 'type': 'offline'} 36 | await self.channel_layer.group_send(self.room_group_name, offline_data) 37 | await self.channel_layer.group_discard('server_announcements', self.channel_name) 38 | # Leave room group 39 | await self.channel_layer.group_discard(self.room_group_name, self.channel_name) 40 | 41 | # Receive message from WebSocket 42 | async def receive(self, text_data): 43 | print('inside ChatConsumer receive()') 44 | if not self.username == 'server': 45 | username = self.scope['session']['username'] 46 | else: 47 | username = 'server' 48 | text_data_json = json.loads(text_data) 49 | typing = text_data_json.get('typing') or False 50 | out_of_focus = text_data_json.get('outoffocus') or False 51 | timestamp = text_data_json.get('timestamp') or '' 52 | online = text_data_json.get('online', True) 53 | chat_data = {'type': 'chat_message', 'username': username, 'outoffocus': out_of_focus, 'typing': typing, 54 | 'timestamp': timestamp, 'online': online} 55 | message = text_data_json.get('message', '') 56 | if message: 57 | chat_data.update({'message': message}) 58 | await self.channel_layer.group_send(self.room_group_name, chat_data) 59 | 60 | async def chat_message(self, event): 61 | print('inside ChatConsumer chat_message()', event) 62 | await self.send(text_data=json.dumps(event)) 63 | 64 | # TODO link with celery later 65 | # save to database 66 | message = event.get('message') or '' 67 | if message: 68 | user_name = event['username'] 69 | room_name = self.scope['url_route']['kwargs']['room_name'] 70 | timestamp = datetime.datetime.utcnow() 71 | chat_data = {'user': user_name, 'chat_room': room_name, 'message': {'text': message}, 72 | 'timestamp': timestamp} 73 | status, inserted_id = await save_to_database('chat_message', 'account_1', chat_data) 74 | if status: 75 | print('chat saved to db successfully ====>', inserted_id) 76 | else: 77 | print('saving to db failed') 78 | 79 | async def offline(self, event): 80 | print('inside offline() ====>', event) 81 | await self.send(text_data=json.dumps(event)) 82 | 83 | 84 | class EventConsumer(JsonWebsocketConsumer): 85 | def connect(self): 86 | print('inside EventConsumer connect()') 87 | async_to_sync(self.channel_layer.group_add)( 88 | 'events', 89 | self.channel_name 90 | ) 91 | self.accept() 92 | 93 | def disconnect(self, close_code): 94 | print('inside EventConsumer disconnect()') 95 | print("Closed websocket with code: ", close_code) 96 | async_to_sync(self.channel_layer.group_discard)( 97 | 'events', 98 | self.channel_name 99 | ) 100 | self.close() 101 | 102 | def receive_json(self, content, **kwargs): 103 | print('inside EventConsumer receive_json()') 104 | print("Received event: {}".format(content)) 105 | self.send_json(content) 106 | 107 | def events_alarm(self, event): 108 | print('inside EventConsumer events_alarm()') 109 | self.send_json( 110 | { 111 | 'type': 'events.alarm', 112 | 'content': event['content'] 113 | } 114 | ) 115 | 116 | -------------------------------------------------------------------------------- /src/chat/helpers.py: -------------------------------------------------------------------------------- 1 | import pytz 2 | 3 | INDIAN_TIMEZONE = 'Asia/Kolkata' 4 | UTC_TIMEZONE = 'UTC' 5 | DATE_TIME_FORMAT = "%I:%M %p" 6 | 7 | def get_str_from_datetime(obj, datetime_format): 8 | try: 9 | return obj.strftime(datetime_format) 10 | except: 11 | return obj 12 | 13 | 14 | def convert_datetime_to_different_timezone(obj, current_time_zone, to_time_zone, preserve_tz_info=False): 15 | obj = obj.replace(tzinfo=None) 16 | obj_in_current_timezone = pytz.timezone(current_time_zone).localize(obj) 17 | if preserve_tz_info: 18 | return obj_in_current_timezone.astimezone(pytz.timezone(to_time_zone)) 19 | return obj_in_current_timezone.astimezone(pytz.timezone(to_time_zone)).replace(tzinfo=None) 20 | -------------------------------------------------------------------------------- /src/chat/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adihat/django-channels-chat/0ff2decfd5bc7df1e0c60a8592f29d9aa6185bec/src/chat/migrations/__init__.py -------------------------------------------------------------------------------- /src/chat/routing.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import consumers 4 | 5 | websocket_urlpatterns = [ 6 | url(r'^ws/chat/(?P[^/]+)/$', consumers.ChatConsumer), 7 | url(r'^ws/event/$', consumers.EventConsumer), 8 | 9 | ] 10 | -------------------------------------------------------------------------------- /src/chat/templates/chat/chat_ui.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Chat Window 6 | 7 | 833 | 834 | 835 |
836 |
837 | 864 |
865 |

{{ room_name }}

866 |

Online users: No users online

867 |
    868 | 885 |
886 |
887 |
888 | 889 | 890 | 891 |
892 |
893 |
894 |
895 | 896 | 1069 | 1070 | 1071 | -------------------------------------------------------------------------------- /src/chat/templates/chat/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Chat Rooms 7 | 8 | 9 |

Welcome {{username}}

10 | What chat room would you like to enter?
11 |
12 | 13 | 14 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/chat/templates/chat/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | login form 6 | 7 | 8 |
9 | {% csrf_token %} 10 |

11 |

12 | 13 |
14 | 15 | -------------------------------------------------------------------------------- /src/chat/templates/chat/room.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Chat Room 6 | 7 | 8 |
9 |
10 |


11 | 12 | 13 | 14 | 92 | 93 | -------------------------------------------------------------------------------- /src/chat/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from . import views 3 | 4 | urlpatterns = [ 5 | url(r'^$', views.index, name='index'), 6 | url(r'^(?P[^/]+)/$', views.room, name='room'), 7 | ] 8 | -------------------------------------------------------------------------------- /src/chat/views.py: -------------------------------------------------------------------------------- 1 | from channels.layers import get_channel_layer 2 | from django.http import JsonResponse, HttpResponseRedirect, HttpResponse 3 | from django.shortcuts import render 4 | from django.utils.safestring import mark_safe 5 | from asgiref.sync import async_to_sync 6 | 7 | from chat.helpers import convert_datetime_to_different_timezone, UTC_TIMEZONE, INDIAN_TIMEZONE, get_str_from_datetime, \ 8 | DATE_TIME_FORMAT 9 | from mysite.settings import MONGO_CLIENT 10 | 11 | 12 | def index(request): 13 | return render(request, 'chat/index.html', {}) 14 | 15 | 16 | def room(request, room_name): 17 | print('inside room view ======>', room_name) 18 | username = request.session.get('username') or '' 19 | if not username: 20 | return HttpResponseRedirect('/login/') 21 | filters = {'chat_room': room_name, 'deleted': {'$ne': True}} 22 | sort_fields = [('timestamp', -1)] 23 | previous_messages = [] 24 | for chat in MONGO_CLIENT['chat_message']['account_1'].find(filters).sort(sort_fields).limit(20): 25 | chat['_id'] = str(chat['_id']) 26 | indian_timestamp = convert_datetime_to_different_timezone(chat['timestamp'], UTC_TIMEZONE, INDIAN_TIMEZONE) 27 | chat['timestamp'] = get_str_from_datetime(indian_timestamp, DATE_TIME_FORMAT) 28 | chat['message'] = chat['message']['text'] 29 | previous_messages.append(chat) 30 | previous_messages = sorted(previous_messages, key=lambda s: s['timestamp']) 31 | print('previous_messages =======>', previous_messages) 32 | return render(request, 'chat/chat_ui.html', { 33 | 'room_name': room_name, 34 | 'prev_messages': mark_safe(previous_messages), 35 | 'current_user': request.session['username'] 36 | }) 37 | 38 | 39 | def http_view(request): 40 | return JsonResponse({'message': 'hello world'}) 41 | 42 | 43 | def login(request): 44 | return render(request, 'chat/login.html', {}) 45 | 46 | 47 | def logged_in(request): 48 | post_data = request.POST 49 | print('post_data =====>', post_data) 50 | username = post_data['username'] 51 | request.session['username'] = username 52 | return render(request, 'chat/index.html', {'username': username}) 53 | 54 | 55 | def send_data_from_server(request): 56 | channel_layer = get_channel_layer() 57 | async_to_sync(channel_layer.group_send)('chat_hubbler', 58 | {'type': 'chat.message', 'username': 'server', 'outoffocus': True, 59 | 'typing': True, 'timestamp': '10:03 PM', 'online': True, 60 | 'message': 'hi from server'}) 61 | return JsonResponse({'success': True}) 62 | 63 | 64 | def alarm(request): 65 | layer = get_channel_layer() 66 | async_to_sync(layer.group_send)('events', { 67 | 'type': 'events.alarm', 68 | 'content': 'triggered' 69 | }) 70 | return HttpResponse('

Done

') 71 | -------------------------------------------------------------------------------- /src/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /src/mysite/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adihat/django-channels-chat/0ff2decfd5bc7df1e0c60a8592f29d9aa6185bec/src/mysite/__init__.py -------------------------------------------------------------------------------- /src/mysite/asgi.py: -------------------------------------------------------------------------------- 1 | import os 2 | import django 3 | from channels.routing import get_default_application 4 | 5 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") 6 | django.setup() 7 | application = get_default_application() 8 | -------------------------------------------------------------------------------- /src/mysite/routing.py: -------------------------------------------------------------------------------- 1 | from channels.auth import AuthMiddlewareStack 2 | from channels.routing import ProtocolTypeRouter, URLRouter 3 | from channels.security.websocket import AllowedHostsOriginValidator 4 | 5 | import chat.routing 6 | 7 | application = ProtocolTypeRouter({ 8 | 'websocket': AllowedHostsOriginValidator( 9 | AuthMiddlewareStack( 10 | URLRouter( 11 | chat.routing.websocket_urlpatterns, 12 | 13 | ) 14 | ) 15 | ), 16 | }) 17 | -------------------------------------------------------------------------------- /src/mysite/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for mysite project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | import pymongo 15 | 16 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 17 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '900boesvc=ofp!hzoiejxr)k5aq%9g2glbtbjuv=!(^^=_6u&%' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = ['*'] 29 | 30 | # Application definition 31 | 32 | INSTALLED_APPS = [ 33 | 'django.contrib.admin', 34 | 'django.contrib.auth', 35 | 'django.contrib.contenttypes', 36 | 'django.contrib.sessions', 37 | 'django.contrib.messages', 38 | 'django.contrib.staticfiles', 39 | 'chat', 40 | 'channels' 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'mysite.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'mysite.wsgi.application' 72 | 73 | # Database 74 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 75 | 76 | DATABASES = { 77 | 'default': { 78 | 'ENGINE': 'django.db.backends.sqlite3', 79 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 80 | } 81 | } 82 | 83 | # Password validation 84 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 85 | 86 | AUTH_PASSWORD_VALIDATORS = [ 87 | { 88 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 89 | }, 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 98 | }, 99 | ] 100 | 101 | # Internationalization 102 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 103 | 104 | LANGUAGE_CODE = 'en-us' 105 | 106 | TIME_ZONE = 'UTC' 107 | 108 | USE_I18N = True 109 | 110 | USE_L10N = True 111 | 112 | USE_TZ = True 113 | 114 | # Static files (CSS, JavaScript, Images) 115 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 116 | 117 | STATIC_URL = '/static/' 118 | 119 | ASGI_APPLICATION = 'mysite.routing.application' 120 | CHANNEL_LAYERS = { 121 | 'default': { 122 | 'BACKEND': 'channels_redis.core.RedisChannelLayer', 123 | 'CONFIG': { 124 | "hosts": [('localhost', 6379)], 125 | }, 126 | }, 127 | } 128 | 129 | MONGO_CLIENT = pymongo.MongoClient() 130 | 131 | # session settings 132 | SESSION_COOKIE_AGE = 5 * 60 133 | SESSION_SAVE_EVERY_REQUEST = True 134 | -------------------------------------------------------------------------------- /src/mysite/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import include, url 2 | from django.contrib import admin 3 | 4 | from chat.views import http_view, login, logged_in, send_data_from_server, alarm 5 | 6 | urlpatterns = [ 7 | url(r'^ws/chat/', include('chat.urls')), 8 | url(r'^admin/', admin.site.urls), 9 | url(r'^ws/hello/$', http_view), 10 | url(r'^login/$', login), 11 | url(r'^logged-in/$', logged_in), 12 | url(r'^server-send/$', send_data_from_server), 13 | url(r'^alarm/$', alarm, name='alarm'), 14 | ] 15 | -------------------------------------------------------------------------------- /src/mysite/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for mysite project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') 15 | 16 | application = get_wsgi_application() 17 | --------------------------------------------------------------------------------