Chat finish; add invitation; friend; see online users if he is your friend

This commit is contained in:
Xamora 2024-01-24 16:03:50 +01:00
parent fe47a4d633
commit 0f7953b2f3
12 changed files with 532 additions and 79 deletions

View File

@ -2,6 +2,7 @@ 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 from games.models import GameModel
from profiles.models import FriendModel, AskFriendModel
import time import time
import json import json
@ -72,23 +73,17 @@ class ChatNoticeConsumer(WebsocketConsumer):
if (self.channel_layer == None): if (self.channel_layer == None):
return return
message_time: int = int(text_data_json.get('time')) message_time: int = text_data_json.get('time')
print(message_time)
print(time.time())
print(time.time() * 1000 - message_time)
if (message_time == None): if (message_time == None):
message_time: int = int(time.time() * 1000) message_time: int = int(time.time() * 1000)
#print("receive" + str(user.pk))
result = None result = None
try: try:
status, result = getattr(self, "pre_" + type_notice)(user, targets) status, result = getattr(self, "pre_" + type_notice)(user, targets)
except AttributeError: except AttributeError as error:
print(error)
status = 200 status = 200
#print(f"La fonction pre_{type_notice} n'existe pas.")
if (status < 300): if (status < 300):
if targets == "all": if targets == "all":
@ -98,7 +93,7 @@ class ChatNoticeConsumer(WebsocketConsumer):
channel = self.channel_layer.users_channels.get(target) channel = self.channel_layer.users_channels.get(target)
if (channel == None or target == user.pk): if (channel == None or target == user.pk):
if (channel == None): if (channel == None):
status = 404 status = 444 # target not connected
continue continue
async_to_sync(self.channel_layer.send)(channel, { async_to_sync(self.channel_layer.send)(channel, {
'type':type_notice, 'type':type_notice,
@ -159,6 +154,9 @@ class ChatNoticeConsumer(WebsocketConsumer):
def pre_invite(self, user, targets): def pre_invite(self, user, targets):
if (user.is_anonymous or not user.is_authenticated):
return 400, None
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]):
@ -181,6 +179,7 @@ class ChatNoticeConsumer(WebsocketConsumer):
for inviter_id, inviteds_id in self.channel_layer.invite.items(): for inviter_id, inviteds_id in self.channel_layer.invite.items():
if (user.pk in inviteds_id and user.pk != inviter_id): if (user.pk in inviteds_id and user.pk != inviter_id):
invites.append(inviter_id) invites.append(inviter_id)
return invites;
def invite(self, event): def invite(self, event):
@ -201,6 +200,9 @@ class ChatNoticeConsumer(WebsocketConsumer):
def pre_accept_invite(self, user, targets): 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]]): if (user.pk not in self.channel_layer.invite[targets[0]]):
return 400, None return 400, None
@ -224,27 +226,148 @@ class ChatNoticeConsumer(WebsocketConsumer):
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'],
'result': event['result'], 'id_game': event['result'],
'invites': invites, 'invites': invites,
'time': event['time'], 'time': event['time'],
'status':event['status'], 'status':event['status'],
})) }))
def online_users(self, event): def pre_refuse_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])
return 200, None
def refuse_invite(self, event):
user = self.scope["user"] user = self.scope["user"]
#if (user.is_anonymous or not user.is_authenticated): if (user.is_anonymous or not user.is_authenticated):
#return return
#print("online_users" + str(user.pk)) invites = self.get_invites(user)
event['content'] = self.channel_layer.users_channels
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,
'time': event['time'],
'status':event['status'],
}))
def pre_ask_friend(self, user, targets):
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 (FriendModel().isFriend(user.pk, targets[0])):
return 409, None
if (targets[0] != None):
AskFriendModel(asker=user.pk, asked=targets[0]).save()
return 200, None
def send_ask_friend(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
asked = AskFriendModel().getAsked(user.pk)
asker = AskFriendModel().getAsker(user.pk)
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'targets':event['targets'],
'asker': asker,
'asked': asked,
'time': event['time'],
'status':event['status'],
}))
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
asked = user_asked.pk
if (not AskFriendModel.objects.filter(asker=asker, asked=asked)):
return 404, None
if (FriendModel().isFriend(asker, asked)):
return 409, None
if (not AskFriendModel().deleteAsk(asker, asked)):
return 400, 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 accept_friend(self, event):
self.send_ask_friend(event)
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 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 (not FriendModel().deleteFriend(user.pk, targets[0])):
return 400, None
return 200, None
def remove_friend(self, event):
self.send_ask_friend(event)
def online_users(self, event):
user = self.scope["user"]
if (user.is_anonymous or not user.is_authenticated):
return
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"
self.send(text_data=json.dumps({
'type':event['type'],
'author_id':event['author_id'],
'content':online_friends,
'time': event['time'], 'time': event['time'],
'status':event['status'], 'status':event['status'],
})) }))

