Мои пользователи чата не подключаются друг к другуPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Мои пользователи чата не подключаются друг к другу

Сообщение Anonymous »

Я создаю приватный чат и звоню как по голосовой, так и по видеосвязи, которые проповедуют конфиденциальность, с полной сквозной конфиденциальностью, никакие сообщения не сохраняются или не сохраняются на сервере, и каждое сообщение зашифровано, поэтому никто не сможет его взломать, каждый пользователь получил право вести собственный чат, теперь, что бы я ни делал, чат не работает, я чувствую, что мой файл my Consumer.py написан не очень хорошо, я хочу, чтобы пользователи общались и звонили друг другу по видеосвязи, но они не общаются например, пользователи не общаются друг с другом, как будто они не находятся в одной комнате
import json
import logging
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from chat.models import UserProfile

# Set up the logger
logger = logging.getLogger(__name__)

class SecureChatConsumer(AsyncWebsocketConsumer):

async def connect(self):
self.user = self.scope['user']
self.friend_username = self.scope['url_route']['kwargs']
['username']

if not self.user.is_authenticated:
await self.close()
return

if not self.friend_username or not isinstance(self.friend_username, str):
logger.error("Friend username is missing or invalid during WebSocket connection.")
await self.close()
return

try:
# Create a shared room name between both users for proper communication
self.room_name = f"chat_{'_'.join(sorted([self.user.username, self.friend_username]))}"

await self.channel_layer.group_add(self.room_name, self.channel_name)
await self.update_user_status(online=True)
await self.accept()
logger.info(f"WebSocket connection established for user {self.user.username} in room {self.room_name}")
except Exception as e:
logger.error(f"Error during WebSocket connection: {e}")
await self.close()

async def disconnect(self, close_code):
await self.channel_layer.group_discard(self.room_name, self.channel_name)
await self.update_user_status(online=False)
logger.info(f"WebSocket disconnected for user {self.user.username}")

async def receive(self, text_data):
"""
Handle incoming WebSocket messages. Distinguish between message events, WebRTC events, and other types.
"""
try:
data = json.loads(text_data)
message_type = data.get('type')
logger.info(f"Received message of type '{message_type}' from {self.user.username}")
except json.JSONDecodeError as e:
logger.error(f"Error parsing message data: {e}")
await self.send_error("Invalid JSON format.")
return

if message_type == 'message':
await self.handle_message_event(data)
elif message_type in ['call_offer', 'call_answer', 'ice_candidate']:
await self.handle_webrtc_event(data)
elif message_type == 'public_key':
await self.handle_key_exchange(data)
elif message_type == 'user_status':
await self.handle_user_status(data)
else:
logger.warning(f"Unknown message type received: {message_type}")
await self.send_error("Unknown message type.")

async def handle_message_event(self, data):
"""
Handle secure chat message events between two users using end-to-end encryption.
"""
message = data.get('message')
recipient_username = data.get('to')

if message and recipient_username:
logger.info(f"Forwarding encrypted message from {self.user.username} to {recipient_username}")
await self.forward_message(recipient_username, message, data.get('iv'))

async def forward_message(self, recipient_username, message, iv):
"""
Forward an encrypted message to the specified recipient.
"""
await self.channel_layer.group_send(
f"chat_{'_'.join(sorted([self.user.username, recipient_username]))}",
{
'type': 'chat_message',
'message': message,
'iv': iv,
'sender': self.user.username
}
)

async def chat_message(self, event):
"""
Deliver the chat message to the WebSocket client.
"""
await self.send(text_data=json.dumps({
'type': 'message',
'message': event['message'],
'iv': event['iv'],
'sender': event['sender']
}))

async def handle_webrtc_event(self, data):
"""
Handle WebRTC signaling for peer-to-peer voice and video calls.
"""
recipient_username = data.get('to')
event_type = data['type']
event_data = data['data']

if recipient_username:
await self.forward_webrtc_signal(recipient_username, event_type, event_data)

