From 9569071a2a016da1c4ef313d3bde1c1fdefa5517 Mon Sep 17 00:00:00 2001
From: uniknow <000-drakon@mail.ru>
Date: Tue, 27 Aug 2024 22:29:04 +0400
Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D1=80=D0=B0=D0=B1?=
=?UTF-8?q?=D0=BE=D1=82=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D0=BD=D0=BE?=
=?UTF-8?q?=D0=B2=D0=BE=D0=B9=20=D0=B1=D0=B4?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
docker/lib/chat.js | 232 +++++
docker/lib/login.js | 35 +
docker/lib/register.js | 94 +++
docker/lib/settings.js | 59 ++
docker/lib/userFunction.js | 30 +
docker/lib/websocket.js | 40 +
src/lib/chat.js | 15 +-
src/lib/login.js | 2 +-
src/lib/register.js | 4 +-
src/routes/+page.svelte | 1356 +++++++++++++++++++++++++++++-
src/routes/Header.svelte | 2 +-
src/routes/chat/+page.svelte | 27 +-
src/routes/register/+page.svelte | 4 +-
13 files changed, 1868 insertions(+), 32 deletions(-)
create mode 100644 docker/lib/chat.js
create mode 100644 docker/lib/login.js
create mode 100644 docker/lib/register.js
create mode 100644 docker/lib/settings.js
create mode 100644 docker/lib/userFunction.js
create mode 100644 docker/lib/websocket.js
diff --git a/docker/lib/chat.js b/docker/lib/chat.js
new file mode 100644
index 0000000..b7d643c
--- /dev/null
+++ b/docker/lib/chat.js
@@ -0,0 +1,232 @@
+import { PUBLIC_URL } from '$env/static/public';
+
+export async function getLastMessages(chatId,msgLoaded){
+
+ let token = localStorage.getItem('BPChat')
+ const response = await fetch(`${PUBLIC_URL}/api/chat/get_some_messages/${chatId}?messages_loaded=${msgLoaded}&messages_to_get=15`,
+ {
+ method:'GET',
+ credentials:'include',
+ headers: {'accept': 'application/json',
+ 'Authorization': token,
+ },
+ })
+
+ if(response.ok){
+ let data = await response.json()
+ let msgMassive = data.messages
+ console.log(msgMassive, " аа сообщения", chatId, " - айди")
+
+ if(msgMassive === null){
+ return []
+ } else {
+ return msgMassive
+ }
+ }
+
+ else if(response.status === 404){
+ console.log(response)
+ }
+
+ else if(!response.ok)
+ console.log(response.status)
+
+ }
+
+ export async function getMessageById(chatId,msgId){
+
+ let token = localStorage.getItem('BPChat')
+ const response = await fetch(`${PUBLIC_URL}/chat/message/${chatId}?message_id=${msgId}`,{
+ method:"GET",
+ credentials:'include',
+ headers: {'Authorization': token },
+
+ })
+
+ if(response.ok){
+ let data = await response.json();
+ return data;
+ }
+ else{
+ return { message: "Сообщение не найдено" };
+ }
+
+ }
+
+ export async function MessagePicToUrl(messagePic){
+
+ let token = localStorage.getItem('BPChat')
+
+ const DataForm = new FormData();
+ DataForm.append('file', messagePic)
+
+ const response = await fetch('${PUBLIC_URL}/api/images/upload_image',
+ {
+ method:"POST",
+ body:DataForm,
+ headers: {'Authorization': token },
+ })
+
+ if(!response.ok)
+ console.log("ошибка", response.status)
+
+
+ if(response.ok){
+ const data = await response.json();
+ console.log("картинка принята")
+ return data.image_url;
+
+ }
+ }
+
+ export async function getAllChats(){
+
+ let token = localStorage.getItem('BPChat')
+ const response = await fetch(`${PUBLIC_URL}/api/chat`,
+ {
+ method:"GET",
+ credentials:'include',
+ headers: {'Authorization': token },
+
+ })
+ if(response.ok){
+ let data = await response.json();
+ data = data.allowed_chats
+ console.log(data)
+
+ if(data == null)
+ return []
+ else
+ return data
+
+ } else if(response.status == 409){
+ return false //если пользователь не подтвердил почту
+ } else {
+ console.log(response)
+ }
+ }
+
+ export async function getPinnedMsg(ID){
+
+ let token = localStorage.getItem('BPChat')
+ const response = await fetch(`${PUBLIC_URL}/api/chat/pinned_messages/${ID}`,{
+ method:"GET",
+ credentials:'include',
+ headers: {'Authorization': token },
+ })
+
+ if(response.ok){
+ const data = await response.json()
+ return data.pinned_messages
+ } else {
+ console.log(response.status)
+ }
+ }
+
+ export async function pinMessage(chatId,messageId){
+
+ let token = localStorage.getItem('BPChat')
+ const response = await fetch(`${PUBLIC_URL}/api/chat/pinn_message?chat_id=${chatId}&message_id=${messageId}`,{
+ method:"POST",
+ credentials:'include',
+ headers: {'Authorization': token },
+ })
+ if(response.ok){
+ const data = await response.json()
+ return data.pinned_message
+ } else
+ console.log(response.status)
+
+ }
+
+ export async function unpinMessage(chatId, messageId){
+
+ let token = localStorage.getItem('BPChat')
+ const response = await fetch(`${PUBLIC_URL}/api/chat/unpinn_message?chat_id=${chatId}&message_id=${messageId}`,{
+ method:"DELETE",
+ credentials:'include',
+ headers: {'Authorization': token },
+ })
+ if(response.ok){
+ return await response.json();
+ }
+ else
+ console.log(response.status)
+
+ }
+
+ export async function uploadImages(image) {
+
+ let token = localStorage.getItem('BPChat')
+ const formData = new FormData();
+ formData.append('file', image);
+
+ const response = await fetch(`${PUBLIC_URL}/api/images/upload_image`, {
+ method: 'POST',
+ credentials: 'include',
+ body: formData,
+ headers: {'Authorization': token },
+ });
+
+ if (response.ok) {
+ let data = await response.json();
+ return data.image_url
+ } else {
+ console.log(response);
+ }
+ }
+
+ export async function getAllUsers(nameToFind){
+
+ const response = await fetch(`${PUBLIC_URL}/api/users?username=${nameToFind}`,{
+ method:"GET",
+ credentials:'include'
+ })
+
+ if(response.ok){
+ let data = await response.json()
+ let anotherData = data.users
+
+ if(anotherData == null){
+ return []
+ }
+ return data.users
+ }
+
+ }
+
+ export async function createNewChat(chatName, excludeUser, token){
+ console.log(token, "token")
+ const response = await fetch(`${PUBLIC_URL}/api/chat/create_chat?user_to_exclude=${excludeUser}&chat_name=${chatName}`,{
+ method: 'POST',
+ credentials: 'include',
+ headers: {'Authorization': token },
+ })
+
+ if(response.ok){
+ let data = await response.json()
+ let id = data.chat_id
+ return id
+ }
+ else{
+ console.log(response)
+ }
+
+ }
+
+ export async function deleteChat(chatId, token){
+
+ const response = await fetch(`${PUBLIC_URL}/api/chat/delete_chat/${chatId}`,{
+ method: 'DELETE',
+ credentials: 'include',
+ headers: {'Authorization': token },
+ })
+
+ if(response.ok){
+ return "Чат удален"
+ }
+
+ else{
+ console.log(response)
+ }
+ }
\ No newline at end of file
diff --git a/docker/lib/login.js b/docker/lib/login.js
new file mode 100644
index 0000000..614268c
--- /dev/null
+++ b/docker/lib/login.js
@@ -0,0 +1,35 @@
+import { PUBLIC_URL } from '$env/static/public';
+
+export async function handleLogin(username, password) {
+
+ const response = await fetch(`${PUBLIC_URL}/api/users/login`, {
+ method: 'POST',
+ credentials:'include',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify
+ ({
+ email_or_username: username,
+ password: password
+ })
+
+ })
+
+ if(response.status === 200)
+ {
+ console.log("залогинен")
+
+ const data = await response.json()
+ const token = data.authorization
+ localStorage.setItem('BPChat', token)
+ window.location.href = '/chat'
+ return "" // чтобы ничего не выводилось в качестве ошибки
+ }
+ else if(response.status === 401)
+ {
+ return "Неправильный логин или пароль"
+ } else {
+ console.log(response)
+ }
+ }
\ No newline at end of file
diff --git a/docker/lib/register.js b/docker/lib/register.js
new file mode 100644
index 0000000..d1ca8ab
--- /dev/null
+++ b/docker/lib/register.js
@@ -0,0 +1,94 @@
+import { PUBLIC_URL } from '$env/static/public';
+
+export async function checkExsistingUser(username, email) {
+ const response = await fetch(`${PUBLIC_URL}/api/users/check_existing_user`, {
+ method:'POST',
+ credentials:"include",
+ headers:{
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ "username": username,
+ "email": email
+ })
+ })
+ if(response.status === 200){
+ return ""
+ }
+ else if(response.status === 409){
+ let data = "ЗАНЯТО НАХУЙ"
+ return data
+ }
+ else if(response.status === 422){
+ let data = await response.json();
+ return data
+ }
+ else{
+ console.log(response.status)
+ }
+}
+
+export async function VerificationEmail(token, Code){
+ const response = await fetch(`${PUBLIC_URL}/api/users/email_verification`,{
+ method:'POST',
+ credentials:'include',
+ headers:{
+ 'Content-Type' : 'application/json',
+ 'Authorization': token
+ },
+ body: JSON.stringify({
+ "user_code": Code
+ })
+ })
+
+ if(response.status === 200){
+ window.location.href = '/chat'
+ return true
+ }
+ else{
+ return false
+ }
+}
+
+export async function resendVerification(token){
+ const response = await fetch(`${PUBLIC_URL}/api/users/resend_email_verification`,{
+ method:'POST',
+ credentials:'include',
+ headers: {'Authorization': token }
+ })
+
+ if(response.ok){
+ return "Отправлено"
+ } else {
+ console.log(response)
+ return "Произошла ошибка"
+ }
+}
+
+ export async function handleRegister(username,password,password2,email,date_of_birth){
+ const response = await fetch(`${PUBLIC_URL}/api/users/register`,{
+ method:'POST',
+ credentials:"include",
+ headers:{ 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ "email": email,
+ "username": username,
+ "password": password,
+ "password2": password2,
+ "date_of_birth": date_of_birth
+ })
+ })
+
+ if(response.status === 201){
+ const data = await response.json();
+ const token = data.authorization
+ localStorage.setItem('BPChat', token)
+ return ""
+ }
+ else if(response.status === 422){
+ console.log(response.status)
+ let data = "Validation Error"
+ return data
+ }
+
+ }
\ No newline at end of file
diff --git a/docker/lib/settings.js b/docker/lib/settings.js
new file mode 100644
index 0000000..e2fcf9e
--- /dev/null
+++ b/docker/lib/settings.js
@@ -0,0 +1,59 @@
+import { PUBLIC_URL } from '$env/static/public';
+
+export async function getAvatarHistory(token){
+
+ let response = await fetch(`${PUBLIC_URL}/api/users/avatars`,{
+ method: 'GET',
+ credentials:'include',
+ headers: {'Authorization': token },
+ })
+
+ if(response.ok){
+ let data = await response.json();
+ data = data.user_avatars
+ data.reverse();
+ return data;
+ } else {
+ console.log(response)
+ }
+}
+
+export async function getConfirmationCode(token, email){
+ console.log(token, email, "<-- лох")
+ const response = await fetch(`${PUBLIC_URL}/api/users/send_confirmation_code`,{
+ method: 'POST',
+ credentials:'include',
+ headers: { 'Content-Type': 'application/json',
+ 'Authorization': token },
+ body: JSON.stringify({'email': email})
+ })
+
+ if(response.ok){
+ return true
+ } else {
+ console.log(response)
+ }
+}
+
+export async function changeUserData(token, username, email, password, avatar, code){
+ let response = await fetch(`${PUBLIC_URL}/api/users/change_data`,{
+
+ method: 'POST',
+ credentials:'include',
+ headers: {'Content-Type': 'application/json',
+ 'Authorization': token },
+ body: JSON.stringify({"verification_code": code,
+ "email": email,
+ "username": username,
+ "new_password": password,
+ "avatar_url": avatar})
+ })
+
+ if(response.ok){
+ return true
+ } else if (response.status == 409){
+
+ } else {
+ console.log(response)
+ }
+}
\ No newline at end of file
diff --git a/docker/lib/userFunction.js b/docker/lib/userFunction.js
new file mode 100644
index 0000000..b03b5e9
--- /dev/null
+++ b/docker/lib/userFunction.js
@@ -0,0 +1,30 @@
+import { PUBLIC_URL } from '$env/static/public';
+
+export async function UserCheck(){
+
+ let token = localStorage.getItem('BPChat')
+ const response = await fetch(`${PUBLIC_URL}/api/users/me`, {
+ method: 'GET',
+ credentials:'include',
+ headers: {'Authorization': token },
+ })
+
+ if(response.ok){
+ const data = await response.json();
+ return data
+ }
+
+ else{
+ console.log(response)
+ location.assign('/login')
+ }
+ }
+
+export async function handleLogout() {
+
+ localStorage.removeItem('BPChat')
+ location.assign('/login')
+
+}
+
+
\ No newline at end of file
diff --git a/docker/lib/websocket.js b/docker/lib/websocket.js
new file mode 100644
index 0000000..41d2a05
--- /dev/null
+++ b/docker/lib/websocket.js
@@ -0,0 +1,40 @@
+export default function createWebSocket(url, token, onMessageCallback) {
+ let socket;
+ let retries = 0;
+ const maxRetries = 5
+ let messageQueue = [];
+
+ function connect() {
+
+ socket = new WebSocket(url, [token]);
+
+ socket.addEventListener('message', (event) => {
+ const jsonData = JSON.parse(event.data)
+ onMessageCallback(jsonData)
+ });
+
+ socket.onopen = () => {
+ console.log('WebSocket is open now.')
+ console.log(socket)
+ retries = 0 //сброс попыток
+
+ while (messageQueue.length > 0) {
+ socket.send(messageQueue.shift());
+ }
+ };
+
+ socket.onclose = (event) => {
+ console.log('WebSocket is closed now.', event)
+ };
+
+ socket.onerror = (error) => {
+ console.error('WebSocket error observed:', error)
+ };
+
+
+ }
+
+ connect()
+
+ return socket
+}
diff --git a/src/lib/chat.js b/src/lib/chat.js
index b7d643c..8f4f4ed 100644
--- a/src/lib/chat.js
+++ b/src/lib/chat.js
@@ -79,9 +79,8 @@ export async function getLastMessages(chatId,msgLoaded){
}
}
- export async function getAllChats(){
-
- let token = localStorage.getItem('BPChat')
+ export async function getAllChats(token){
+
const response = await fetch(`${PUBLIC_URL}/api/chat`,
{
method:"GET",
@@ -116,8 +115,13 @@ export async function getLastMessages(chatId,msgLoaded){
})
if(response.ok){
- const data = await response.json()
- return data.pinned_messages
+ let data = await response.json()
+ data = data.pinned_messages
+ if(data === null){
+ return []
+ } else {
+ return data
+ }
} else {
console.log(response.status)
}
@@ -196,7 +200,6 @@ export async function getLastMessages(chatId,msgLoaded){
}
export async function createNewChat(chatName, excludeUser, token){
- console.log(token, "token")
const response = await fetch(`${PUBLIC_URL}/api/chat/create_chat?user_to_exclude=${excludeUser}&chat_name=${chatName}`,{
method: 'POST',
credentials: 'include',
diff --git a/src/lib/login.js b/src/lib/login.js
index 614268c..e522a0f 100644
--- a/src/lib/login.js
+++ b/src/lib/login.js
@@ -23,7 +23,7 @@ export async function handleLogin(username, password) {
const data = await response.json()
const token = data.authorization
localStorage.setItem('BPChat', token)
- window.location.href = '/chat'
+ window.location.href = '/'
return "" // чтобы ничего не выводилось в качестве ошибки
}
else if(response.status === 401)
diff --git a/src/lib/register.js b/src/lib/register.js
index d1ca8ab..d86da20 100644
--- a/src/lib/register.js
+++ b/src/lib/register.js
@@ -28,7 +28,7 @@ export async function checkExsistingUser(username, email) {
}
}
-export async function VerificationEmail(token, Code){
+export async function VerificationEmail(Code,token){
const response = await fetch(`${PUBLIC_URL}/api/users/email_verification`,{
method:'POST',
credentials:'include',
@@ -42,7 +42,7 @@ export async function VerificationEmail(token, Code){
})
if(response.status === 200){
- window.location.href = '/chat'
+ window.location.href = '/'
return true
}
else{
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index a772757..5bac317 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -1,15 +1,1351 @@
-
+