Block fixed, looking for invite in game

This commit is contained in:
Xamora 2024-01-19 16:48:20 +01:00
parent cdb4dab47a
commit fe47a4d633
9 changed files with 306 additions and 115 deletions

View File

@ -1,6 +1,8 @@
from channels.generic.websocket import WebsocketConsumer from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync from asgiref.sync import async_to_sync
from games.models import GameModel
import time import time
import json import json
@ -31,19 +33,7 @@ class ChatNoticeConsumer(WebsocketConsumer):
self.accept() self.accept()
message_time: int = int(time.time() * 1000) self.sync()
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,
'targets': targets,
'time':message_time,
'status': 200,
})
def disconnect(self, code): def disconnect(self, code):
@ -51,22 +41,15 @@ class ChatNoticeConsumer(WebsocketConsumer):
if (user.is_anonymous or not user.is_authenticated): if (user.is_anonymous or not user.is_authenticated):
return return
self.channel_layer.users_channels.pop(user.pk) del self.channel_layer.users_channels[user.pk]
del self.channel_layer.invite[user.pk]
message_time: int = int(time.time() * 1000) 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()
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,
'targets': targets,
'time':message_time,
'status': 200,
})
def receive(self, text_data=None, bytes_data=None): def receive(self, text_data=None, bytes_data=None):
@ -89,16 +72,25 @@ class ChatNoticeConsumer(WebsocketConsumer):
if (self.channel_layer == None): if (self.channel_layer == None):
return return
message_time: int = int(text_data_json.get('time'))
print(message_time)
print(time.time())
print(time.time() * 1000 - message_time)
if (message_time == None):
message_time: int = int(time.time() * 1000) message_time: int = int(time.time() * 1000)
status = 200;
#print("receive" + str(user.pk)) #print("receive" + str(user.pk))
result = None
try: try:
status = getattr(self, "pre_" + type_notice)(user, targets) status, result = getattr(self, "pre_" + type_notice)(user, targets)
except AttributeError: except AttributeError:
print(f"La fonction pre_{type_notice} n'existe pas.") status = 200
#print(f"La fonction pre_{type_notice} n'existe pas.")
if (status < 300):
if targets == "all": if targets == "all":
targets = list(self.channel_layer.users_channels.keys()) targets = list(self.channel_layer.users_channels.keys())
@ -112,27 +104,83 @@ class ChatNoticeConsumer(WebsocketConsumer):
'type':type_notice, 'type':type_notice,
'author_id':user.pk, 'author_id':user.pk,
'content':content, 'content':content,
'result':result,
'targets': targets, 'targets': targets,
'time':message_time, 'time':message_time,
'status': 200, 'status': 200,
}) })
async_to_sync(self.channel_layer.send)(self.channel_layer.users_channels.get(user.pk), { async_to_sync(self.channel_layer.send)(self.channel_layer.users_channels.get(user.pk), {
'type':type_notice, 'type':type_notice,
'author_id':user.pk, 'author_id':user.pk,
'content':"notice return", 'result':result,
'targets': targets, 'targets': targets,
'time':message_time, 'time':message_time,
'status':status, '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): def pre_invite(self, user, targets):
status = 200
status = 200
for target in targets: for target in targets:
if (target in self.channel_layer.invite[user.pk]): if (target in self.channel_layer.invite[user.pk]):
status = 409 status = 409
return status 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)
def invite(self, event): def invite(self, event):
@ -140,23 +188,48 @@ class ChatNoticeConsumer(WebsocketConsumer):
if (user.is_anonymous or not user.is_authenticated): if (user.is_anonymous or not user.is_authenticated):
return return
if (user.pk in self.channel_layer.invite[event["author_id"]]): invites = self.get_invites(user)
return
if (user.pk != event["author_id"]):
self.channel_layer.invite[event["author_id"]].append(user.pk)
self.send(text_data=json.dumps({ self.send(text_data=json.dumps({
'type':event['type'], 'type':event['type'],
'author_id':event['author_id'], 'author_id':event['author_id'],
'content':event['content'], 'invites': invites,
'targets': event['targets'], 'targets': event['targets'],
'time': event['time'], 'time': event['time'],
'status':event['status'], 'status':event['status'],
})) }))
def pre_online_users(self, user, targets): def pre_accept_invite(self, user, targets):
pass
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])
id_game = GameModel().create([user.pk, targets[0]]);
return 200, id_game
def accept_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'],
'result': event['result'],
'invites': invites,
'time': event['time'],
'status':event['status'],
}))
def online_users(self, event): def online_users(self, event):

