the tabulations must die

This commit is contained in:
AdrienLSH
2024-02-08 12:47:10 +01:00
parent 9aa885c49d
commit f6bb48e772
32 changed files with 1070 additions and 1070 deletions

View File

@ -8,244 +8,244 @@ import json
class ChatConsumer(WebsocketConsumer):
def connect(self):
def connect(self):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
channel_id : int = int(self.scope['url_route']['kwargs']['chat_id'])
channel_id : int = int(self.scope['url_route']['kwargs']['chat_id'])
if ChatMemberModel.objects.filter(member_id=user.pk, channel_id=int(channel_id)).count() != 1:
return
if ChatMemberModel.objects.filter(member_id=user.pk, channel_id=int(channel_id)).count() != 1:
return
if (self.channel_layer == None):
return
if (self.channel_layer == None):
return
self.room_group_name = f'chat{channel_id}'
self.room_group_name = f'chat{channel_id}'
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
self.accept()
def receive(self, text_data=None, bytes_data=None):
def receive(self, text_data=None, bytes_data=None):
if text_data == None:
return
if text_data == None:
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
text_data_json: dict = json.loads(text_data)
message = text_data_json.get('message')
if (message is None):
return
receivers_id = text_data_json.get('receivers_id')
if (receivers_id is None):
return
text_data_json: dict = json.loads(text_data)
message = text_data_json.get('message')
if (message is None):
return
receivers_id = text_data_json.get('receivers_id')
if (receivers_id is None):
return
channel_id : int = int(self.scope['url_route']['kwargs']['chat_id'])
channel_id : int = int(self.scope['url_route']['kwargs']['chat_id'])
if ChatMemberModel.objects.filter(member_id = user.pk, channel_id = channel_id).count() != 1:
return
if ChatMemberModel.objects.filter(member_id = user.pk, channel_id = channel_id).count() != 1:
return
if (self.channel_layer == None):
return
if (self.channel_layer == None):
return
message_time: int = int(time.time() * 1000)
if (len(receivers_id) == 1 and
BlockModel.objects.filter(blocker=user.pk, blocked=receivers_id[0]) or
BlockModel.objects.filter(blocker=receivers_id[0], blocked=user.pk)
):
return
message_time: int = int(time.time() * 1000)
if (len(receivers_id) == 1 and
BlockModel.objects.filter(blocker=user.pk, blocked=receivers_id[0]) or
BlockModel.objects.filter(blocker=receivers_id[0], blocked=user.pk)
):
return
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type':'chat_message',
'author_id':user.pk,
'content':message,
'time':message_time,
}
)
new_message = ChatMessageModel(
channel_id = channel_id,
author_id = user.pk,
content = message,
time = message_time
).save()
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type':'chat_message',
'author_id':user.pk,
'content':message,
'time':message_time,
}
)
new_message = ChatMessageModel(
channel_id = channel_id,
author_id = user.pk,
content = message,
time = message_time
).save()
def chat_message(self, event):
def chat_message(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
channel_id: int = int(self.scope['url_route']['kwargs']['chat_id'])
channel_id: int = int(self.scope['url_route']['kwargs']['chat_id'])
if ChatMemberModel.objects.filter(member_id=user.pk, channel_id=channel_id).count() != 1:
return
if ChatMemberModel.objects.filter(member_id=user.pk, channel_id=channel_id).count() != 1:
return
self.send(text_data=json.dumps({
'type':'chat',
'author_id':event['author_id'],
'content':event['content'],
'time': event['time'],
}))
self.send(text_data=json.dumps({
'type':'chat',
'author_id':event['author_id'],
'content':event['content'],
'time': event['time'],
}))
class ChatNoticeConsumer(WebsocketConsumer):
def connect(self):
def connect(self):
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
if (self.channel_layer == None):
return
if (self.channel_layer == None):
return
self.room_group_name = f'chatNotice{user.pk}'
if (not hasattr(self.channel_layer, "users_channels")):
self.channel_layer.users_channels = {}
self.channel_layer.users_channels[user.pk] = self.channel_name
self.room_group_name = f'chatNotice{user.pk}'
if (not hasattr(self.channel_layer, "users_channels")):
self.channel_layer.users_channels = {}
self.channel_layer.users_channels[user.pk] = self.channel_name
if (not hasattr(self.channel_layer, "invite")):
self.channel_layer.invite = {}
self.channel_layer.invite[user.pk] = [];
if (not hasattr(self.channel_layer, "invite")):
self.channel_layer.invite = {}
self.channel_layer.invite[user.pk] = [];
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
self.accept()
message_time: int = int(time.time() * 1000)
targets = list(self.channel_layer.users_channels.keys())
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or target == user.pk):
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':"online_users",
'author_id':user.pk,
'time':message_time,
})
message_time: int = int(time.time() * 1000)
targets = list(self.channel_layer.users_channels.keys())
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or target == user.pk):
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':"online_users",
'author_id':user.pk,
'time':message_time,
})
def disconnect(self, code):
def disconnect(self, code):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
self.channel_layer.users_channels.pop(user.pk)
self.channel_layer.users_channels.pop(user.pk)
message_time: int = int(time.time() * 1000)
message_time: int = int(time.time() * 1000)
targets = list(self.channel_layer.users_channels.keys())
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or target == user.pk):
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':"online_users",
'author_id':user.pk,
'time':message_time,
})
targets = list(self.channel_layer.users_channels.keys())
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or target == user.pk):
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':"online_users",
'author_id':user.pk,
'time':message_time,
})
def receive(self, text_data=None, bytes_data=None):
def receive(self, text_data=None, bytes_data=None):
if text_data == None:
return
if text_data == None:
return
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
text_data_json = json.loads(text_data)
type_notice = text_data_json.get('type')
targets : list = text_data_json.get('targets')
content : dict = text_data_json.get('content')
text_data_json = json.loads(text_data)
type_notice = text_data_json.get('type')
targets : list = text_data_json.get('targets')
content : dict = text_data_json.get('content')
if (type_notice == None or targets == None):
return
if (type_notice == None or targets == None):
return
if (self.channel_layer == None):
return
if (self.channel_layer == None):
return
message_time: int = int(time.time() * 1000)
status = 200;
message_time: int = int(time.time() * 1000)
status = 200;
#print("receive" + str(user.pk))
#print("receive" + str(user.pk))
if targets == "all":
targets = list(self.channel_layer.users_channels.keys())
if targets == "all":
targets = list(self.channel_layer.users_channels.keys())
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or target == user.pk):
if (channel == None):
status = 404
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':type_notice,
'author_id':user.pk,
'content':content,
'time':message_time,
'status': 200,
})
async_to_sync(self.channel_layer.send)(self.channel_layer.users_channels.get(user.pk), {
'type':type_notice,
'author_id':user.pk,
'content':"notice return",
'time':message_time,
'status':status,
})
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or target == user.pk):
if (channel == None):
status = 404
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':type_notice,
'author_id':user.pk,
'content':content,
'time':message_time,
'status': 200,
})
async_to_sync(self.channel_layer.send)(self.channel_layer.users_channels.get(user.pk), {
'type':type_notice,
'author_id':user.pk,
'content':"notice return",
'time':message_time,
'status':status,
})
def invite(self, event):
def invite(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
if (self.channel_layer.invite[event["author_id"]].get(user.pk)):
return
self.channel_layer.invite[event["author_id"]].append(user.pl)
if (self.channel_layer.invite[event["author_id"]].get(user.pk)):
return
self.channel_layer.invite[event["author_id"]].append(user.pl)
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'content':event['content'],
'time': event['time'],
'status':event['status'],
}))
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'content':event['content'],
'time': event['time'],
'status':event['status'],
}))
def online_users(self, event):
def online_users(self, event):
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
#print("online_users" + str(user.pk))
#print("online_users" + str(user.pk))
event['content'] = self.channel_layer.users_channels
event['content'] = self.channel_layer.users_channels
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'content':event['content'],
'time': event['time'],
'status':event['status'],
}))
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'content':event['content'],
'time': event['time'],
'status':event['status'],
}))