async def forward_webrtc_signal(self, recipient_username, signal_type, data):
"""
Forward WebRTC signaling data to the specified recipient.
"""
if not recipient_username:
logger.error("Recipient username is missing for WebRTC signal.")
return

await self.channel_layer.group_send(
f"chat_{'_'.join(sorted([self.user.username, recipient_username]))}",
{
'type': signal_type,
'data': data,
'sender': self.user.username
}
)

async def call_offer(self, event):
"""
Send a WebRTC call offer to the recipient.
"""
await self.send(text_data=json.dumps({
'type': 'call_offer',
'data': event['data'],
'from': event['sender']
}))

async def call_answer(self, event):
"""
Send a WebRTC call answer to the recipient.
"""
await self.send(text_data=json.dumps({
'type': 'call_answer',
'data': event['data'],
'from': event['sender']
}))

async def ice_candidate(self, event):
"""
Send an ICE candidate to the recipient to assist in the WebRTC connection setup.
"""
await self.send(text_data=json.dumps({
'type': 'ice_candidate',
'data': event['data'],
'from': event['sender']
}))

async def handle_key_exchange(self, data):
"""
Handle the exchange of public keys for secure messaging.
"""
recipient_username = data.get('to')
public_key = data.get('publicKey')

if public_key and recipient_username:
await self.forward_public_key(recipient_username, public_key)

async def forward_public_key(self, recipient_username, public_key):
"""
Forward the public key to the specified recipient.
"""
await self.channel_layer.group_send(
f"chat_{'_'.join(sorted([self.user.username, recipient_username]))}",
{
'type': 'public_key',
'publicKey': public_key,
'sender': self.user.username
}
)

async def public_key(self, event):
"""
Deliver the public key to the WebSocket client.
"""
await self.send(text_data=json.dumps({
'type': 'public_key',
'publicKey': event['publicKey'],
'sender': event['sender']
}))

async def handle_user_status(self, data):
"""
Handle user status updates (online/offline).
"""
recipient_username = data.get('to')
status = data.get('status')

if recipient_username and status:
await self.forward_user_status(recipient_username, status)

async def forward_user_status(self, recipient_username, status):
"""
Forward the user status to the specified recipient.
"""
await self.channel_layer.group_send(
f"chat_{'_'.join(sorted([self.user.username, recipient_username]))}",
{
'type': 'user_status',
'status': status,
'sender': self.user.username
}
)

async def user_status(self, event):
"""
Deliver the user status update to the WebSocket client.
"""
await self.send(text_data=json.dumps({
'type': 'user_status',
'status': event['status'],
'sender': event['sender']
}))

@database_sync_to_async
def update_user_status(self, online):
"""
Update the user's online status in the database.
"""
try:
user_profile = UserProfile.objects.get(username=self.user.username)
user_profile.online = online
user_profile.save()
except UserProfile.DoesNotExist:
logger.error(f"User profile not found for {self.user.username}")

async def send_error(self, message):
"""
Send an error message to the client.
"""
await self.send(text_data=json.dumps({
'status': 'error',
'message': message
}))

это тоже мой код JavaScript,
let sharedKey = null;
let localECDHPrivateKey = null;
let peerConnection = null;
let localStream = null;