View File

@ -78,7 +78,6 @@
border: none; border: none;
outline: none; outline: none;
border-bottom: 0.15em solid green; border-bottom: 0.15em solid green;
caret-color: green;
color: green; color: green;
font-size: 0.8em; font-size: 0.8em;
} }
@ -106,9 +105,8 @@
word-wrap: break-word; word-wrap: break-word;
} }
#app #invite { #app #invite, #app #yes, #app #no {
position: relative; position: relative;
background-color: green;
border: none; border: none;
color: white; color: white;
text-align: center; text-align: center;
@ -118,3 +116,15 @@
width: 4em; width: 4em;
cursor: pointer; cursor: pointer;
} }
#app #yes, #app #no {
position: relative;
border: none;
color: white;
text-align: center;
text-decoration: none;
font-size: 0.8em;
height: 2em;
width: 2em;
cursor: pointer;
}

View File

@ -1,3 +1,4 @@
import { navigateTo } from "../../index.js";
import {create_popup} from "../../utils/noticeUtils.js"; import {create_popup} from "../../utils/noticeUtils.js";
class Notice { class Notice {
@ -7,9 +8,8 @@ class Notice {
// users online, invited by, asked friend by, // users online, invited by, asked friend by,
let data_variable = ["online", "invited", "asked"]; let data_variable = ["online", "invited", "asked"];
for (let i in data_variable) { for (let i in data_variable)
this.data[data_variable[i]] = []; this.data[data_variable[i]] = [];
}
this.connect(); this.connect();
@ -20,12 +20,14 @@ class Notice {
this.chatSocket = new WebSocket(url); this.chatSocket = new WebSocket(url);
this.chatSocket.onmessage = (event) =>{ this.chatSocket.onmessage = (event) =>{
let data = JSON.parse(event.data); let send = JSON.parse(event.data);
//console.log("notice: ", data); console.log("notice: ", send);
if (data.type == "invite") if (send.type == "invite")
this.receiveInvite(data); this.receiveInvite(send);
else if (data.type == "online_users" || data.type == "disconnect") else if (send.type == "online_users" || send.type == "disconnect")
this.receiveOnlineUser(data); this.receiveOnlineUser(send);
else if (send.type == "accept_invite")
this.receiveAcceptInvite(send);
} }
this.chatSocket.onopen = (event) => { this.chatSocket.onopen = (event) => {
this.getOnlineUser(); this.getOnlineUser();
@ -40,61 +42,96 @@ class Notice {
} }
async sendInvite(id_inviter, id_inviteds) { async acceptInvite(invitedBy) {
if (this.chatSocket == undefined) this.sendRequest({
return; type: "accept_invite",
targets: [invitedBy],
});
this.chatSocket.send(JSON.stringify({ }
async receiveAcceptInvite(send) {
let id_game = send["result"];
navigateTo("/game/" + id_game);
}
async refuseInvite(invitedBy) {
this.sendRequest({
type: "refuse_invite",
targets: [invitedBy],
});
}
async sendInvite(id_inviteds) {
this.sendRequest({
type: "invite", type: "invite",
targets: id_inviteds, targets: id_inviteds,
})); time: new Date().getTime(),
});
} }
async receiveInvite(data) { async receiveInvite(send) {
if (data.content === "notice return") { if (this.client.me == undefined)
if (data.status == 200) { return ;
for (let target in data.targets)
this.data["invited"].push(target); let content = send.content;
if (send.author_id == this.client.me.id) {
if (send.status == 200) {
for (let target in send.targets)
return create_popup("Invitation send"); return create_popup("Invitation send");
} }
else if (data.status == 404) else if (send.status == 404)
return create_popup("User not connected"); return create_popup("User not connected");
else if (data.status == 409) else if (send.status == 409)
return create_popup("Already invited"); return create_popup("Already invited");
} }
else { else {
let sender = await this.client.profiles.getProfile(data.author_id);
this.inviter.push(data.author_id); if (!content.includes(send.author_id) ||
this.data["invited"].includes(send.author_id))
return;
this.data["invited"] = content;
let sender = await this.client.profiles.getProfile(send.author_id);
create_popup("Invitation received by " + sender.username); create_popup("Invitation received by " + sender.username);
if (this.rewrite_invite !== undefined)
this.rewrite_invite();
// Géré la reception de l'invitation // Géré la reception de l'invitation
} }
} }
async getOnlineUser() { async getOnlineUser() {
if (this.chatSocket == undefined)
return;
this.online_users = {}; this.online_users = {};
this.chatSocket.send(JSON.stringify({ this.sendRequest({
type: "online_users", type: "online_users",
targets: "all", targets: [],
})); time: new Date().getTime(),
});
} }
async receiveOnlineUser(data) { async receiveOnlineUser(send) {
if (data.content !== undefined) { let content = send.content;
if (content !== undefined) {
if (this.online_users.length > 0) { if (this.data["online"].length > 0) {
// get all disconnect user // get all disconnect user
let disconnects = this.online_users.filter(id => !Object.keys(data.content).includes(id)); let disconnects = this.data["online"].filter(id => !Object.keys(content).includes(id));
// delete invite // delete invite
this.data["invited"] = this.data["invited"].filter(id => !disconnects.includes(id)); this.data["invited"] = this.data["invited"].filter(id => !disconnects.includes(id));
@ -102,12 +139,19 @@ class Notice {
//console.log(this.data["invited"]); //console.log(this.data["invited"]);
} }
this.data["online"] = Object.keys(data.content); this.data["online"] = Object.keys(content);
if (this.rewrite_usernames !== undefined) if (this.rewrite_usernames !== undefined)
this.rewrite_usernames(); this.rewrite_usernames();
} }
} }
async sendRequest(content) {
if (this.chatSocket == undefined)
return;
this.chatSocket.send(JSON.stringify(content));
}
} }
export {Notice} export {Notice}

View File

@ -34,6 +34,7 @@ class Profile
let block_response = await this.client._get("/api/profiles/block"); let block_response = await this.client._get("/api/profiles/block");
if (block_response.status != 200) if (block_response.status != 200)
return return
@ -42,7 +43,7 @@ class Profile
block_list.forEach(block => { block_list.forEach(block => {
let blocker = block.fields.blocker; let blocker = block.fields.blocker;
let blocked = block.fields.blocked; let blocked = block.fields.blocked;
if (blocker == this.client.me.user_id && blocked == user_id) if (blocker == this.client.me.id && blocked == this.id)
return this.isBlocked = true; return this.isBlocked = true;
}); });
} }

View File

@ -37,7 +37,7 @@ class Profiles
// blocker & blocked // blocker & blocked
let response = await this.client._post("/api/profiles/block", { let response = await this.client._post("/api/profiles/block", {
users_id:[this.client.me.user_id, user_id], users_id:[this.client.me.id, user_id],
}); });
let data = await response.json(); let data = await response.json();
@ -49,7 +49,7 @@ class Profiles
// blocker & blocked // blocker & blocked
let response = await this.client._delete("/api/profiles/block", { let response = await this.client._delete("/api/profiles/block", {
users_id:[this.client.me.user_id, user_id], users_id:[this.client.me.id, user_id],
}); });
let data = await response.json(); let data = await response.json();

View File

@ -8,6 +8,7 @@ export default class extends AbstractView {
async getHtml() { async getHtml() {
return ` return `
<h1>404 Bozo</h1> <h1>404 Bozo</h1>
<img src="https://media.giphy.com/media/pm0BKtuBFpdM4/giphy.gif">
<p>Git gud</p> <p>Git gud</p>
`; `;
} }

View File

@ -31,8 +31,10 @@ export default class extends AbstractView {
//await client.notice.getOnlineUser(); //await client.notice.getOnlineUser();
await this.wait_get_online_users(); await this.wait_get_online_users();
client.notice.rewrite_usernames = this.rewrite_usernames; client.notice.rewrite_usernames = this.rewrite_usernames;
client.notice.rewrite_invite = this.display_invite;
let search = document.getElementById("input_user"); let search = document.getElementById("input_user");
if (search != undefined)
search.oninput = () => this.display_users(logged, profiles); search.oninput = () => this.display_users(logged, profiles);
let chat_input = document.getElementById("input_chat"); let chat_input = document.getElementById("input_chat");
@ -175,13 +177,15 @@ export default class extends AbstractView {
chat_input.maxLength=255; chat_input.maxLength=255;
chat.appendChild(chat_input); chat.appendChild(chat_input);
let members_id = client.channels.channel.members_id;
chat_input.onkeydown = async () => { chat_input.onkeydown = async () => {
if (event.keyCode == 13 && client.channels.channel != undefined) { if (event.keyCode == 13 && client.channels.channel != undefined) {
//let chat_input = document.getElementById("input_chat"); //let chat_input = document.getElementById("input_chat");
let chat_text = chat_input.value; let chat_text = chat_input.value;
let receivers_id = []; let receivers_id = [];
client.channels.channel.members_id.forEach((member_id) => { members_id.forEach((member_id) => {
if (member_id != client.me.id) if (member_id != client.me.id)
receivers_id.push(profiles.filter(user => user.id == member_id)[0].id); receivers_id.push(profiles.filter(user => user.id == member_id)[0].id);
}); });
@ -196,7 +200,7 @@ export default class extends AbstractView {
// Scroll to the bottom of messages // Scroll to the bottom of messages
messages.scrollTop = messages.scrollHeight; messages.scrollTop = messages.scrollHeight;
this.display_invite(chat); this.display_invite();
} }
@ -242,10 +246,13 @@ export default class extends AbstractView {
} }
async display_members(chat, profiles) { async display_members(chat, profiles) {
let members_id = client.channels.channel.members_id;
let members = document.createElement("h2"); let members = document.createElement("h2");
members.id = "members"; members.id = "members";
let usernames = ""; let usernames = "";
client.channels.channel.members_id.forEach((member_id) => { members_id.forEach((member_id) => {
if (member_id != client.me.id) { if (member_id != client.me.id) {
if (usernames.length > 0) if (usernames.length > 0)
usernames += ", "; usernames += ", ";
@ -258,17 +265,66 @@ export default class extends AbstractView {
return members return members
} }
async display_invite(chat, profiles) { async display_invite() {
let chat = document.getElementById("chat");
if (chat == undefined)
return ;
let members_id = client.channels.channel.members_id;
let others = members_id.filter(id => id !== client.me.id);
let invite = document.getElementById("invite") || document.createElement("button");
let yes = document.getElementById("yes") || document.createElement("button");
let no = document.getElementById("no") || document.createElement("button");
let invitedBy = undefined;
for (let x in others) {
if (client.notice.data["invited"].includes(others[x])) {
invitedBy = others[x];
}
}
if (invitedBy == undefined) {
if (yes && no) {
yes.remove();
no.remove();
}
// Button to send invite to play // Button to send invite to play
let invite = document.getElementById("invite") || document.createElement("button");
invite.id = "invite"; invite.id = "invite";
invite.style.background = "orange";
invite.innerText = "invite"; invite.innerText = "invite";
invite.title = "Invite to play a game"
invite.onclick = async () => { invite.onclick = async () => {
await client.notice.sendInvite(client.me.id, await client.notice.sendInvite(others);
client.channels.channel.members_id.filter(id => id !== client.me.id));
}; };
chat.appendChild(invite); chat.appendChild(invite);
}
else {
if (invite)
invite.remove()
yes.id = "yes";
yes.style.background = "green";
yes.title = "Accept to play a game"
yes.onclick = async () => {
await client.notice.acceptInvite(invitedBy);
};
no.id = "no";
no.style.background = "red";
no.title = "Refuse to play a game"
no.onclick = async () => {
await client.notice.refuseInvite(invitedBy);
};
chat.appendChild(yes);
chat.appendChild(no);
}
} }

View File

@ -33,7 +33,10 @@ class BlocksView(APIView):
users_id = request.data.get("users_id", None) users_id = request.data.get("users_id", None)
if (users_id == None): if (users_id == None):
return Response({"Error"}, status=status.HTTP_400_BAD_REQUEST) return Response({"Error send None"}, status=status.HTTP_400_BAD_REQUEST)
if (users_id[0] == None or users_id[1] == None):
return Response({"Error send blocker/ed None"}, status=status.HTTP_400_BAD_REQUEST)
if (BlockModel.objects.filter(blocker=users_id[0], blocked=users_id[1])): if (BlockModel.objects.filter(blocker=users_id[0], blocked=users_id[1])):
return Response({"Already Exist"}, status=status.HTTP_409_CONFLICT) return Response({"Already Exist"}, status=status.HTTP_409_CONFLICT)
@ -52,6 +55,9 @@ class BlocksView(APIView):
if (users_id == None): if (users_id == None):
return Response({"Error"}, status=status.HTTP_400_BAD_REQUEST) return Response({"Error"}, status=status.HTTP_400_BAD_REQUEST)
if (users_id[0] == None or users_id[1] == None):
return Response({"Error send blocker/ed None"}, status=status.HTTP_400_BAD_REQUEST)
block = BlockModel.objects.filter(blocker=users_id[0], blocked=users_id[1]) block = BlockModel.objects.filter(blocker=users_id[0], blocked=users_id[1])
print(list(block)) print(list(block))