View File

@ -9,371 +9,371 @@ import json
class ChatNoticeConsumer(WebsocketConsumer):
def connect(self):
def connect(self):
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
if (self.channel_layer == None):
return
self.room_group_name = f'chatNotice{user.pk}'
if (not hasattr(self.channel_layer, "users_channels")):
self.channel_layer.users_channels = {}
self.channel_layer.users_channels[user.pk] = self.channel_name
if (not hasattr(self.channel_layer, "invite")):
self.channel_layer.invite = {}
self.channel_layer.invite[user.pk] = [];
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
self.sync()
def disconnect(self, code):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
del self.channel_layer.users_channels[user.pk]
del self.channel_layer.invite[user.pk]
for inviter_id, inviteds_id in self.channel_layer.invite.items():
if (user.pk in inviteds_id):
self.channel_layer.invite[inviter_id].remove(user.pk)
self.sync()
def receive(self, text_data=None, bytes_data=None):
if text_data == None:
return
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
text_data_json = json.loads(text_data)
type_notice = text_data_json.get('type')
targets : list = text_data_json.get('targets')
content : dict = text_data_json.get('content')
if (type_notice == None or targets == None):
return
if (self.channel_layer == None):
return
message_time: int = text_data_json.get('time')
if (message_time == None):
message_time: int = int(time.time() * 1000)
result = None
try:
status, result = getattr(self, "pre_" + type_notice)(user, targets)
except AttributeError as error:
status = 200
if (status < 300):
if targets == "all":
targets = list(self.channel_layer.users_channels.keys())
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or target == user.pk):
if (channel == None):
status = 444 # target not connected
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':type_notice,
'author_id':user.pk,
'content':content,
'result':result,
'targets': targets,
'time':message_time,
'status': 200,
})
async_to_sync(self.channel_layer.send)(self.channel_layer.users_channels.get(user.pk), {
'type':type_notice,
'author_id':user.pk,
'result':result,
'targets': targets,
'time':message_time,
'status':status,
})
def sync(self, user = None, level = None):
sendToUser = True
if (user == None):
user = self.scope["user"]
sendToUser = False
if (level == None):
level = 0
message_time: int = int(time.time() * 1000)
if (sendToUser):
targets = [user.pk]
else:
targets = list(self.channel_layer.users_channels.keys())
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or (not sendToUser and target == user.pk)):
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':"online_users",
'author_id':user.pk,
'targets': targets,
'time':message_time,
'status': 200,
})
if (level >= 1):
async_to_sync(self.channel_layer.send)(channel, {
'type':"invite",
'author_id':user.pk,
'targets': targets,
'time':message_time,
'status': 200,
})
def pre_invite(self, user, targets):
if (user.is_anonymous or not user.is_authenticated):
return 400, None
status = 200
for target in targets:
if (target in self.channel_layer.invite[user.pk]):
status = 409
continue
channel = self.channel_layer.users_channels.get(target)
if (channel == None):
status = 404
continue
# Add the invited in "self.channel_layer.invite"
if (user.pk != target):
self.channel_layer.invite[user.pk].append(target)
return status, None
def get_invites(self, user):
invites = []
for inviter_id, inviteds_id in self.channel_layer.invite.items():
if (user.pk in inviteds_id and user.pk != inviter_id):
invites.append(inviter_id)
return invites;
def invite(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
invites = self.get_invites(user)
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'invites': invites,
'targets': event['targets'],
'time': event['time'],
'status':event['status'],
}))
def pre_accept_invite(self, user, targets):
if (user.is_anonymous or not user.is_authenticated):
return 400, None
if (user.pk not in self.channel_layer.invite[targets[0]]):
return 400, None
self.channel_layer.invite[targets[0]].remove(user.pk)
if (self.channel_layer == None):
return
self.room_group_name = f'chatNotice{user.pk}'
if (not hasattr(self.channel_layer, "users_channels")):
self.channel_layer.users_channels = {}
self.channel_layer.users_channels[user.pk] = self.channel_name
if (not hasattr(self.channel_layer, "invite")):
self.channel_layer.invite = {}
self.channel_layer.invite[user.pk] = [];
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
self.sync()
def disconnect(self, code):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
del self.channel_layer.users_channels[user.pk]
del self.channel_layer.invite[user.pk]
for inviter_id, inviteds_id in self.channel_layer.invite.items():
if (user.pk in inviteds_id):
self.channel_layer.invite[inviter_id].remove(user.pk)
self.sync()
def receive(self, text_data=None, bytes_data=None):
if text_data == None:
return
user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated):
#return
text_data_json = json.loads(text_data)
type_notice = text_data_json.get('type')
targets : list = text_data_json.get('targets')
content : dict = text_data_json.get('content')
if (type_notice == None or targets == None):
return
if (self.channel_layer == None):
return
message_time: int = text_data_json.get('time')
if (message_time == None):
message_time: int = int(time.time() * 1000)
result = None
try:
status, result = getattr(self, "pre_" + type_notice)(user, targets)
except AttributeError as error:
status = 200
if (status < 300):
if targets == "all":
targets = list(self.channel_layer.users_channels.keys())
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or target == user.pk):
if (channel == None):
status = 444 # target not connected
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':type_notice,
'author_id':user.pk,
'content':content,
'result':result,
'targets': targets,
'time':message_time,
'status': 200,
})
async_to_sync(self.channel_layer.send)(self.channel_layer.users_channels.get(user.pk), {
'type':type_notice,
'author_id':user.pk,
'result':result,
'targets': targets,
'time':message_time,
'status':status,
})
def sync(self, user = None, level = None):
sendToUser = True
if (user == None):
user = self.scope["user"]
sendToUser = False
if (level == None):
level = 0
message_time: int = int(time.time() * 1000)
if (sendToUser):
targets = [user.pk]
else:
targets = list(self.channel_layer.users_channels.keys())
for target in targets:
channel = self.channel_layer.users_channels.get(target)
if (channel == None or (not sendToUser and target == user.pk)):
continue
async_to_sync(self.channel_layer.send)(channel, {
'type':"online_users",
'author_id':user.pk,
'targets': targets,
'time':message_time,
'status': 200,
})
if (level >= 1):
async_to_sync(self.channel_layer.send)(channel, {
'type':"invite",
'author_id':user.pk,
'targets': targets,
'time':message_time,
'status': 200,
})
def pre_invite(self, user, targets):
if (user.is_anonymous or not user.is_authenticated):
return 400, None
status = 200
for target in targets:
if (target in self.channel_layer.invite[user.pk]):
status = 409
continue
channel = self.channel_layer.users_channels.get(target)
if (channel == None):
status = 404
continue
# Add the invited in "self.channel_layer.invite"
if (user.pk != target):
self.channel_layer.invite[user.pk].append(target)
return status, None
def get_invites(self, user):
invites = []
for inviter_id, inviteds_id in self.channel_layer.invite.items():
if (user.pk in inviteds_id and user.pk != inviter_id):
invites.append(inviter_id)
return invites;
def invite(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
invites = self.get_invites(user)
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'invites': invites,
'targets': event['targets'],
'time': event['time'],
'status':event['status'],
}))
def pre_accept_invite(self, user, targets):
if (user.is_anonymous or not user.is_authenticated):
return 400, None
if (user.pk not in self.channel_layer.invite[targets[0]]):
return 400, None
self.channel_layer.invite[targets[0]].remove(user.pk)
if (targets[0] in self.channel_layer.invite[user.pk]):
self.channel_layer.invite[user.pk].remove(targets[0])
if (targets[0] in self.channel_layer.invite[user.pk]):
self.channel_layer.invite[user.pk].remove(targets[0])
id_game = GameModel().create([user.pk, targets[0]]);
id_game = GameModel().create([user.pk, targets[0]]);
return 200, id_game
return 200, id_game
def accept_invite(self, event):
def accept_invite(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
invites = self.get_invites(user)
invites = self.get_invites(user)
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'id_game': event['result'],
'invites': invites,
'time': event['time'],
'status':event['status'],
}))
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'id_game': event['result'],
'invites': invites,
'time': event['time'],
'status':event['status'],
}))
def pre_refuse_invite(self, user, targets):
def pre_refuse_invite(self, user, targets):
if (user.is_anonymous or not user.is_authenticated):
return 400, None
if (user.is_anonymous or not user.is_authenticated):
return 400, None
if (user.pk not in self.channel_layer.invite[targets[0]]):
return 400, None
if (user.pk not in self.channel_layer.invite[targets[0]]):
return 400, None
self.channel_layer.invite[targets[0]].remove(user.pk)
self.channel_layer.invite[targets[0]].remove(user.pk)
if (targets[0] in self.channel_layer.invite[user.pk]):
self.channel_layer.invite[user.pk].remove(targets[0])
if (targets[0] in self.channel_layer.invite[user.pk]):
self.channel_layer.invite[user.pk].remove(targets[0])
return 200, None
def refuse_invite(self, event):
return 200, None
def refuse_invite(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
invites = self.get_invites(user)
invites = self.get_invites(user)
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'invites': invites,
'time': event['time'],
'status':event['status'],
}))
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'invites': invites,
'time': event['time'],
'status':event['status'],
}))
def pre_ask_friend(self, user, targets):
def pre_ask_friend(self, user, targets):
if (user.is_anonymous or not user.is_authenticated):
return 400, None
if (user.is_anonymous or not user.is_authenticated):
return 400, None
if (AskFriendModel.objects.filter(asker=user.pk, asked=targets[0])):
return 409, None
if (AskFriendModel.objects.filter(asker=user.pk, asked=targets[0])):
return 409, None
if (FriendModel().isFriend(user.pk, targets[0])):
return 409, None
if (FriendModel().isFriend(user.pk, targets[0])):
return 409, None
if (targets[0] != None):
AskFriendModel(asker=user.pk, asked=targets[0]).save()
if (targets[0] != None):
AskFriendModel(asker=user.pk, asked=targets[0]).save()
return 200, None
return 200, None
def send_ask_friend(self, event):
def send_ask_friend(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
asked = AskFriendModel().getAsked(user.pk)
asker = AskFriendModel().getAsker(user.pk)
asked = AskFriendModel().getAsked(user.pk)
asker = AskFriendModel().getAsker(user.pk)
online_friends = self.get_online_friend(user)
online_friends = self.get_online_friend(user)
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'targets':event['targets'],
'asker': asker,
'asked': asked,
'online': online_friends,
'time': event['time'],
'status':event['status'],
}))
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'targets':event['targets'],
'asker': asker,
'asked': asked,
'online': online_friends,
'time': event['time'],
'status':event['status'],
}))
def ask_friend(self, event):
self.send_ask_friend(event)
def ask_friend(self, event):
self.send_ask_friend(event)
def delete_ask(self, asker, user_asked):
if (user_asked.is_anonymous or not user_asked.is_authenticated):
return 400, None
def delete_ask(self, asker, user_asked):
if (user_asked.is_anonymous or not user_asked.is_authenticated):
return 400, None
asked = user_asked.pk
asked = user_asked.pk
if (not AskFriendModel.objects.filter(asker=asker, asked=asked)):
return 404, None
if (not AskFriendModel.objects.filter(asker=asker, asked=asked)):
return 404, None
if (FriendModel().isFriend(asker, asked)):
return 409, None
if (FriendModel().isFriend(asker, asked)):
return 409, None
if (not AskFriendModel().deleteAsk(asker, asked)):
return 400, None
if (not AskFriendModel().deleteAsk(asker, asked)):
return 400, None
return 200, None
return 200, None
def pre_accept_friend(self, user, targets):
status, result = self.delete_ask(targets[0], user)
if (status == 200):
FriendModel(user_id1=user.pk, user_id2=targets[0]).save()
return status, result
def pre_accept_friend(self, user, targets):
status, result = self.delete_ask(targets[0], user)
if (status == 200):
FriendModel(user_id1=user.pk, user_id2=targets[0]).save()
return status, result
def accept_friend(self, event):
self.send_ask_friend(event)
def accept_friend(self, event):
self.send_ask_friend(event)
def pre_refuse_friend(self, user, targets):
return self.delete_ask(targets[0], user)
def pre_refuse_friend(self, user, targets):
return self.delete_ask(targets[0], user)
def refuse_friend(self, event):
self.send_ask_friend(event)
def refuse_friend(self, event):
self.send_ask_friend(event)
def pre_remove_friend(self, user, targets):
def pre_remove_friend(self, user, targets):
if (user.is_anonymous or not user.is_authenticated):
return 400, None
if (not FriendModel().isFriend(user.pk, targets[0])):
return 409, None
if (user.is_anonymous or not user.is_authenticated):
return 400, None
if (not FriendModel().isFriend(user.pk, targets[0])):
return 409, None
if (not FriendModel().deleteFriend(user.pk, targets[0])):
return 400, None
if (not FriendModel().deleteFriend(user.pk, targets[0])):
return 400, None
return 200, None
def remove_friend(self, event):
self.send_ask_friend(event)
return 200, None
def remove_friend(self, event):
self.send_ask_friend(event)
def get_online_friend(self, user):
online_friends = {}
for friend in FriendModel().getFriends(user.pk):
if (friend in self.channel_layer.users_channels):
online_friends[friend] = "green"
else:
online_friends[friend] = "red"
return online_friends
def get_online_friend(self, user):
online_friends = {}
for friend in FriendModel().getFriends(user.pk):
if (friend in self.channel_layer.users_channels):
online_friends[friend] = "green"
else:
online_friends[friend] = "red"
return online_friends
def online_users(self, event):
def online_users(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
online_friends = self.get_online_friend(user)
online_friends = self.get_online_friend(user)
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'online':online_friends,
'time': event['time'],
'status':event['status'],
}))
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'online':online_friends,
'time': event['time'],
'status':event['status'],
}))