document.addEventListener("DOMContentLoaded", function () {
const socketProtocol = window.location.protocol === "https:" ? "wss" : "ws";
const chatSocket = new WebSocket(`${socketProtocol}://${window.location.host}/ws/chat/${friendUsername}/`);

chatSocket.onopen = () => {
console.log("WebSocket connection established.");
securelyExchangeKeys();
sendUserStatus('online'); // Notify the friend that the current user is online
};

chatSocket.onmessage = async function (event) {
const data = JSON.parse(event.data);

if (data.type === 'public_key') {
console.log('Received public key from the friend.');
await handlePublicKey(data);
} else if (data.type === 'message') {
await handleIncomingMessage(data.message, data.iv, data.sender);
} else if (['call_offer', 'call_answer', 'ice_candidate'].includes(data.type)) {
handleWebRTCSignal(data);
} else if (data.type === 'user_status') {
updateUserStatus(data.sender, data.status);
} else {
console.warn("Unhandled message type received:", data.type);
}
};

chatSocket.onclose = () => {
console.log("WebSocket connection closed.");
sendUserStatus('offline'); // Notify the friend that the current user is offline
};
chatSocket.onerror = (error) => console.error("WebSocket error:", error);

async function securelyExchangeKeys() {
try {
const keyPair = await window.crypto.subtle.generateKey(
{ name: 'ECDH', namedCurve: 'P-256' },
true,
['deriveKey']
);

localECDHPrivateKey = keyPair.privateKey;
const exportedPublicKey = await window.crypto.subtle.exportKey('raw', keyPair.publicKey);

chatSocket.send(JSON.stringify({
type: 'public_key',
publicKey: Array.from(new Uint8Array(exportedPublicKey)),
to: friendUsername
}));

console.log('Public key sent for secure key exchange.');
} catch (error) {
console.error("Error during key generation or public key export:", error);
}
}

async function handlePublicKey(data) {
const publicKeyArray = new Uint8Array(data.publicKey);
try {
const importedPublicKey = await window.crypto.subtle.importKey(
'raw',
publicKeyArray.buffer,
{ name: 'ECDH', namedCurve: 'P-256' },
true,
[]
);
sharedKey = await window.crypto.subtle.deriveKey(
{
name: 'ECDH',
public: importedPublicKey
},
localECDHPrivateKey,
{
name: 'AES-GCM',
length: 256
},
false,
['encrypt', 'decrypt']
);
console.log('Shared key successfully derived for secure messaging!');
} catch (error) {
console.error("Error deriving shared key:", error);
}
}

async function handleIncomingMessage(encryptedMessage, iv, sender) {
try {
const decryptedMessage = await decryptMessage(sharedKey, encryptedMessage, iv);
displayDecryptedMessage(sender || 'Friend', decryptedMessage);
} catch (error) {
console.error("Decryption error:", error);
}
}

async function decryptMessage(sharedKey, encryptedMessage, iv) {
try {
const ivArray = new Uint8Array(iv);
const ciphertext = new Uint8Array(encryptedMessage);
const decrypted = await window.crypto.subtle.decrypt({ name: 'AES-GCM', iv: ivArray }, sharedKey, ciphertext);
return new TextDecoder().decode(decrypted);
} catch (error) {
console.error("Decryption error:", error);
throw error;
}
}

async function encryptMessage(sharedKey, message) {
try {
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const encodedMessage = new TextEncoder().encode(message);
const ciphertext = await window.crypto.subtle.encrypt({ name: 'AES-GCM', iv }, sharedKey, encodedMessage);
return { ciphertext: Array.from(new Uint8Array(ciphertext)), iv: Array.from(iv) };
} catch (error) {
console.error("Encryption error:", error);
throw error;
}
}

function displayDecryptedMessage(sender, message) {
const chatLog = document.getElementById('chat-log');
const messageElement = document.createElement('div');
messageElement.className = 'message';
messageElement.innerHTML = `${sender}: ${message}`;
chatLog.appendChild(messageElement);
}

const sendButton = document.getElementById('send-button');
sendButton.addEventListener('click', async () => {
const messageInput = document.getElementById('message-input');
const message = messageInput ? messageInput.value.trim() : '';

if (message !== '' && sharedKey) {
try {
const { ciphertext, iv } = await encryptMessage(sharedKey, message);
chatSocket.send(JSON.stringify({ type: 'message', message: ciphertext, iv: iv, sender: currentUser, to: friendUsername }));
messageInput.value = '';
displayDecryptedMessage('You', message);
} catch (error) {
console.error("Error encrypting message:", error);
}
} else {
console.warn("Shared key is not ready or message is empty.");
}
});

function sendUserStatus(status) {
chatSocket.send(JSON.stringify({ type: 'user_status', status: status, sender: currentUser }));
}

function updateUserStatus(username, status) {
const statusElement = document.getElementById(`status-${username}`);
if (statusElement) {
statusElement.textContent = status === 'online' ? 'Online' : 'Offline';
statusElement.classList.toggle('online', status === 'online');
statusElement.classList.toggle('offline', status !== 'online');
}
}

// WebRTC Signal Handling
async function handleWebRTCSignal(data) {
if (!peerConnection) setupPeerConnection();

switch (data.type) {
case 'call_offer':
await peerConnection.setRemoteDescription(new RTCSessionDescription(data.data));
const answer = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(answer);
chatSocket.send(JSON.stringify({ type: 'call_answer', data: answer, to: friendUsername }));
break;
case 'call_answer':
await peerConnection.setRemoteDescription(new RTCSessionDescription(data.data));
break;
case 'ice_candidate':
if (data.data) {
await peerConnection.addIceCandidate(new RTCIceCandidate(data.data));
}
break;
default:
console.warn("Unhandled WebRTC signal:", data.type);
}
}

async function startVideoCall() {
setupPeerConnection();
try {
localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));
displayLocalVideoStream(localStream);

const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
chatSocket.send(JSON.stringify({ type: 'call_offer', data: offer, to: friendUsername }));
} catch (error) {
console.error("Error starting video call:", error);
}
}