View File

@ -3,12 +3,20 @@
font-size: 0.8em; font-size: 0.8em;
} }
#app #block { #app #block, #app #friend {
cursor: pointer; cursor: pointer;
font-size: 0.7em; font-size: 0.7em;
text-decoration: underline; text-decoration: underline;
} }
#app { #app {
margin-top: 20px; margin-top: 1em;
background-color: red;
}
#app #yes, #app #no {
display:inline;
cursor: pointer;
font-size: 0.7em;
text-decoration: underline;
} }

View File

@ -6,8 +6,8 @@ class Notice {
this.client = client; this.client = client;
this.data = {}; this.data = {};
// users online, invited by, asked friend by, // users online, invited by ..., asked by ..., asker to ...
let data_variable = ["online", "invited", "asked"]; let data_variable = ["online", "invited", "asked", "asker"];
for (let i in data_variable) for (let i in data_variable)
this.data[data_variable[i]] = []; this.data[data_variable[i]] = [];
@ -21,16 +21,19 @@ class Notice {
this.chatSocket = new WebSocket(url); this.chatSocket = new WebSocket(url);
this.chatSocket.onmessage = (event) =>{ this.chatSocket.onmessage = (event) =>{
let send = JSON.parse(event.data); let send = JSON.parse(event.data);
console.log("notice: ", send); //console.log("notice: ", send);
if (send.type == "invite")
this.receiveInvite(send); try {
else if (send.type == "online_users" || send.type == "disconnect") this["receive_" + send.type](send);
this.receiveOnlineUser(send); }
else if (send.type == "accept_invite") catch (error) {
this.receiveAcceptInvite(send); console.log("receive_" + send.type + ": Function not found");
}
} }
this.chatSocket.onopen = (event) => { this.chatSocket.onopen = (event) => {
this.getOnlineUser(); this.getOnlineUser();
this.ask_friend();
} }
} }
@ -42,7 +45,7 @@ class Notice {
} }
async acceptInvite(invitedBy) { async accept_invite(invitedBy) {
this.sendRequest({ this.sendRequest({
type: "accept_invite", type: "accept_invite",
@ -51,14 +54,15 @@ class Notice {
} }
async receiveAcceptInvite(send) { async receive_accept_invite(send) {
let id_game = send["result"]; this.data["invited"] = send.invites;
let id_game = send["id_game"];
navigateTo("/game/" + id_game); navigateTo("/game/" + id_game);
} }
async refuseInvite(invitedBy) { async refuse_invite(invitedBy) {
this.sendRequest({ this.sendRequest({
type: "refuse_invite", type: "refuse_invite",
@ -67,8 +71,23 @@ class Notice {
} }
async receive_refuse_invite(send) {
async sendInvite(id_inviteds) { this.data["invited"] = send.invites;
if (send.author_id == this.client.me.id) {
if (this.rewrite_invite !== undefined)
this.rewrite_invite();
}
else {
let sender = await this.client.profiles.getProfile(send.author_id);
create_popup(sender.username + " refuse your invitation");
}
}
async send_invite(id_inviteds) {
this.sendRequest({ this.sendRequest({
type: "invite", type: "invite",
@ -78,25 +97,27 @@ class Notice {
} }
async receiveInvite(send) { async receive_invite(send) {
if (this.client.me == undefined) if (this.client.me == undefined)
return ; return ;
let content = send.content; let content = send.invites;
if (send.author_id == this.client.me.id) { if (send.author_id == this.client.me.id) {
if (send.status == 200) { if (send.status == 200) {
for (let target in send.targets) for (let target in send.targets)
return create_popup("Invitation send"); return create_popup("Invitation send");
} }
else if (send.status == 404) else if (send.status == 444)
return create_popup("User not connected"); return create_popup("User not connected");
else if (send.status == 409) else if (send.status == 409)
return create_popup("Already invited"); return create_popup("Already invited");
} }
else { else {
// Regarder qu'il est bien invité par l'auteur
// Et qu'il n'est pas déjà invité
if (!content.includes(send.author_id) || if (!content.includes(send.author_id) ||
this.data["invited"].includes(send.author_id)) this.data["invited"].includes(send.author_id))
return; return;
@ -108,8 +129,6 @@ class Notice {
if (this.rewrite_invite !== undefined) if (this.rewrite_invite !== undefined)
this.rewrite_invite(); this.rewrite_invite();
// Géré la reception de l'invitation
} }
} }
@ -125,13 +144,20 @@ class Notice {
} }
async receiveOnlineUser(send) { async receive_online_users(send) {
let content = send.content; let content = send.content;
if (content !== undefined) { if (content !== undefined) {
if (this.data["online"].length > 0) { if (this.data["online"].length > 0) {
// get all disconnect user // get all disconnect user
let disconnects = this.data["online"].filter(id => !Object.keys(content).includes(id)); //let disconnects = this.data["online"].filter(id => !Object.keys(content).includes(id));
let disconnects = [];
for (const [key, value] of Object.entries(this.data["online"])) {
if (content[key] == "red" && value == "green")
disconnects.push(key);
}
// 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));
@ -139,13 +165,131 @@ class Notice {
//console.log(this.data["invited"]); //console.log(this.data["invited"]);
} }
this.data["online"] = Object.keys(content); this.data["online"] = content;
if (this.rewrite_usernames !== undefined) if (this.rewrite_usernames !== undefined)
this.rewrite_usernames(); this.rewrite_usernames();
} }
} }
async ask_friend(user_id=undefined) {
this.sendRequest({
type: "ask_friend",
targets: [user_id],
time: new Date().getTime(),
});
}
async receive_ask_friend(send) {
let my_id = (this.client.me && this.client.me.id) || send.author_id;
if (send.author_id == my_id) {
if (send.status == 400)
create_popup("Friend ask error");
else if (send.status == 409)
create_popup("Already asked friend or already friend");
}
//if (!send.asked.includes(send.author_id) ||
//this.data["asked"].includes(send.author_id))
//return;
//if (!send.asker.includes(send.author_id) ||
//this.data["asker"].includes(send.author_id))
//return;
this.data["asked"] = send.asked;
this.data["asker"] = send.asker;
if (send.author_id != my_id) {
let sender = await this.client.profiles.getProfile(send.author_id);
if (this.data["asker"].includes(send.author_id))
create_popup(sender.username + " ask you as friend");
if (this.rewrite_profile !== undefined)
await this.rewrite_profile();
}
}
async remove_friend(user_id) {
this.sendRequest({
type: "remove_friend",
targets: [user_id],
time: new Date().getTime(),
});
}
async receive_remove_friend(send) {
this.data["asked"] = send.asked;
this.data["asker"] = send.asker;
if (send.author_id == this.client.me.id) {
if (send.status == 400)
create_popup("Error remove Friend");
else if (send.status == 409)
create_popup("Not friend, wtf");
}
if (this.rewrite_profile !== undefined)
await this.rewrite_profile();
}
async accept_friend(user_id) {
this.sendRequest({
type: "accept_friend",
targets: [user_id],
time: new Date().getTime(),
});
}
async receive_accept_friend(send) {
this.data["asked"] = send.asked;
this.data["asker"] = send.asker;
let sender = await this.client.profiles.getProfile(send.author_id);
if (send.author_id == this.client.me.id) {
if (send.status == 400)
create_popup("Error accept Friend");
else if (send.status == 404)
create_popup("Not found request Friend");
else if (send.status == 409)
create_popup("Already Friend, wtf");
}
else {
create_popup(sender.username + " accept your friend request");
}
if (this.rewrite_profile !== undefined)
await this.rewrite_profile();
}
async refuse_friend(user_id) {
this.sendRequest({
type: "refuse_friend",
targets: [user_id],
time: new Date().getTime(),
});
}
async receive_refuse_friend(send) {
this.data["asked"] = send.asked;
this.data["asker"] = send.asker;
let sender = await this.client.profiles.getProfile(send.author_id);
if (send.author_id == this.client.me.id) {
if (send.status == 400)
create_popup("Error refuse Friend");
else if (send.status == 404)
create_popup("Not found request Friend");
else if (send.status == 409)
create_popup("Already Friend, WTF");
}
if (this.rewrite_profile !== undefined)
await this.rewrite_profile();
}
async sendRequest(content) { async sendRequest(content) {
if (this.chatSocket == undefined) if (this.chatSocket == undefined)
return; return;

View File

@ -79,7 +79,7 @@ class Client
async _patch_json(uri, data) async _patch_json(uri, data)
{ {
let response = await fetch(this._url + uri, { let response = await fetch(this._url + uri, {
method: "PATCH", ethod: "PATCH",
headers: { headers: {
"X-CSRFToken": getCookie("csrftoken"), "X-CSRFToken": getCookie("csrftoken"),
"Content-Type": "application/json", "Content-Type": "application/json",

View File

@ -15,6 +15,7 @@ class Profile
this.username = username; this.username = username;
this.avatar_url = avatar_url; this.avatar_url = avatar_url;
this.isBlocked = false; this.isBlocked = false;
this.isFriend = false;
} }
async init() async init()
@ -29,24 +30,47 @@ class Profile
this.username = response_data.username; this.username = response_data.username;
this.avatar_url = response_data.avatar_url; this.avatar_url = response_data.avatar_url;
if (this.client.me == undefined) await this.getBlock();
return; await this.getFriend();
}
async getBlock() {
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
let block_data = await block_response.json(); let block_data = await block_response.json();
let block_list = JSON.parse(block_data); let block_list = JSON.parse(block_data["blockeds"]);
let client_id = block_data["user_id"];
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.id && blocked == this.id) if (blocker == client_id && blocked == this.id)
return this.isBlocked = true; return this.isBlocked = true;
}); });
} }
async getFriend() {
let friend_response = await this.client._get("/api/profiles/friend");
this.isFriend = false;
if (friend_response.status != 200)
return this.isFriend;
let friend_data = await friend_response.json();
let friends_list = friend_data["friends"];
let client_id = friend_data["user_id"];
friends_list.forEach(friend => {
if (friend == this.id) {
this.isFriend = true;
return this.isFriend;
}
});
return this.isFriend;
}
} }
export {Profile} export {Profile}

View File

@ -58,6 +58,7 @@ async function renderView(view)
let error_code = await view.postInit(); let error_code = await view.postInit();
if (error_code === 404) if (error_code === 404)
renderView(new PageNotFoundView()); renderView(new PageNotFoundView());
else if (error_code === 403) else if (error_code === 403)

View File

@ -4,17 +4,16 @@ import { client } from "../index.js"
export default class extends AbstractView { export default class extends AbstractView {
constructor(params) { constructor(params) {
super(params, "Profile "); super(params, "Profile ");
this.user_id = params.id; this.id = Number(params.id);
} }
async postInit() async postInit()
{ {
let profile = await client.profiles.getProfile(this.user_id); this.profile = await client.profiles.getProfile(this.id);
if (profile === null) if (this.profile === null)
return 404; return 404;
this.profile = await client.profiles.getProfile(this.user_id);
this.info = document.getElementById("info"); this.info = document.getElementById("info");
// Username // Username
@ -32,6 +31,14 @@ export default class extends AbstractView {
this.info.appendChild(avatar); this.info.appendChild(avatar);
await this.blockButton(); await this.blockButton();
await this.friendButton();
client.notice.rewrite_profile = async () => {
let result = await this.profile.getFriend();
await this.profile.getBlock()
await this.friendButton();
}
} }
async blockButton() { async blockButton() {
@ -39,23 +46,81 @@ export default class extends AbstractView {
if (await client.isAuthentificate() === false) if (await client.isAuthentificate() === false)
return; return;
if (client.me.id != this.user_id) { if (client.me.id != this.id) {
let block = document.getElementById("block") || document.createElement("a"); let block = document.getElementById("block");
if (block == undefined) {
block = document.createElement("p");
this.info.appendChild(block);
}
block.id = "block"; block.id = "block";
block.innerText = "";
block.onclick = async () => { block.onclick = async () => {
if (!this.profile.isBlocked) if (this.profile.isBlocked)
await client.profiles.block(this.user_id); await client.profiles.deblock(this.id);
else else
await client.profiles.deblock(this.user_id); await client.profiles.block(this.id);
this.profile = await client.profiles.getProfile(this.user_id); this.profile = await client.profiles.getProfile(this.id);
this.blockButton(); this.blockButton();
}; };
if (this.profile.isBlocked) if (this.profile.isBlocked)
block.appendChild(document.createTextNode("Deblock")); block.textContent = "Deblock";
else else
block.appendChild(document.createTextNode("Block")); block.textContent = "Block";
this.info.appendChild(block); }
}
async friendButton() {
if (await client.isAuthentificate() === false)
return;
if (client.me.id != this.id) {
let yes = document.getElementById("yes") || document.createElement("p");
let no = document.getElementById("no") || document.createElement("p");
let friend = document.getElementById("friend") || document.createElement("p");
if (client.notice.data["asker"].includes(this.id)) {
if (friend)
friend.remove();
yes.id = "yes";
yes.textContent = "Accept Friend";
yes.onclick = async () => {
client.notice.accept_friend(this.id);
}
no.id = "no";
no.textContent = "Refuse Friend";
no.onclick = async () => {
client.notice.refuse_friend(this.id);
}
this.info.appendChild(yes);
this.info.appendChild(document.createTextNode(" "));
this.info.appendChild(no);
}
else {
if (yes && no)
yes.remove(); no.remove();
friend.id = "friend"
friend.onclick = async () => {
if (this.profile.isFriend)
await client.notice.remove_friend(this.id);
else
await client.notice.ask_friend(this.id);
this.profile = await client.profiles.getProfile(this.id);
this.friendButton();
};
if (this.profile.isFriend)
friend.textContent = "Remove Friend";
else {
friend.textContent = "Ask Friend";
}
this.info.appendChild(friend);
}
} }
} }

View File

@ -10,12 +10,12 @@ export default class extends AbstractView {
async wait_get_online_users() { async wait_get_online_users() {
return new Promise((resolve) => { return new Promise((resolve) => {
const checkInterval = setInterval(() => { const checkInterval = setInterval(() => {
//console.log(client.notice.data["online"].length); console.log(client.notice.data["online"]);
if (client.notice.data["online"].length > 0) { if (Object.keys(client.notice.data["online"]).length > 0) {
clearInterval(checkInterval); clearInterval(checkInterval);
resolve(); resolve();
} }
}, 100); }, 1);
}); });
} }
@ -29,7 +29,7 @@ export default class extends AbstractView {
return console.log("Error"); return console.log("Error");
//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; client.notice.rewrite_invite = this.display_invite;
@ -68,7 +68,14 @@ export default class extends AbstractView {
username.setAttribute('data-link', ''); username.setAttribute('data-link', '');
username.id = `username${user.id}` username.id = `username${user.id}`
username.href = `/profiles/${user.id}`; username.href = `/profiles/${user.id}`;
username.style.color = client.notice.data["online"].includes(user.id.toString()) ? "green" : "red";
if (user.id == client.me.id)
username.style.color = "green";
else {
let online = client.notice.data["online"][user.id];
username.style.color = online !== undefined ? online : "gray";
}
username.appendChild(document.createTextNode(user.username)); username.appendChild(document.createTextNode(user.username));
new_user.appendChild(username); new_user.appendChild(username);
@ -137,8 +144,14 @@ export default class extends AbstractView {
profiles.filter(user => user.username.toLowerCase().startsWith(search) == true).forEach((user) => { profiles.filter(user => user.username.toLowerCase().startsWith(search) == true).forEach((user) => {
let username = document.getElementById(`username${user.id}`); let username = document.getElementById(`username${user.id}`);
if (username !== null) if (username !== null) {
username.style.color = client.notice.data["online"].includes(user.id.toString()) ? "green" : "red"; if (user.id == client.me.id)
username.style.color = "green";
else {
let online = client.notice.data["online"][user.id];
username.style.color = online !== undefined ? online : "gray";
}
}
}); });
} }
@ -259,9 +272,10 @@ export default class extends AbstractView {
usernames += (profiles.filter(user => user.id == member_id)[0].username); usernames += (profiles.filter(user => user.id == member_id)[0].username);
} }
}); });
members.appendChild(document.createTextNode(usernames)); members.textContent = usernames;
chat.appendChild(members); chat.appendChild(members);
return members return members
} }
@ -299,7 +313,7 @@ export default class extends AbstractView {
invite.innerText = "invite"; invite.innerText = "invite";
invite.title = "Invite to play a game" invite.title = "Invite to play a game"
invite.onclick = async () => { invite.onclick = async () => {
await client.notice.sendInvite(others); await client.notice.send_invite(others);
}; };
chat.appendChild(invite); chat.appendChild(invite);
} }
@ -312,14 +326,14 @@ export default class extends AbstractView {
yes.style.background = "green"; yes.style.background = "green";
yes.title = "Accept to play a game" yes.title = "Accept to play a game"
yes.onclick = async () => { yes.onclick = async () => {
await client.notice.acceptInvite(invitedBy); await client.notice.accept_invite(invitedBy);
}; };
no.id = "no"; no.id = "no";
no.style.background = "red"; no.style.background = "red";
no.title = "Refuse to play a game" no.title = "Refuse to play a game"
no.onclick = async () => { no.onclick = async () => {
await client.notice.refuseInvite(invitedBy); await client.notice.refuse_invite(invitedBy);
}; };
chat.appendChild(yes); chat.appendChild(yes);

View File

@ -1,7 +1,9 @@
from django.contrib import admin from django.contrib import admin
from .models import ProfileModel, BlockModel from .models import ProfileModel, BlockModel, FriendModel, AskFriendModel
# Register your models here. # Register your models here.
admin.site.register(ProfileModel) admin.site.register(ProfileModel)
admin.site.register(BlockModel) admin.site.register(BlockModel)
admin.site.register(FriendModel)
admin.site.register(AskFriendModel)

View File

@ -26,3 +26,67 @@ class BlockModel(models.Model):
def __str__(self): def __str__(self):
return "blocker_id: " + str(self.blocker) + ", blocked_id: " + str(self.blocked) return "blocker_id: " + str(self.blocker) + ", blocked_id: " + str(self.blocked)
class AskFriendModel(models.Model):
asker = IntegerField(primary_key=False)
asked = IntegerField(primary_key=False)
def getAsked(self, asker):
askeds = []
for ask in AskFriendModel.objects.filter(asker=asker):
askeds.append(ask.asked)
return askeds
def getAsker(self, asked):
askers = []
for ask in AskFriendModel.objects.filter(asked=asked):
askers.append(ask.asker)
return askers
def deleteAsk(self, asker, asked):
deleted = AskFriendModel.objects.filter(asker=asker, asked=asked)
if (deleted.count() == 0 or not deleted):
return False
deleted.delete()
return True
class FriendModel(models.Model):
user_id1 = IntegerField(primary_key=False)
user_id2 = IntegerField(primary_key=False)
def getFriends(self, user_id):
friends = []
for friend in FriendModel.objects.filter(user_id1=user_id):
friends.append(friend.user_id2)
for friend in FriendModel.objects.filter(user_id2=user_id):
friends.append(friend.user_id1)
return friends
def isFriend(self, user_id1, user_id2):
return user_id2 in self.getFriends(user_id1)
def deleteFriend(self, user_id1, user_id2):
first = FriendModel.objects.filter(user_id1=user_id1, user_id2=user_id2)
if (first.count() == 1):
first.delete()
return True
second = FriendModel.objects.filter(user_id1=user_id2, user_id2=user_id1)
if (second.count() == 1):
second.delete()
return True
return False

View File

@ -11,5 +11,6 @@ urlpatterns = [
path("", viewsets.ProfileViewSet.as_view({'get': 'list'}), name="profiles_list"), path("", viewsets.ProfileViewSet.as_view({'get': 'list'}), name="profiles_list"),
path("block", views.BlocksView.as_view(), name="block_page"), path("block", views.BlocksView.as_view(), name="block_page"),
path("block/<int:pk>", views.BlockView.as_view(), name="block_page"), path("block/<int:pk>", views.BlockView.as_view(), name="block_page"),
path("friend", views.FriendsView.as_view(), name="friend_page"),
] + static("/static/avatars/", document_root="./avatars") ] + static("/static/avatars/", document_root="./avatars")

View File

@ -4,7 +4,7 @@ from rest_framework import authentication, permissions, status
from rest_framework.authentication import SessionAuthentication from rest_framework.authentication import SessionAuthentication
from rest_framework.renderers import JSONRenderer from rest_framework.renderers import JSONRenderer
from django.core import serializers from django.core import serializers
from .models import BlockModel from .models import BlockModel, FriendModel
class BlockView(APIView): class BlockView(APIView):
permission_classes = (permissions.IsAuthenticated,) permission_classes = (permissions.IsAuthenticated,)
@ -25,7 +25,7 @@ class BlocksView(APIView):
def get(self, request): def get(self, request):
blocks = BlockModel.objects.filter(blocker=request.user.pk) blocks = BlockModel.objects.filter(blocker=request.user.pk)
if (blocks): if (blocks):
return Response(serializers.serialize("json", BlockModel.objects.filter(blocker=request.user.pk)), status=status.HTTP_200_OK) return Response({"blockeds": serializers.serialize("json", BlockModel.objects.filter(blocker=request.user.pk)), "user_id": request.user.pk}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_204_NO_CONTENT) return Response({}, status=status.HTTP_204_NO_CONTENT)
def post(self, request): def post(self, request):
@ -60,7 +60,6 @@ class BlocksView(APIView):
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))
if (block.count() > 1): if (block.count() > 1):
return Response("Not normal >:[", status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response("Not normal >:[", status=status.HTTP_500_INTERNAL_SERVER_ERROR)
@ -69,3 +68,11 @@ class BlocksView(APIView):
block.delete() block.delete()
return Response("Deleted", status=status.HTTP_200_OK) return Response("Deleted", status=status.HTTP_200_OK)
class FriendsView(APIView):
def get(self, request):
friends = FriendModel().getFriends(request.user.pk)
if (friends):
return Response({"friends": friends, "user_id": request.user.pk}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_204_NO_CONTENT)