View File

@ -5,28 +5,28 @@ from django.contrib import admin
# Create your models here.
class ChatChannelModel(models.Model):
def create(self, users_id: [int]):
self.save()
for user_id in users_id:
ChatMemberModel(channel_id = self.pk, member_id = user_id).save()
return self.pk
def create(self, users_id: [int]):
self.save()
for user_id in users_id:
ChatMemberModel(channel_id = self.pk, member_id = user_id).save()
return self.pk
def get_members_id(self):
return [member_channel.member_id for member_channel in ChatMemberModel.objects.filter(channel_id = self.pk)]
def get_members_id(self):
return [member_channel.member_id for member_channel in ChatMemberModel.objects.filter(channel_id = self.pk)]
class ChatMemberModel(models.Model):
member_id = IntegerField(primary_key=False)
channel_id = IntegerField(primary_key=False)
member_id = IntegerField(primary_key=False)
channel_id = IntegerField(primary_key=False)
def __str__(self):
return "member_id: " + str(self.member_id) + ", channel_id: " + str(self.channel_id)
def __str__(self):
return "member_id: " + str(self.member_id) + ", channel_id: " + str(self.channel_id)
class ChatMessageModel(models.Model):
channel_id = IntegerField(primary_key=False)
author_id = IntegerField(primary_key=False)
content = models.CharField(max_length=255)
time = IntegerField(primary_key=False)
channel_id = IntegerField(primary_key=False)
author_id = IntegerField(primary_key=False)
content = models.CharField(max_length=255)
time = IntegerField(primary_key=False)
def __str__(self):
return "author_id: " + str(self.author_id) + ", channel_id: " + str(self.channel_id) + ", content: " + self.content
def __str__(self):
return "author_id: " + str(self.author_id) + ", channel_id: " + str(self.channel_id) + ", content: " + self.content