async function startVoiceCall() {
setupPeerConnection();
try {
localStream = await navigator.mediaDevices.getUserMedia({ audio: true });
localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));

const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
chatSocket.send(JSON.stringify({ type: 'call_offer', data: offer, to: friendUsername }));
} catch (error) {
console.error("Error starting voice call:", error);
}
}

function setupPeerConnection() {
peerConnection = new RTCPeerConnection({ iceServers: [{ urls: "stun:stun.l.google.com:19302" }] });

peerConnection.onicecandidate = (event) => {
if (event.candidate) {
chatSocket.send(JSON.stringify({ type: 'ice_candidate', data: event.candidate, to: friendUsername }));
}
};

peerConnection.ontrack = (event) => {
const remoteVideoElement = document.getElementById('remoteVideo');
if (remoteVideoElement) {
remoteVideoElement.srcObject = event.streams[0];
remoteVideoElement.play();
}
};
}

function displayLocalVideoStream(stream) {
const localVideoElement = document.getElementById('localVideo');
if (localVideoElement) {
localVideoElement.srcObject = stream;
localVideoElement.play();
}
}

window.addEventListener('beforeunload', () => {
if (peerConnection) {
peerConnection.close();
}
});});

это также мой файл Chats.html
{% extends "chat/Base.html" %}
{% load static %}

{% block content %}









Friends





{{ friend.name }}
Offline



























const friendUsername = "{{ friend.username }}"; // Assign friend's username to a JS variable


{% endblock %}


Подробнее здесь: https://stackoverflow.com/questions/790 ... each-other
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Мои пользователи чата не подключаются друг к другу
    Anonymous » » в форуме Python
    0 Ответы
    14 Просмотры
    Последнее сообщение Anonymous
  • Мои пользователи чата не подключаются друг к другу
    Anonymous » » в форуме Python
    0 Ответы
    13 Просмотры
    Последнее сообщение Anonymous
  • Сгруппированные пузыри или пузыри близко друг к другу?
    Anonymous » » в форуме Python
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous
  • Сгруппированные пузыри или пузыри близко друг к другу?
    Anonymous » » в форуме Python
    0 Ответы
    24 Просмотры
    Последнее сообщение Anonymous
  • Как удалить контуры, расположенные слишком близко друг к другу по осям X OPENCV — PYTHON
    Anonymous » » в форуме Python
    0 Ответы
    26 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»