api update

This commit is contained in:
vladimir 2024-08-11 15:17:53 +03:00
parent 6b0770844c
commit 9dfe013cc6
5 changed files with 319 additions and 155 deletions

View File

@ -186,6 +186,13 @@ h1 {
position: fixed;
}
#error {
color: red;
font-size: 15px;
margin-top: 10px;
text-align: center;
display: none;
}
.close {
color: #aaa;
float: right;

View File

@ -1,52 +1,37 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Список Чат-Комнат</title>
<link rel="stylesheet" href="/assets/css/list-rooms.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Список Чат-Комнат</title>
<link rel="stylesheet" href="/assets/css/list-rooms.css">
</head>
<body>
<div class="container">
<h1 style="color: white;">Выберите Чат-Комнату</h1>
<ul class="room-list">
<!-- Здесь будет список комнат -->
</ul>
<button class="create-room-button" onclick="openCreateRoomModal()">Создать Комнату</button>
<h1 style="color: white;">Выберите Чат-Комнату</h1>
<ul class="room-list">
<!-- Здесь будет список комнат -->
</ul>
<button class="create-room-button" onclick="openCreateRoomModal()">Создать Комнату</button>
</div>
<!-- Модальное окно для создания комнаты -->
<div id="createRoomModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close" onclick="closeCreateRoomModal()">&times;</span>
<h2>Создать Комнату</h2>
</div>
<div class="modal-body">
<input type="text" id="newRoomName" placeholder="Название комнаты">
</div>
<div class="modal-footer">
<button class="join-button" onclick="createRoom()">Создать</button>
</div>
</div>
<div class="modal-content">
<div class="modal-header">
<span class="close" onclick="closeCreateRoomModal()">&times;</span>
<h2>Создать Комнату</h2>
</div>
<div class="modal-body">
<input type="text" id="newRoomName" placeholder="Название комнаты">
<input type="password" id="newRoomNickname" placeholder="Никнейм комнаты">
</div>
<div id="error"></div>
<div class="modal-footer">
<button class="join-button" onclick="createRoom()">Создать</button>
</div>
</div>
</div>
<!-- Модальное окно для добавления участников -->
<div class="overlay" id="add_members">
<div class="add-members">
<div class="add-members-header">
<span class="close" onclick="closeAdd()">&times;</span>
<h2>Добавить участников</h2>
</div>
<div class="add-members-body">
<input type="text" id="newMemberLogin" placeholder="Логин пользователя">
</div>
<div class="add-members-footer">
<button class="add-member-button" onclick="addMember()">Добавить</button>
</div>
</div>
</div>
<script src="/assets/js/list-rooms.js"></script>
</body>
</html>

View File

@ -1,41 +1,152 @@
function sendMessage() {
const chatMessages = document.getElementById('chat-messages');
const chatInput = document.getElementById('chat-input');
const message = chatInput.value;
if (message.trim() !== '') {
const messageElement = document.createElement('div');
messageElement.classList.add('chat-message');
let currentHistoryId = 0;
let currentChatID = null;
const avatarElement = document.createElement('div');
avatarElement.classList.add('avatar');
document.addEventListener("DOMContentLoaded", async function() {
currentChatID = await getChatID();
});
const avatarImage = document.createElement('img');
avatarImage.src = 'https://sun9-59.userapi.com/impg/t8GhZ7FkynVifY1FQCnaf31tGprbV_rfauZzgg/fSq4lyc6V0U.jpg?size=1280x1280&quality=96&sign=e3c309a125cb570d2e18465eba65f940&type=album';
avatarElement.appendChild(avatarImage);
async function sendMessage() {
const chatMessages = document.getElementById('chat-messages');
const chatInput = document.getElementById('chat-input');
const message = chatInput.value;
const messageContentElement = document.createElement('div');
messageContentElement.classList.add('message-content');
if (message.trim() !== '') {
const request = {
'chatId': currentChatID,
'LocalHistoryId': currentHistoryId,
'content': {
'text': message
}
};
const usernameElement = document.createElement('div');
usernameElement.classList.add('username');
usernameElement.textContent = 'Адель';
const response = await fetch("/internalapi/sendMessage", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
});
const textElement = document.createElement('div');
textElement.classList.add('text');
textElement.textContent = message;
const res = await response.json();
messageContentElement.appendChild(usernameElement);
messageContentElement.appendChild(textElement);
if (res.update) {
const update = res.update[0];
currentHistoryId = update.HistoryId;
messageElement.appendChild(avatarElement);
messageElement.appendChild(messageContentElement);
const messageElement = document.createElement('div');
messageElement.classList.add('chat-message');
chatMessages.appendChild(messageElement);
const avatarElement = document.createElement('div');
avatarElement.classList.add('avatar');
chatInput.value = '';
chatMessages.scrollTop = chatMessages.scrollHeight;
const avatarImage = document.createElement('img');
avatarImage.src = 'https://sun9-59.userapi.com/impg/t8GhZ7FkynVifY1FQCnaf31tGprbV_rfauZzgg/fSq4lyc6V0U.jpg?size=1280x1280&quality=96&sign=e3c309a125cb570d2e18465eba65f940&type=album';
avatarElement.appendChild(avatarImage);
const messageContentElement = document.createElement('div');
messageContentElement.classList.add('message-content');
const usernameElement = document.createElement('div');
usernameElement.classList.add('username');
usernameElement.textContent = await getUserName();
const textElement = document.createElement('div');
textElement.classList.add('text');
textElement.textContent = message;
messageContentElement.appendChild(usernameElement);
messageContentElement.appendChild(textElement);
messageElement.appendChild(avatarElement);
messageElement.appendChild(messageContentElement);
chatMessages.appendChild(messageElement);
chatInput.value = '';
chatMessages.scrollTop = chatMessages.scrollHeight;
}
}
}
}
document.getElementById('chat-input').addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
sendMessage();
}
});
async function getUserName() {
const userID = await getUserID();
const request = {
"id": userID
};
const response = await fetch('/internalapi/getUserInfo', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
});
const res = await response.json();
return res.content.name;
}
async function getUserID() {
const response = await fetch('/internalapi/mirror', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({})
});
const res = await response.json();
return res.id;
}
async function getChatID() {
const chatNickname = window.location.pathname.split('/').pop();
const response = await fetch('/internalapi/getChatList', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({})
});
const res = await response.json();
for (const chat of res.chats) {
if (chat.content.nickname === chatNickname) {
return chat.id;
}
}
return -1;
}
async function editMessage(new_message) {
const req = {
'chatId': currentChatID,
'LocalHistoryId': currentHistoryId,
'id': getUserID(),
'content': {
'text': new_message
}
};
const res = await fetch('/internalapi/editMessage', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(req)
});
const response = await res.json();
if (response.update) {
currentHistoryId = response.update[0].HistoryId;
}
}
function openMembersList() {
document.getElementById("members-list").style.display = "block";
document.getElementById("overlay").style.display = "flex";
@ -49,4 +160,4 @@ document.getElementById('chat-input').addEventListener('keydown', function (even
if (event.key === 'Enter') {
sendMessage();
}
});
});