View File

@ -4,6 +4,6 @@ from . import consumersChat
from . import consumersNotice
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<chat_id>\d+)$', consumersChat.ChatConsumer.as_asgi()),
re_path(r'ws/chat/notice$', consumersNotice.ChatNoticeConsumer.as_asgi()),
re_path(r'ws/chat/(?P<chat_id>\d+)$', consumersChat.ChatConsumer.as_asgi()),
re_path(r'ws/chat/notice$', consumersNotice.ChatNoticeConsumer.as_asgi()),
]

View File

@ -6,25 +6,25 @@ from django.contrib.auth.models import User
# Create your tests here.
class ChatTest(TestCase):
def setUp(self):
self.client = Client()
def setUp(self):
self.client = Client()
self.username='bozo1'
self.password='password'
self.username='bozo1'
self.password='password'
self.user: User = User.objects.create_user(username=self.username, password=self.password)
self.user: User = User.objects.create_user(username=self.username, password=self.password)
self.dest: User = User.objects.create_user(username="bozo2", password=self.password)
self.dest: User = User.objects.create_user(username="bozo2", password=self.password)
self.url = "/api/chat/"
self.url = "/api/chat/"
def test_create_chat(self):
self.client.login(username=self.username, password=self.password)
response: HttpResponse = self.client.post(self.url + str(self.user.pk), {"members_id": [self.user.pk, self.dest.pk]})
response_dict: dict = eval(response.content)
self.assertDictEqual(response_dict, {})
def test_create_chat(self):
self.client.login(username=self.username, password=self.password)
response: HttpResponse = self.client.post(self.url + str(self.user.pk), {"members_id": [self.user.pk, self.dest.pk]})
response_dict: dict = eval(response.content)
self.assertDictEqual(response_dict, {})
def test_create_chat_unlogged(self):
response: HttpResponse = self.client.post(self.url + str(self.user.pk), {"members_id": [self.user.pk, self.dest.pk]})
response_dict: dict = eval(response.content)
self.assertDictEqual(response_dict, {'detail': 'Authentication credentials were not provided.'})
def test_create_chat_unlogged(self):
response: HttpResponse = self.client.post(self.url + str(self.user.pk), {"members_id": [self.user.pk, self.dest.pk]})
response_dict: dict = eval(response.content)
self.assertDictEqual(response_dict, {'detail': 'Authentication credentials were not provided.'})

