Chat app for Django, powered by Django Channels, Websockets & Asyncio

Overview

Django Private Chat2

https://badge.fury.io/py/django_private_chat2

https://travis-ci.org/Bearle/django_private_chat2

https://codecov.io/gh/Bearle/django_private_chat2

New and improved https://github.com/Bearle/django-private-chat

Chat app for Django, powered by Django Channels, Websockets & Asyncio

screenshot

Documentation

The full documentation will be at https://django_private_chat2.readthedocs.io.

Quickstart

Install django_private_chat2:

pip install django_private_chat2

Add it to your INSTALLED_APPS:

INSTALLED_APPS = (
    ...
    'django_private_chat2.apps.DjangoPrivateChat2Config',
    ...
)

Add django_private_chat2's URL patterns:

from django_private_chat2 import urls as django_private_chat2_urls


urlpatterns = [
    ...
    url(r'^', include(django_private_chat2_urls)),
    ...
]

Add django_private_chat2's websocket URLs to your asgi.py:

django_asgi_app = get_asgi_application()
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django_private_chat2 import urls
application = ProtocolTypeRouter({
    "http": django_asgi_app,
    "websocket": AuthMiddlewareStack(
        URLRouter(urls.websocket_urlpatterns)
    ),
})

Important:

django_private_chat2 doesn't provide any endpoint to fetch users (required to start new chat, for example) It's up to you to do so. The example app does it in urls.py so feel free to copy the handler from there if you wish.

Support

django_private_chat2 is tested against python3.6, python3.7, python3.8, python3.9 with Django 3.0, Django 3.1 and Django 3.2.

You can view the builds here:

https://travis-ci.com/github/Bearle/django_private_chat2/builds/

Please file an issue if you have any problems with any combination of the above.

Features

Django-related

- Fully-functional example app

- Uses Django admin

- Supports pluggable User model (and accounts for non-integer primary keys, too)

- Doesn't require Django Rest Framework (views are based off django.views.generic)

- Configurable via settings

- Fully translatable

- Uses Django storage system & FileField for file uploads (swappable)

Functionality-related

- Soft deletable messages

- Read/unread messages

- Random id (send message first, write to database later)

- Supports text & file messages

- Gracefully handles errors

- Support 'typing' statuses

- Upload the file first, send the message later (async uploads) - potential for file ref re-use later

... and more

Example app frontend features

  1. Auto reconnected websocket
  2. Toasts about errors & events
  3. Send text messages
  4. Search for users
  5. Create new chat with another user
  6. Online/offline status
  7. Realtime messaging via websocket
  8. Last message
  9. Auto-avatar (identicon) based on user id
  10. Connection status display
  11. Typing... status
  12. Message delivery status (sent, received, waiting, etc.)
  13. Message history
  14. Persistent chat list
  15. Read / unread messages
  16. Unread messages counters (updates when new messages are received)
  17. Send file messages (upload them to server)

TODO

Frontend (example app) & backend

  1. Pagination support on frontend
    1. For messages
    2. For dialogs
  2. Example app only - user list
    1. Endpoint
    2. UI
  3. New dialog support
  4. Online's fetching on initial load
  5. Last message
    1. In fetch
    2. In new dialog
    3. On arriving message
  6. Read / unread/ unread count
  7. Last seen
  8. Send photo
  9. Send file
  10. Reply to message
  11. Delete message
  12. Forward message
  13. Search for dialog (username)
    1. Frontend (local)
    2. Server based - won't do, out of the scope of the project
  14. Fake data generator (to test & bench) - done via factories in tests
  15. Cache dialogs (get_groups_to_add) - ?
  16. Move views to async views - ?
  17. Add some sounds
    1. New message
    2. New dialog
    3. Sent message received db_id
  18. Optimize /messages/ endpoint
  19. Some tests
  20. Full test coverage
  21. Migration from v1 guide
  22. Documentation

Running Tests

Does the code actually work?

source <YOURVIRTUALENV>/bin/activate
(myenv) $ pip install tox
(myenv) $ tox