View File

@ -1,85 +1,128 @@
let rooms = {};
let currentRoom = null;
let currentHistoryId = 0;
function openRoom(currentRoom) {
alert('Вы вошли в комнату: ' + currentRoom);
}
function closeAdd() {
document.getElementById('add_members').style.display = 'none';
}
function openAdd() {
document.getElementById('add_members').style.display = 'flex';
}
function addMember() {
const login = document.getElementById('newMemberLogin').value;
if (login) {
alert(`Участник с никнеймом '${login}' добавлен`);
closeAdd();
} else {
alert('Пожалуйста, введите логин участника');
}
}
function openCreateRoomModal() {
document.getElementById('createRoomModal').style.display = 'block';
}
function closeCreateRoomModal() {
document.getElementById('createRoomModal').style.display = 'none';
}
function createRoom() {
const roomName = document.getElementById('newRoomName').value.trim();
if (roomName === '') {
alert('Пожалуйста, заполните все поля.');
return;
}
if (rooms[roomName]) {
alert('Комната с таким названием уже существует.');
return;
}
rooms[roomName] = true;
addRoomToList(roomName);
closeCreateRoomModal();
}
function addRoomToList(roomName) {
const roomList = document.querySelector('.room-list');
const existingRoomItem = Array.from(roomList.children).find(item => item.querySelector('.room-name').textContent === roomName);
if (existingRoomItem) {
existingRoomItem.remove();
function openModal(roomName) {
currentRoom = roomName;
document.getElementById('passwordModal').style.display = 'block';
}
const roomItem = document.createElement('li');
roomItem.classList.add('room-item');
roomItem.innerHTML = `
<span class="room-name">${roomName}</span>
<button class="add-members-button" onclick="openAdd()">Добавить участников</button>
<button class="join-button" onclick="openRoom('${roomName}')">Войти</button>
`;
roomList.appendChild(roomItem);
}
function initializeRoomList() {
Object.keys(rooms).forEach(roomName => {
addRoomToList(roomName);
});
}
initializeRoomList();
window.onclick = function(event) {
if (event.target === document.getElementById('createRoomModal')) {
closeCreateRoomModal();
function closeModal() {
document.getElementById('passwordModal').style.display = 'none';
}
}
document.getElementById('newRoomName').addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
createRoom();
function openCreateRoomModal() {
document.getElementById('createRoomModal').style.display = 'block';
}
});
function closeCreateRoomModal() {
document.getElementById('createRoomModal').style.display = 'none';
}
async function createRoom() {
const errorElement = document.getElementById('error');
const roomName = document.getElementById('newRoomName').value.trim();
const roomNickname = document.getElementById('newRoomNickname').value.trim();
errorElement.style.display = 'none';
errorElement.textContent = '';
if (roomName === '' || roomNickname === '') {
errorElement.textContent = 'Пожалуйста, заполните все поля';
errorElement.style.display = 'block';
return;
}
const request = {
LocalHistoryId: currentHistoryId,
content: {
name: roomName,
nickname: roomNickname
}
};
try {
const response = await fetch('/internalapi/createChat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
});
const res = await response.json();
if (res.status === 0) {
addRoomToList(roomName, roomNickname);
closeCreateRoomModal();
currentHistoryId = res.update.LocalHistoryId;
window.location.href = '/chat/' + roomNickname;
} else {
throw new Error(res.error || 'Ошибка');
}
} catch (error) {
alert('Ошибка создания чата: ' + error.message);
}
}
function addRoomToList(roomName, roomNickname) {
const roomList = document.querySelector('.room-list');
const existingRoomItem = Array.from(roomList.children).find(item => item.querySelector('.room-name').textContent === roomName);
if (existingRoomItem) {
existingRoomItem.remove();
}
const roomItem = document.createElement('li');
roomItem.classList.add('room-item');
roomItem.innerHTML = `
<span class="room-name">${roomName}</span>
<button class="join-button" onclick="window.location.href = '/chat/${roomNickname}'">Войти</button>
`;
roomList.appendChild(roomItem);
}
async function initializeRoomList() {
try {
const response = await fetch('/internalapi/getChatList', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({})
});
const res = await response.json();
if (res.status === 0) {
res.chats.forEach(chat => {
addRoomToList(chat.content.name, chat.content.nickname);
});
} else {
throw new Error(res.error || 'Неизвестная ошибка');
}
} catch (error) {
alert('Ошибка загрузки списка чатов: ' + error.message);
}
}
async function getChatID() {
const chatNickname = window.location.pathname.split('/').pop();
const response = await fetch('/internalapi/getChatList', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({})
});
const res = await response.json();
for (const chat of res.chats) {
if (chat.content.nickname === chatNickname) {
return chat.id;
}
}
return -1;
}
document.addEventListener('DOMContentLoaded', initializeRoomList);

View File

@ -29,22 +29,40 @@ document.addEventListener('DOMContentLoaded', function() {
});
form.addEventListener('submit', function(event) {
if (!validateForm()) {
event.preventDefault();
}
event.preventDefault();
validateForm();
});
function validateForm() {
const username = document.getElementById('username').value.trim();
const login = document.getElementById('login').value.trim();
const password = document.getElementById('password').value.trim();
async function validateForm() {
const name = document.getElementById('name').value.trim();
const nickname = document.getElementById('nickname').value.trim();
if (username === '' || login === '' || password === '') {
if (name === '' || nickname === '') {
errorElement.textContent = 'Пожалуйста, заполните все поля';
errorElement.style.display = 'block';
return false;
}
try {
// Отправка данных для регистрации
let response = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({name, nickname})
});
const result = await response.json();
if (result.status === 0) {
window.location.href = '/';
} else {
throw Error(result.error);
}
} catch(error) {
errorElement.textContent = 'Попробуйте еще раз';
errorElement.style.display = 'block';
}
return true;
}
});