View File

@ -14,35 +14,35 @@ from .serializers import ChatChannelSerializer, ChatMessageSerializer
class ChannelView(APIView):
queryset = ChatChannelModel.objects
serializer_class = ChatChannelSerializer
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
queryset = ChatChannelModel.objects
serializer_class = ChatChannelSerializer
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def post(self, request):
def post(self, request):
serializer = self.serializer_class(data = request.data)
serializer.is_valid(raise_exception=True)
serializer = self.serializer_class(data = request.data)
serializer.is_valid(raise_exception=True)
data: dict = serializer.validated_data
data: dict = serializer.validated_data
members_id = data.get("members_id")
if members_id == None:
return Response({"detail": "members_id is None."}, status = status.HTTP_400_BAD_REQUEST)
members_id = data.get("members_id")
if members_id == None:
return Response({"detail": "members_id is None."}, status = status.HTTP_400_BAD_REQUEST)
if self.request.user.pk not in members_id:
return Response({"detail": "You are trying to create a chat group without you."}, status = status.HTTP_400_BAD_REQUEST)
if self.request.user.pk not in members_id:
return Response({"detail": "You are trying to create a chat group without you."}, status = status.HTTP_400_BAD_REQUEST)
for member_channel in ChatMemberModel.objects.filter(member_id = members_id[0]):
channel_id: int = member_channel.channel_id
if not ChatChannelModel.objects.filter(pk = channel_id).exists():
continue
channel: ChatChannelModel = ChatChannelModel.objects.get(pk = channel_id)
if set(channel.get_members_id()) == set(members_id):
messages = ChatMessageModel.objects.filter(channel_id = channel_id).order_by("time")
messages = serializers.serialize("json", messages)
return Response({'channel_id': channel_id, 'messages': messages}, status=status.HTTP_200_OK)
for member_channel in ChatMemberModel.objects.filter(member_id = members_id[0]):
channel_id: int = member_channel.channel_id
if not ChatChannelModel.objects.filter(pk = channel_id).exists():
continue
channel: ChatChannelModel = ChatChannelModel.objects.get(pk = channel_id)
if set(channel.get_members_id()) == set(members_id):
messages = ChatMessageModel.objects.filter(channel_id = channel_id).order_by("time")
messages = serializers.serialize("json", messages)
return Response({'channel_id': channel_id, 'messages': messages}, status=status.HTTP_200_OK)
new_channel_id = ChatChannelModel().create(members_id)
return Response({'channel_id': new_channel_id}, status=status.HTTP_201_CREATED)
new_channel_id = ChatChannelModel().create(members_id)
return Response({'channel_id': new_channel_id}, status=status.HTTP_201_CREATED)