Notes![what is notes.io? What is notes.io?](/theme/images/whatisnotesio.png)
![]() ![]() Notes - notes.io |
'channels',
]
# ASGI setup for Channels
ASGI_APPLICATION = 'social_app.asgi.application'
# Redis setup for WebSocket handling
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)], # Redis server
},
},
}
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from social_app.routing import websocket_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'social_app.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/chat/<str:username>/', consumers.ChatConsumer.as_asgi()),
]
from django.db import models
from django.contrib.auth.models import User
class Conversation(models.Model):
participants = models.ManyToManyField(User, related_name='conversations')
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Conversation between {', '.join([p.username for p in self.participants.all()])}"
class Message(models.Model):
conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='messages')
sender = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.sender}: {self.content[:20]}"
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from .models import Conversation, Message
from django.contrib.auth.models import User
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.username = self.scope['url_route']['kwargs']['username']
self.user = self.scope['user']
# Ensure the user is authenticated
if not self.user.is_authenticated:
await self.close()
# Create a unique group name for the conversation
self.chat_group_name = f"chat_{min(self.username, self.user.username)}_{max(self.username, self.user.username)}"
# Join the chat group
await self.channel_layer.group_add(
self.chat_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave the chat group
await self.channel_layer.group_discard(
self.chat_group_name,
self.channel_name
)
async def receive(self, text_data):
data = json.loads(text_data)
message = data['message']
# Save message to the database
recipient = User.objects.get(username=self.username)
conversation, created = Conversation.objects.get_or_create()
conversation.participants.add(self.user, recipient)
Message.objects.create(conversation=conversation, sender=self.user, content=message)
# Broadcast the message to the group
await self.channel_layer.group_send(
self.chat_group_name,
{
'type': 'chat_message',
'message': message,
'sender': self.user.username,
}
)
async def chat_message(self, event):
# Send the message to WebSocket
await self.send(text_data=json.dumps({
'message': event['message'],
'sender': event['sender'],
}))
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User
def chat_view(request, username):
user_to_chat = get_object_or_404(User, username=username)
return render(request, 'chat/live_chat.html', {'chat_user': user_to_chat})
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h3>Chat with {{ chat_user.username }}</h3>
<div id="chat-log" style="border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: auto;"></div>
<textarea id="chat-message-input" rows="3" style="width: 100%;"></textarea>
<button id="chat-message-submit" class="btn btn-primary mt-2">Send</button>
</div>
<script>
const chatSocket = new WebSocket(
'ws://' + window.location.host + '/ws/chat/{{ chat_user.username }}/'
);
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
const messageLog = document.querySelector('#chat-log');
messageLog.innerHTML += `<div><strong>${data.sender}:</strong> ${data.message}</div>`;
};
document.querySelector('#chat-message-submit').onclick = function(e) {
const messageInput = document.querySelector('#chat-message-input');
const message = messageInput.value;
chatSocket.send(JSON.stringify({ 'message': message }));
messageInput.value = '';
};
</script>
{% endblock %}
![]() |
Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 14 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team