Development commands

pip install -r requirements_dev.txt
invoke -l

Credits

Tools used in rendering this package:

Paid support

If you wish to have professional help from the authors of django_private_chat2, or simply hire Django experts to solve a particular problem, please contact us via email tech at bearle.ru or Bearle in telegram

Comments
  • JSON parse error while running

    JSON parse error while running

    • django_private_chat2 version: latest
    • Django version: 3.2.4
    • Python version: 3.9
    • Operating System: Linux

    Description

    When ever i login, i get this annoying json parse error image

    THE FULL LOG HERE: https://bpa.st/74OQ Thank you guys!

    opened by alexdrm98 6
  • Django_private_chat2 Deployment in Production

    Django_private_chat2 Deployment in Production

    Setup

    • django_private_chat2: 0.3.0
    • Django: 3.0
    • Python: 3.7.5
    • channels: 3.0.3
    • OS: Ubuntu 21.04 x64
    • gunicorn (20.1.0), nginx and uvicorn (0.12.0)

    Description

    I was trying to get django_private_chat2 up on my staging/production environment on the ubuntu server. Locally everything is working perfectly. In the browser I can see the error "500 Internal "Server Error for URL http://...105.123/messages" and "Server Error for URL http://...105.123/dialogs". When I click on "inspect element" in the browser I see "WebSocket connection to 'ws://...105.125/chat_ws' failed: ". My guess would be that the ASGI cannot be set properly in the settings.py OR that the server configurations are misconfigured.

    What I Did

    • Enclosed a screenshot of the app (screenshot_a)
    Screenshot 2021-05-31 at 22 41 19
    • Enclosed the settings.py

    ALLOWED_HOSTS = ['143.78.105.125','0.0.0.0'] CHAT_WS_SERVER_HOST = '143.78.105.125' # Q CHAT_WS_SERVER_PORT = 5002 #T, Q

    CHAT_WS_SERVER_PROTOCOL = 'ws' #T, Q CHAT_WS_CLIENT_HOST = '143.78.105.125' CHAT_WS_CLIENT_PORT = 80 #T, Q

    CHAT_WS_CLIENT_ROUTE = 'ws/' #T,Q INTERNAL_IPS = ['143.78.105.125'] SESSION_COOKIE_AGE = 12096000

    INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'crispy_forms', 'django_private_chat2.apps.DjangoPrivateChat2Config', 'example.apps.ExampleConfig',

    ]

    MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'easy_timezones.middleware.EasyTimezoneMiddleware', > ] ROOT_URLCONF = 'app.urls'

    STATIC_URL = '/static/'

    STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), #os.path.join(os.path.dirname(BASE_DIR), 'app'), > ]

    SITE_ROOT = os.path.realpath(os.path.dirname(file)) if DEBUG == True: STATIC_ROOT = os.path.join(SITE_ROOT, 'static') else: #STATIC_ROOT = os.path.join(BASE_DIR, 'statics_root') STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') STATIC_URL = '/static/'

    MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

    CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer' } }

    CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('http://143.78.105.125', 6379)], }, }, }

    ASGI_APPLICATION = 'app.routing.application' #WSGI_APPLICATION = 'app.wsgi.application'

    • Enclosed nignx/default configs:

    listen [::]:80 default_server; root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;
    
        server_name _;
        client_max_body_size 20M;
        charset utf-8;
    
        location / {
                try_files $uri $uri/ =404;
                proxy_pass http://unix:/run/gunicorn.sock;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
    
                proxy_redirect off;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Host $server_name;
        }
    
    • Enclosed the gunicorn.service configs:

    [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target PartOf=gunicorn.target ReloadPropagatedFrom=gunicorn.target

    [Service] User=christian Group=www-data WorkingDirectory=/home/christian/app/app ExecStart=/home/christian/app/env/bin/gunicorn app.asgi:application -w 2 -k uvicorn.workers.UvicornWorker --bind unix:/run/gunicorn.sock

    [Install] WantedBy=gunicorn.target

    • Enclosed the gunicorn.socket configs:
    Screenshot 2021-06-01 at 14 03 52

    I tried pretty much everything. Do you have any ideas what I am doing wrong? Many thanks!

    opened by chrisdevel 5
  • 413 Request Entity Too Large for URL

    413 Request Entity Too Large for URL

    Guys, I am getting the enclosed error when uploading specific files (also enclosed). I dont know if it has to do something with the extension, however jpeg and other files work perfectly fine. Its just that some do not work. I did not any kind of restriction (size, file extension). Also I dont know where the error is raised in the code. Any clue where to look at?

    Many thanks - you guys are awesome!

    413 Request Entity Too Large for URL

    IMG_20211211_170230

    opened by chrisdevel 3
  • User Dialogs Limit / User

    User Dialogs Limit / User

    Currently I have around 150 dialogs / user in DB, however not all dialogs are displayed in the chat app. After deleting some dialogs as admin, others dialogs appeared again.

    I was wondering if there is a limit as of dialogs per user?

    opened by chrisdevel 3
  • Change Example app

    Change Example app

    • django_private_chat2 version: 0.1.4
    • Django version: 3.2.2
    • Python version: 3.9.1
    • Operating System: ubuntu

    Description

    I can't build frontend app.

    What I Did

    1. npm install -g yarn
    2. sudo snap install dotnet-sdk --classic --channel=5.0
    3. sudo snap alias dotnet-sdk.dotnet dotnet
    4. sudo snap install dotnet-runtime-50 --classic
    5. sudo snap alias dotnet-runtime-50.dotnet dotnet
    6. export DOTNET_ROOT=/snap/dotnet-sdk/current
    7. dotnet --list-sdks 5.0.203 [/snap/dotnet-sdk/126/sdk]
    8. dotnet --list-runtimes Microsoft.AspNetCore.App 5.0.6 [/snap/dotnet-sdk/126/shared/Microsoft.AspNetCore.App] Microsoft.NETCore.App 5.0.6 [/snap/dotnet-sdk/126/shared/Microsoft.NETCore.App]
    9. npm run start:fable cha[email protected] start:fable /home/dell/PycharmProjects/chat/web/frontend

    dotnet fable watch fs-src

    Fable: F# to JS compiler 3.1.7 Thanks to the contributor! @worldbeater fs-src> dotnet restore App.fsproj Could not execute because the application was not found or a compatible .NET SDK is not installed. Possible reasons for this include:

    • You intended to execute a .NET program: The application 'restore' does not exist.
    • You intended to execute a .NET SDK command: ......

    errno 134 npm ERR! [email protected] start:fable: dotnet fable watch fs-src npm ERR! Exit status 134 npm ERR! npm ERR! Failed at the [email protected] start:fable script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in: npm ERR! /home/dell/.npm/_logs/2021-05-12T20_03_58_299Z-debug.log

    Please, what I need do?
    
    opened by ovt00 3
  • Migration error on MySql

    Migration error on MySql

    • django_private_chat2 version: 2 0.1.2
    • Django version: 3.1.7
    • Python version: 3.8
    • Operating System: W10 20h2

    Description

    Giving errors in the third migration.

    Applying django_private_chat2.0003_auto_20210323_1410...Traceback (most recent call last): File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\mysql\base.py", line 73, in exec ute return self.cursor.execute(query, args) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1553, "Cannot drop index 'Unique dialog': needed in a foreign key constraint")

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\core\management_init_.py", line 401, in e xecute_from_command_line utility.execute() File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\core\management_init_.py", line 395, in e xecute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\core\management\base.py", line 330, in run_f rom_argv self.execute(*args, **cmd_options) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\core\management\base.py", line 371, in execu te output = self.handle(*args, **options) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\core\management\base.py", line 85, in wrappe d res = handle_func(*args, **kwargs) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\core\management\commands\migrate.py", line 2 43, in handle post_migrate_state = executor.migrate( File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in mig rate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _mi grate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\migrations\executor.py", line 227, in app ly_migration state = migration.apply(state, schema_editor) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\migrations\migration.py", line 124, in ap ply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\migrations\operations\models.py", line 84 3, in database_forwards schema_editor.remove_constraint(model, constraint) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\base\schema.py", line 368, in re move_constraint self.execute(sql) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\base\schema.py", line 142, in ex ecute cursor.execute(sql, params) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\utils.py", line 75, in execute with_wrappers return executor(sql, params, many, context) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\django\db\backends\mysql\base.py", line 73, in exec ute return self.cursor.execute(query, args) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "C:\Users\Yunus\PycharmProjects\yeye\venv\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1553, "Cannot drop index 'Unique dialog': needed in a foreign key constraint")

    What I Did

    I just tried to migrate after the setup.

    opened by adamsocrat 3
  • how to fix this?

    how to fix this?

    • django_private_chat2 version:
    • Django version:
    • Python version:
    • Operating System:

    Description

    Describe what you were trying to get done. Tell us what happened, what went wrong, and what you expected to happen.

    What I Did

    Paste the command(s) you ran and the output.
    If there was a crash, please include the traceback here.
    

    Exception inside application: 'ChatConsumer' object has no attribute 'channel_name' Traceback (most recent call last): File "/root/testchat/venv/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in call return await self.application(scope, receive, send) File "/root/testchat/venv/lib/python3.8/site-packages/channels/routing.py", line 71, in call return await application(scope, receive, send) File "/root/testchat/venv/lib/python3.8/site-packages/channels/sessions.py", line 47, in call return await self.inner(dict(scope, cookies=cookies), receive, send) File "/root/testchat/venv/lib/python3.8/site-packages/channels/sessions.py", line 263, in call return await self.inner(wrapper.scope, receive, wrapper.send) File "/root/testchat/venv/lib/python3.8/site-packages/channels/auth.py", line 185, in call return await super().call(scope, receive, send) File "/root/testchat/venv/lib/python3.8/site-packages/channels/middleware.py", line 26, in call return await self.inner(scope, receive, send) File "/root/testchat/venv/lib/python3.8/site-packages/channels/routing.py", line 150, in call return await application( File "/root/testchat/venv/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/root/testchat/venv/lib/python3.8/site-packages/channels/consumer.py", line 62, in call await await_many_dispatch([receive], self.dispatch) File "/root/testchat/venv/lib/python3.8/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/root/testchat/venv/lib/python3.8/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/root/testchat/venv/lib/python3.8/site-packages/channels/generic/websocket.py", line 173, in websocket_connect await self.connect() File "/root/testchat/venv/lib/python3.8/site-packages/django_private_chat2/consumers.py", line 138, in connect logger.info(f"User {self.user.pk} connected, adding {self.channel_name} to {self.group_name}") AttributeError: 'ChatConsumer' object has no attribute 'channel_name'

    hi how i can fix this?

    opened by Mohammadwh 2
  • Cross Origin requests to 127.0.0.1:8000 not allowed when running the example code

    Cross Origin requests to 127.0.0.1:8000 not allowed when running the example code

    • django_private_chat2 version: 0.1.4
    • Django version: 3.2.3
    • Python version: 3.9.5
    • Operating System: macOS Big Sur

    Description

    Running the test app results in a cross origin error

    What I Did

    python manage.py migrate
    python manage.py createsuperuser
    python manage.py runserver
    

    In the logs:

    (0.001) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2021-06-21 11:44:57.252571' AND "django_session"."session_key" = 'XXX') LIMIT 21; args=('2021-06-21 11:44:57.252571', 'XXX')
    (0.000) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1 LIMIT 21; args=(1,)
    WebSocket CONNECT /chat_ws [127.0.0.1:51810]
    (0.001) SELECT "django_private_chat2_dialogsmodel"."user1_id", "django_private_chat2_dialogsmodel"."user2_id" FROM "django_private_chat2_dialogsmodel" WHERE ("django_private_chat2_dialogsmodel"."user1_id" = 1 OR "django_private_chat2_dialogsmodel"."user2_id" = 1); args=(1, 1)
    

    In the frontend: Screenshot 2021-06-21 at 18 39 37

    opened by merc1er 2
  • Sending E-Mails if Users are offline

    Sending E-Mails if Users are offline

    Hi team,

    I could not find a place in the views.py where messages are being written into the database. I would like to send an email from the backend, if a user has written a message, however the second user is offline.

    Could you please tell me at which please the chat messages are being saved?

    Many thanks.

    opened by chrisdevel 2
  • On the another page of django chat, how can I start a new chat with a certain profile?

    On the another page of django chat, how can I start a new chat with a certain profile?

    • django_private_chat2 version: latest
    • Django version:4
    • Python version:3.8
    • Operating System:windows

    Description

    How I can open new chat with profile ID 2 in example

    What I Did

    I try to pass ID in the url but I cant handle the view of chat.

    opened by jhackr 1
  • According to Quickstart configuration, no front-end page is opened

    According to Quickstart configuration, no front-end page is opened

    • django_private_chat2 version:1.0.2
    • Django version:3.2
    • Python version:3.7
    • Operating System:windows

    Description

    According to Quickstart configuration, no front-end page is opened

    What I Did

    According to Quickstart configuration, no front-end page is opened. image ps:When will the new version be released?

    Paste the command(s) you ran and the output.
    If there was a crash, please include the traceback here.
    
    opened by wangxr011235 1
  • How can I change user's avatar manually?

    How can I change user's avatar manually?

    • django_private_chat2 version: 1.0.2
    • Django version:3.2.15
    • Python version:3.8.10
    • Operating System: manjaro

    Description

    I wanna to change user's avatar instead of auto avatar, but I'm failed to find the code which making auto acatar.

    What I Did

    I had tried to find example/static/js/main.js , but I still failed to find the code.

    opened by 05ZT30 1
  • How to deploy on server

    How to deploy on server

    • django_private_chat2 version:
    • Django version:
    • Python version:
    • Operating System:

    Description

    Describe what you were trying to get done. Tell us what happened, what went wrong, and what you expected to happen.

    What I Did

    what changes to do before deployment on server?

    opened by buneshwarEc 0
  • Users not loading.

    Users not loading.

    • django_private_chat2 version:
    • Django version:3.2.7
    • Python version:3.9.2
    • Operating System: macOS Monterey

    Description

    Websocket connections sometimes connect but often doesn't. I Keep getting

    WebSocket HANDSHAKING /chat_ws [127.0.0.1:50071] WebSocket REJECT /chat_ws [127.0.0.1:50071] WebSocket DISCONNECT /chat_ws [127.0.0.1:50071]

    I have been able to set up the project. Have setup my chat index and user list in a Django chat app. frontend code from example are in an app called chat of my django project.

    I set up urls like this: path('apps/chat/', include("chat.urls") ,name="chat-app"), path(r'apps/chat/', include('django_private_chat2.urls', namespace='django_private_chat2')

    When I visit chat and users_list ape endpoint in browser, I get results. but console is logging not found.

    What I Did

    Paste the command(s) you ran and the output.
    If there was a crash, please include the traceback here.
    
    opened by mailantwi 2
  • Group Chat 1:n

    Group Chat 1:n

    Hi,

    I would like to have a 1:n chat (group-chat) additionally to the current 1:1 chat. I was wondering what kind of modifications are needed to do so. Maybe you have same advice as for the starting point.

    Many thanks!

    opened by chrisdevel 6
  • Django Rest Framework Simple JWT getting anonymous user

    Django Rest Framework Simple JWT getting anonymous user

    • django_private_chat2 version: 1.0.2
    • Django version: 4.0.1
    • Python version: 10.0
    • Operating System: Win 10

    Description

    I want to use Rest Framework simpleJWT as authentication earlier I was using Django default authentication. Here are views currently I am getting AnonymousUser error, what changes do I need to get a user request from JWT Authenticated user. I want to get a request.user from a jWT Authenticated user. Please help me out.

    Here are views

    class MessagesModelList(ListView):
    http_method_names = ['get', ]
    paginate_by = getattr(settings, 'MESSAGES_PAGINATION', 500)
    
    def get_queryset(self):
        if self.kwargs.get('dialog_with'):
            qs = MessageModel.objects \
                .filter(Q(recipient=self.request.user, sender=self.kwargs['dialog_with']) |
                        Q(sender=self.request.user, recipient=self.kwargs['dialog_with'])) \
                .select_related('sender', 'recipient')
        else:
            qs = MessageModel.objects.filter(Q(recipient=self.request.user) |
                                             Q(sender=self.request.user)).prefetch_related('sender', 'recipient', 'file')
    
        return qs.order_by('-created')
    
    def render_to_response(self, context, **response_kwargs):
        user_pk = self.request.user.pk
        data = [serialize_message_model(i, user_pk)
                for i in context['object_list']]
        page: Page = context.pop('page_obj')
        paginator: Paginator = context.pop('paginator')
        return_data = {
            'page': page.number,
            'pages': paginator.num_pages,
            'data': data
        }
        return JsonResponse(return_data, **response_kwargs)
    
    class DialogsModelList(ListView):
    
    http_method_names = ['get', ]
    paginate_by = getattr(settings, 'DIALOGS_PAGINATION', 20)
    
    def get_queryset(self):
        qs = DialogsModel.objects.filter(Q(user1_id=self.request.user.pk) | Q(user2_id=self.request.user.pk)) \
            .select_related('user1', 'user2')
        return qs.order_by('-created')
    
    def render_to_response(self, context, **response_kwargs):
        # TODO: add online status
        user_pk = self.request.user.pk
        data = [serialize_dialog_model(i, user_pk)
                for i in context['object_list']]
        page: Page = context.pop('page_obj')
        paginator: Paginator = context.pop('paginator')
        return_data = {
            'page': page.number,
            'pages': paginator.num_pages,
            'data': data
        }
        return JsonResponse(return_data, **response_kwargs)
    
    
    class SelfInfoView(DetailView):
    
    def get_object(self, queryset=None):
        return self.request.user
    
    def render_to_response(self, context, **response_kwargs):
        user: AbstractBaseUser = context['object']
        data = {
            "username": user.get_username(),
            "pk": str(user.pk)
        }
        return JsonResponse(data, **response_kwargs)
    
    class UploadView(CreateView):
    http_method_names = ['post', ]
    model = UploadedFile
    form_class = UploadForm
    
    def form_valid(self, form: UploadForm):
        self.object = UploadedFile.objects.create(
            uploaded_by=self.request.user, file=form.cleaned_data['file'])
        return JsonResponse(serialize_file_model(self.object))
    
    def form_invalid(self, form: UploadForm):
        context = self.get_context_data(form=form)
        errors_json: str = context['form'].errors.get_json_data()
        return HttpResponseBadRequest(content=json.dumps({'errors': errors_json}))
    
    opened by devhusnain 1
Releases(1.0.2)
Owner
Bearle
Bearle
image stream publish server over websocket

Image Stream Push Server 简介 通过浏览器网页实时查看图像处理结果。 环境 运行程序需要安装一下python依赖: tornado: 用于创建http及websocket服务; opencv-contrib-python: 用于图像数据源获取及图像处理。 使用 进入到src目

MrError404 1 Nov 04, 2021
Python Socket.IO server and client

python-socketio Python implementation of the Socket.IO realtime client and server. Version compatibility The Socket.IO protocol has been through a num

Miguel Grinberg 3.2k Dec 31, 2022
Library for building WebSocket servers and clients in Python

What is websockets? websockets is a library for building WebSocket servers and clients in Python with a focus on correctness and simplicity. Built on

Aymeric Augustin 4.3k Jan 04, 2023
This websocket program is for data transmission between server and client. Data transmission is for Federated Learning in Edge computing environment.

websocket-for-data-transmission This websocket program is for data transmission between server and client. Data transmission is for Federated Learning

9 Jul 19, 2022
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.9k Jan 03, 2023
Minecraft WebSocket

Minecraft-WebSocket Pythonでマインクラフトと通信します。 紹介動画 推奨設定 Minecraft Windows Edition (Education Edition) 1.17 以上 Python 3系(3.8.2で動作確認済み) 必要なモジュール ・asyncio ・w

Roii.py 2 Jul 07, 2022
Tetri5 - Multiplayer Websocket Backend

Tetri5 - Multiplayer Websocket Backend This repository is the backend of the multiplayer portion of the Tetri5 game client. It uses the python websock

Giovani Rodriguez 1 Dec 10, 2022
一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK

Nakuru Project 一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK 在 kuriyama 的基础上改动 项目名来源于藍月なくる,图标由せら绘制 食用方法 将 nakuru 文件夹移至 Python 的 Lib/site-packages 目录下。

35 Dec 21, 2022
SocketIO 转发台,保持 botoy 能力和插件功能的同时,透传其接口,以此使用更灵活、生态更好的技术进行开发

bot_sio_transfer SocketIO 转发台,保持 botoy 能力和插件功能的同时,透传其接口,以此使用更灵活、生态更好的技术进行开发 Usage 请参考 botoy 文档接入本插件 Example 考虑一种图文混排场景,如何从复杂结构内快速获取第一张图片的 url ? ( 假设图片

OPQ Open Source Community 3 Oct 18, 2021
Developer-friendly asynchrony for Django

Django Channels Channels augments Django to bring WebSocket, long-poll HTTP, task offloading and other async support to your code, using familiar Djan

Django 5.5k Jan 03, 2023
Python socket.io server implementation on top of Tornado framework

TornadIO2 Disclaimer Unfortunately, Socket.IO 0.8 branch is abandoned, there are huge amount of bugs and nothing getting fixed. I would suggest to loo

Serge S. Koval 526 Oct 03, 2022
Synci - Learning project to create a websocket based client server messaging application

Synci Learning project to create a websocket based client server messaging appli

2 Jan 13, 2022
Websocket RPC and Pub/Sub for Python applications and microservices

wampy [whomp-ee] For a background as to what WAMP is, please see here. This is a Python implementation of WAMP using Gevent, but you can also configur

simon 121 Nov 22, 2022
A Security Tool for Enumerating WebSockets

STEWS: Security Testing and Enumeration of WebSockets STEWS is a tool suite for security testing of WebSockets This research was first presented at OW

175 Jan 01, 2023
Whatsapp Clone using django, django-channels and websocket

whatsapp-clone Whatsapp Clone using django, django-channels and websocket Features : Signup/Login One on One personal chat with other user Some screen

Anshu Pal 14 Dec 25, 2022
Django Channels HTTP/WebSocket server

daphne Daphne is a HTTP, HTTP2 and WebSocket protocol server for ASGI and ASGI-HTTP, developed to power Django Channels. It supports automatic negotia

Django 1.9k Dec 31, 2022
Terminals served by tornado websockets

This is a Tornado websocket backend for the Xterm.js Javascript terminal emulator library. It evolved out of pyxterm, which was part of GraphTerm (as

Project Jupyter 332 Dec 27, 2022
tiny multi-threaded socks4 server implemented in python2

tiny, multi-threaded socks4a server implemented in python2.

4 Sep 21, 2022
alien.py - Python interface to websocket endpoint of ALICE Grid Services

alien.py - Python interface to websocket endpoint of ALICE Grid Services Quick containerized testing: singularity

Adrian Sevcenco 6 Dec 14, 2022
Discord.py Connect to Discord voice call with websocket

Discord.py Connect to Discord voice call with websocket

WoahThatsHot 3 Apr 22, 2022