Spaces:
Running
Running
Update index.html
Browse files- index.html +213 -157
index.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
| 6 |
-
<title>
|
| 7 |
<style>
|
| 8 |
:root {
|
| 9 |
--bg-main: #0e1621;
|
|
@@ -427,8 +427,8 @@
|
|
| 427 |
|
| 428 |
<div id="auth-screen" class="overlay auth-overlay">
|
| 429 |
<div class="modal-card text-center">
|
| 430 |
-
<h2 class="modal-title" style="font-size: 1.5rem; text-align:center;">Web
|
| 431 |
-
<p class="modal-desc" style="text-align:center;">
|
| 432 |
|
| 433 |
<div class="modal-tabs">
|
| 434 |
<button id="tab-login" class="modal-tab active" onclick="switchAuthTab('login')">Вход</button>
|
|
@@ -444,9 +444,17 @@
|
|
| 444 |
<label class="form-label">Пароль</label>
|
| 445 |
<input type="password" id="auth-password" class="form-input" placeholder="••••••••" required />
|
| 446 |
</div>
|
| 447 |
-
<
|
| 448 |
-
|
| 449 |
-
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
</div>
|
| 451 |
<div id="auth-error" class="error-msg hidden"></div>
|
| 452 |
<button type="submit" id="auth-btn" class="btn-submit">Войти</button>
|
|
@@ -483,7 +491,7 @@
|
|
| 483 |
<div id="active-avatar" class="avatar">C</div>
|
| 484 |
<div class="chat-header-info">
|
| 485 |
<h3 id="active-title">Чат</h3>
|
| 486 |
-
<span>
|
| 487 |
</div>
|
| 488 |
</div>
|
| 489 |
|
|
@@ -580,10 +588,12 @@
|
|
| 580 |
const CONST_SERVER = 'https://matrix.unredacted.org';
|
| 581 |
const AVATAR_COLORS = ['#e11d48', '#d97706', '#059669', '#2563eb', '#7c3aed', '#db2777', '#0891b2', '#4f46e5'];
|
| 582 |
|
| 583 |
-
//
|
| 584 |
class MatrixAPI {
|
| 585 |
constructor() {
|
| 586 |
this.token = ''; this.userId = ''; this.txnId = Date.now();
|
|
|
|
|
|
|
| 587 |
}
|
| 588 |
|
| 589 |
async req(endpoint, opts = {}) {
|
|
@@ -593,7 +603,12 @@
|
|
| 593 |
|
| 594 |
const res = await fetch(`${CONST_SERVER}/_matrix/client/v3${endpoint}`, { ...opts, headers });
|
| 595 |
const data = await res.json();
|
| 596 |
-
if (!res.ok)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 597 |
return data;
|
| 598 |
}
|
| 599 |
|
|
@@ -601,86 +616,55 @@
|
|
| 601 |
return this.req('/login', { method: 'POST', body: JSON.stringify({ type: 'm.login.password', identifier: { type: 'm.id.user', user }, password: pass }) });
|
| 602 |
}
|
| 603 |
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
headers: { 'Content-Type': 'application/json' },
|
| 610 |
-
body: JSON.stringify({ username: user, password: pass })
|
| 611 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
| 612 |
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 617 |
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
body: JSON.stringify({
|
| 637 |
-
username: user,
|
| 638 |
-
password: pass,
|
| 639 |
-
auth: { type: 'm.login.dummy', session }
|
| 640 |
-
})
|
| 641 |
-
});
|
| 642 |
-
const authData = await authRes.json();
|
| 643 |
-
if (!authRes.ok) {
|
| 644 |
-
throw new Error(authData.error || 'Не удалось завершить регистрацию');
|
| 645 |
}
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
}
|
| 649 |
-
|
| 650 |
-
// Проверяем, есть ли поток, включающий m.login.registration_token
|
| 651 |
-
const tokenFlow = flows.find(flow =>
|
| 652 |
-
flow.stages && flow.stages.includes('m.login.registration_token')
|
| 653 |
-
);
|
| 654 |
-
if (tokenFlow) {
|
| 655 |
-
if (!registrationToken) {
|
| 656 |
-
// Требуется токен, но он не предоставлен
|
| 657 |
-
const err = new Error('Для регистрации требуется токен. Введите его в поле ниже.');
|
| 658 |
-
err.requiresToken = true;
|
| 659 |
-
throw err;
|
| 660 |
-
}
|
| 661 |
-
// Отправляем с токеном
|
| 662 |
-
const authRes = await fetch(`${CONST_SERVER}/_matrix/client/v3/register`, {
|
| 663 |
-
method: 'POST',
|
| 664 |
-
headers: { 'Content-Type': 'application/json' },
|
| 665 |
-
body: JSON.stringify({
|
| 666 |
-
username: user,
|
| 667 |
-
password: pass,
|
| 668 |
-
auth: {
|
| 669 |
-
type: 'm.login.registration_token',
|
| 670 |
-
token: registrationToken,
|
| 671 |
-
session
|
| 672 |
-
}
|
| 673 |
-
})
|
| 674 |
-
});
|
| 675 |
-
const authData = await authRes.json();
|
| 676 |
-
if (!authRes.ok) {
|
| 677 |
-
throw new Error(authData.error || 'Не удалось завершить регистрацию с токеном');
|
| 678 |
-
}
|
| 679 |
-
return authData;
|
| 680 |
-
}
|
| 681 |
-
|
| 682 |
-
// Если ни один из поддерживаемых методов не найден
|
| 683 |
-
throw new Error('Сервер требует неподдерживаемый метод аутентификации (например, капчу). Регистрация невозможна.');
|
| 684 |
}
|
| 685 |
|
| 686 |
async uploadMedia(file) {
|
|
@@ -704,35 +688,16 @@
|
|
| 704 |
}
|
| 705 |
}
|
| 706 |
|
| 707 |
-
// Crypto Layer for payload isolation
|
| 708 |
-
class Security {
|
| 709 |
-
static async getK(secret) {
|
| 710 |
-
const e = new TextEncoder();
|
| 711 |
-
const m = await crypto.subtle.importKey("raw", e.encode(secret), { name: "PBKDF2" }, false, ["deriveKey"]);
|
| 712 |
-
return crypto.subtle.deriveKey({ name: "PBKDF2", salt: e.encode("tweb-salt-v1"), iterations: 100000, hash: "SHA-256" }, m, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
|
| 713 |
-
}
|
| 714 |
-
static async encrypt(obj, secret) {
|
| 715 |
-
const k = await this.getK(secret);
|
| 716 |
-
const iv = crypto.getRandomValues(new Uint8Array(12));
|
| 717 |
-
const enc = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, k, new TextEncoder().encode(JSON.stringify(obj)));
|
| 718 |
-
return { iv: btoa(String.fromCharCode(...iv)), data: btoa(String.fromCharCode(...new Uint8Array(enc))) };
|
| 719 |
-
}
|
| 720 |
-
static async decrypt(encObj, secret) {
|
| 721 |
-
try {
|
| 722 |
-
const k = await this.getK(secret);
|
| 723 |
-
const iv = Uint8Array.from(atob(encObj.iv), c => c.charCodeAt(0));
|
| 724 |
-
const data = Uint8Array.from(atob(encObj.data), c => c.charCodeAt(0));
|
| 725 |
-
const dec = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, k, data);
|
| 726 |
-
return JSON.parse(new TextDecoder().decode(dec));
|
| 727 |
-
} catch(e) { return null; }
|
| 728 |
-
}
|
| 729 |
-
}
|
| 730 |
-
|
| 731 |
const mx = new MatrixAPI();
|
| 732 |
const state = {
|
| 733 |
-
session: JSON.parse(localStorage.getItem('
|
| 734 |
rooms: {}, msgs: {}, activeRoom: null, syncLoop: false,
|
| 735 |
-
replyTo: null, contextMsgId: null
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 736 |
};
|
| 737 |
|
| 738 |
window.onload = () => {
|
|
@@ -762,9 +727,17 @@
|
|
| 762 |
document.getElementById('tab-register').classList.toggle('active', m==='register');
|
| 763 |
document.getElementById('auth-btn').textContent = m==='login' ? 'Войти' : 'Зарегистрироваться';
|
| 764 |
document.getElementById('auth-error').classList.add('hidden');
|
| 765 |
-
//
|
| 766 |
-
document.getElementById('
|
| 767 |
-
document.getElementById('
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 768 |
}
|
| 769 |
|
| 770 |
async function handleAuthSubmit(e) {
|
|
@@ -773,40 +746,112 @@
|
|
| 773 |
const err = document.getElementById('auth-error');
|
| 774 |
const u = document.getElementById('auth-username').value.trim();
|
| 775 |
const p = document.getElementById('auth-password').value;
|
| 776 |
-
const
|
| 777 |
-
const
|
| 778 |
|
| 779 |
btn.disabled = true; err.classList.add('hidden');
|
| 780 |
try {
|
| 781 |
-
let res;
|
| 782 |
if (btn.textContent === 'Войти') {
|
| 783 |
-
res = await mx.login(u, p);
|
|
|
|
|
|
|
|
|
|
| 784 |
} else {
|
| 785 |
-
//
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
//
|
| 791 |
-
|
| 792 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 793 |
err.classList.remove('hidden');
|
| 794 |
btn.disabled = false;
|
| 795 |
return;
|
| 796 |
}
|
| 797 |
-
|
|
|
|
|
|
|
|
|
|
| 798 |
}
|
| 799 |
}
|
| 800 |
-
state.session = { token: res.access_token, userId: res.user_id };
|
| 801 |
-
localStorage.setItem('tw_sess', JSON.stringify(state.session));
|
| 802 |
-
initApp();
|
| 803 |
} catch(ex) {
|
| 804 |
err.textContent = ex.message; err.classList.remove('hidden');
|
| 805 |
} finally { btn.disabled = false; }
|
| 806 |
}
|
| 807 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 808 |
function handleLogout() {
|
| 809 |
-
state.syncLoop = false; localStorage.removeItem('
|
| 810 |
}
|
| 811 |
|
| 812 |
async function initApp() {
|
|
@@ -854,7 +899,6 @@
|
|
| 854 |
state.rooms[id] = { id, name: "Чат", avatar: null, ts: 0, preview: "" };
|
| 855 |
}
|
| 856 |
|
| 857 |
-
// Parse Name & Avatar from state
|
| 858 |
if (rData.state && rData.state.events) {
|
| 859 |
let rName = null, rAv = null, otherMember = null;
|
| 860 |
for(const ev of rData.state.events) {
|
|
@@ -882,28 +926,35 @@
|
|
| 882 |
if(changed) { renderRoomList(); if(state.activeRoom) renderChat(); }
|
| 883 |
}
|
| 884 |
|
| 885 |
-
|
| 886 |
if(!state.msgs[roomId]) state.msgs[roomId] = [];
|
| 887 |
if(state.msgs[roomId].some(m => m.id === ev.event_id)) return;
|
| 888 |
|
| 889 |
-
let
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
|
|
|
|
|
|
|
|
|
| 895 |
}
|
| 896 |
|
| 897 |
const msg = {
|
| 898 |
-
id: ev.event_id,
|
|
|
|
| 899 |
senderName: ev.sender.split(':')[0].substring(1),
|
| 900 |
-
text:
|
| 901 |
-
|
|
|
|
|
|
|
|
|
|
| 902 |
};
|
| 903 |
|
| 904 |
state.msgs[roomId].push(msg);
|
| 905 |
state.rooms[roomId].ts = msg.ts;
|
| 906 |
-
state.rooms[roomId].preview =
|
| 907 |
}
|
| 908 |
|
| 909 |
function renderRoomList() {
|
|
@@ -1003,12 +1054,21 @@
|
|
| 1003 |
inp.value = '';
|
| 1004 |
const roomId = state.activeRoom;
|
| 1005 |
|
| 1006 |
-
let
|
|
|
|
|
|
|
|
|
|
| 1007 |
if (fileObj) {
|
| 1008 |
-
|
| 1009 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1010 |
}
|
| 1011 |
-
if (state.replyTo) payload.replyTo = state.replyTo.id;
|
| 1012 |
|
| 1013 |
cancelReply();
|
| 1014 |
|
|
@@ -1018,19 +1078,15 @@
|
|
| 1018 |
if(!state.msgs[roomId]) state.msgs[roomId] = [];
|
| 1019 |
state.msgs[roomId].push({
|
| 1020 |
id: tempId, senderId: mx.userId, senderName: state.session.name,
|
| 1021 |
-
text:
|
| 1022 |
-
|
|
|
|
|
|
|
|
|
|
| 1023 |
});
|
| 1024 |
renderChat();
|
| 1025 |
|
| 1026 |
-
const enc = await Security.encrypt(payload, roomId);
|
| 1027 |
-
const content = {
|
| 1028 |
-
msgtype: 'm.text', body: '🔒 Зашифрованное сообщение. Откройте в Web Telegram.',
|
| 1029 |
-
'x.tw.enc': enc
|
| 1030 |
-
};
|
| 1031 |
-
|
| 1032 |
const res = await mx.sendEvent(roomId, 'm.room.message', content);
|
| 1033 |
-
// Replace temp ID
|
| 1034 |
const m = state.msgs[roomId].find(x => x.id === tempId);
|
| 1035 |
if(m) m.id = res.event_id;
|
| 1036 |
} catch(e) { console.error(e); alert('Ошибка отправки'); }
|
|
@@ -1042,7 +1098,7 @@
|
|
| 1042 |
e.target.value = '';
|
| 1043 |
try {
|
| 1044 |
const url = await mx.uploadMedia(file);
|
| 1045 |
-
handleSendMessage({ url, type: file.type });
|
| 1046 |
} catch(ex) { alert("Ошибка загрузки файла"); }
|
| 1047 |
}
|
| 1048 |
|
|
@@ -1141,7 +1197,7 @@
|
|
| 1141 |
try {
|
| 1142 |
await mx.req(`/profile/${encodeURIComponent(mx.userId)}/displayname`, { method: 'PUT', body: JSON.stringify({ displayname: n }) });
|
| 1143 |
state.session.name = n;
|
| 1144 |
-
localStorage.setItem('
|
| 1145 |
updateMyProfileUI();
|
| 1146 |
closeSettingsModal();
|
| 1147 |
} catch(e) { alert("Ошибка сохранения"); }
|
|
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
| 6 |
+
<title>Matrix Web Client</title>
|
| 7 |
<style>
|
| 8 |
:root {
|
| 9 |
--bg-main: #0e1621;
|
|
|
|
| 427 |
|
| 428 |
<div id="auth-screen" class="overlay auth-overlay">
|
| 429 |
<div class="modal-card text-center">
|
| 430 |
+
<h2 class="modal-title" style="font-size: 1.5rem; text-align:center;">Matrix Web Client</h2>
|
| 431 |
+
<p class="modal-desc" style="text-align:center;">Простой клиент для Matrix сервера</p>
|
| 432 |
|
| 433 |
<div class="modal-tabs">
|
| 434 |
<button id="tab-login" class="modal-tab active" onclick="switchAuthTab('login')">Вход</button>
|
|
|
|
| 444 |
<label class="form-label">Пароль</label>
|
| 445 |
<input type="password" id="auth-password" class="form-input" placeholder="••••••••" required />
|
| 446 |
</div>
|
| 447 |
+
<!-- Поля для регистрации с email -->
|
| 448 |
+
<div id="register-email-group" class="form-group hidden">
|
| 449 |
+
<label class="form-label">Email</label>
|
| 450 |
+
<input type="email" id="register-email" class="form-input" placeholder="user@example.com" />
|
| 451 |
+
</div>
|
| 452 |
+
<div id="register-code-group" class="form-group hidden">
|
| 453 |
+
<label class="form-label">Код подтверждения</label>
|
| 454 |
+
<input type="text" id="register-code" class="form-input" placeholder="Введите код" />
|
| 455 |
+
</div>
|
| 456 |
+
<div class="form-group hidden" id="register-send-code-group">
|
| 457 |
+
<button type="button" class="btn-secondary" onclick="sendEmailCode()">Отправить код на email</button>
|
| 458 |
</div>
|
| 459 |
<div id="auth-error" class="error-msg hidden"></div>
|
| 460 |
<button type="submit" id="auth-btn" class="btn-submit">Войти</button>
|
|
|
|
| 491 |
<div id="active-avatar" class="avatar">C</div>
|
| 492 |
<div class="chat-header-info">
|
| 493 |
<h3 id="active-title">Чат</h3>
|
| 494 |
+
<span>Онлайн</span>
|
| 495 |
</div>
|
| 496 |
</div>
|
| 497 |
|
|
|
|
| 588 |
const CONST_SERVER = 'https://matrix.unredacted.org';
|
| 589 |
const AVATAR_COLORS = ['#e11d48', '#d97706', '#059669', '#2563eb', '#7c3aed', '#db2777', '#0891b2', '#4f46e5'];
|
| 590 |
|
| 591 |
+
// Simple Matrix API wrapper
|
| 592 |
class MatrixAPI {
|
| 593 |
constructor() {
|
| 594 |
this.token = ''; this.userId = ''; this.txnId = Date.now();
|
| 595 |
+
this.registerSession = null;
|
| 596 |
+
this.clientSecret = null;
|
| 597 |
}
|
| 598 |
|
| 599 |
async req(endpoint, opts = {}) {
|
|
|
|
| 603 |
|
| 604 |
const res = await fetch(`${CONST_SERVER}/_matrix/client/v3${endpoint}`, { ...opts, headers });
|
| 605 |
const data = await res.json();
|
| 606 |
+
if (!res.ok) {
|
| 607 |
+
const err = new Error(data.error || 'Ошибка Matrix API');
|
| 608 |
+
err.status = res.status;
|
| 609 |
+
err.data = data;
|
| 610 |
+
throw err;
|
| 611 |
+
}
|
| 612 |
return data;
|
| 613 |
}
|
| 614 |
|
|
|
|
| 616 |
return this.req('/login', { method: 'POST', body: JSON.stringify({ type: 'm.login.password', identifier: { type: 'm.id.user', user }, password: pass }) });
|
| 617 |
}
|
| 618 |
|
| 619 |
+
async registerInit(user, pass) {
|
| 620 |
+
// Step 1: initial register attempt
|
| 621 |
+
const res = await this.req('/register', {
|
| 622 |
+
method: 'POST',
|
| 623 |
+
body: JSON.stringify({ username: user, password: pass })
|
|
|
|
|
|
|
| 624 |
});
|
| 625 |
+
// If success, return token etc.
|
| 626 |
+
if (res.access_token) return res;
|
| 627 |
+
// Shouldn't happen because req throws on non-2xx
|
| 628 |
+
}
|
| 629 |
|
| 630 |
+
async registerWithDummy(user, pass, session) {
|
| 631 |
+
return this.req('/register', {
|
| 632 |
+
method: 'POST',
|
| 633 |
+
body: JSON.stringify({
|
| 634 |
+
username: user,
|
| 635 |
+
password: pass,
|
| 636 |
+
auth: { type: 'm.login.dummy', session }
|
| 637 |
+
})
|
| 638 |
+
});
|
| 639 |
+
}
|
| 640 |
|
| 641 |
+
async registerRequestEmail(email, clientSecret, sendAttempt = 1) {
|
| 642 |
+
return this.req('/register/email/requestToken', {
|
| 643 |
+
method: 'POST',
|
| 644 |
+
body: JSON.stringify({
|
| 645 |
+
client_secret: clientSecret,
|
| 646 |
+
email: email,
|
| 647 |
+
send_attempt: sendAttempt
|
| 648 |
+
})
|
| 649 |
+
});
|
| 650 |
+
}
|
| 651 |
|
| 652 |
+
async registerWithEmail(user, pass, session, clientSecret, sid) {
|
| 653 |
+
return this.req('/register', {
|
| 654 |
+
method: 'POST',
|
| 655 |
+
body: JSON.stringify({
|
| 656 |
+
username: user,
|
| 657 |
+
password: pass,
|
| 658 |
+
auth: {
|
| 659 |
+
type: 'm.login.email.identity',
|
| 660 |
+
threepid_creds: {
|
| 661 |
+
client_secret: clientSecret,
|
| 662 |
+
sid: sid
|
| 663 |
+
},
|
| 664 |
+
session: session
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 665 |
}
|
| 666 |
+
})
|
| 667 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 668 |
}
|
| 669 |
|
| 670 |
async uploadMedia(file) {
|
|
|
|
| 688 |
}
|
| 689 |
}
|
| 690 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 691 |
const mx = new MatrixAPI();
|
| 692 |
const state = {
|
| 693 |
+
session: JSON.parse(localStorage.getItem('mx_sess') || 'null'),
|
| 694 |
rooms: {}, msgs: {}, activeRoom: null, syncLoop: false,
|
| 695 |
+
replyTo: null, contextMsgId: null,
|
| 696 |
+
// Registration state
|
| 697 |
+
regFlow: null,
|
| 698 |
+
regSession: null,
|
| 699 |
+
regClientSecret: null,
|
| 700 |
+
regSid: null
|
| 701 |
};
|
| 702 |
|
| 703 |
window.onload = () => {
|
|
|
|
| 727 |
document.getElementById('tab-register').classList.toggle('active', m==='register');
|
| 728 |
document.getElementById('auth-btn').textContent = m==='login' ? 'Войти' : 'Зарегистрироваться';
|
| 729 |
document.getElementById('auth-error').classList.add('hidden');
|
| 730 |
+
// Hide email/register-specific fields
|
| 731 |
+
document.getElementById('register-email-group').classList.add('hidden');
|
| 732 |
+
document.getElementById('register-code-group').classList.add('hidden');
|
| 733 |
+
document.getElementById('register-send-code-group').classList.add('hidden');
|
| 734 |
+
document.getElementById('register-email').value = '';
|
| 735 |
+
document.getElementById('register-code').value = '';
|
| 736 |
+
// Reset registration state
|
| 737 |
+
state.regFlow = null;
|
| 738 |
+
state.regSession = null;
|
| 739 |
+
state.regClientSecret = null;
|
| 740 |
+
state.regSid = null;
|
| 741 |
}
|
| 742 |
|
| 743 |
async function handleAuthSubmit(e) {
|
|
|
|
| 746 |
const err = document.getElementById('auth-error');
|
| 747 |
const u = document.getElementById('auth-username').value.trim();
|
| 748 |
const p = document.getElementById('auth-password').value;
|
| 749 |
+
const email = document.getElementById('register-email').value.trim();
|
| 750 |
+
const code = document.getElementById('register-code').value.trim();
|
| 751 |
|
| 752 |
btn.disabled = true; err.classList.add('hidden');
|
| 753 |
try {
|
|
|
|
| 754 |
if (btn.textContent === 'Войти') {
|
| 755 |
+
const res = await mx.login(u, p);
|
| 756 |
+
state.session = { token: res.access_token, userId: res.user_id };
|
| 757 |
+
localStorage.setItem('mx_sess', JSON.stringify(state.session));
|
| 758 |
+
initApp();
|
| 759 |
} else {
|
| 760 |
+
// Registration flow
|
| 761 |
+
if (!state.regSession) {
|
| 762 |
+
// Initial attempt
|
| 763 |
+
try {
|
| 764 |
+
const res = await mx.registerInit(u, p);
|
| 765 |
+
// If immediate success (rare)
|
| 766 |
+
if (res.access_token) {
|
| 767 |
+
state.session = { token: res.access_token, userId: res.user_id };
|
| 768 |
+
localStorage.setItem('mx_sess', JSON.stringify(state.session));
|
| 769 |
+
initApp();
|
| 770 |
+
return;
|
| 771 |
+
}
|
| 772 |
+
} catch (ex) {
|
| 773 |
+
if (ex.status === 401 && ex.data && ex.data.session) {
|
| 774 |
+
state.regSession = ex.data.session;
|
| 775 |
+
const flows = ex.data.flows || [];
|
| 776 |
+
// Check available flows
|
| 777 |
+
if (flows.some(f => f.stages && f.stages.length === 1 && f.stages[0] === 'm.login.dummy')) {
|
| 778 |
+
// Try dummy
|
| 779 |
+
const res2 = await mx.registerWithDummy(u, p, state.regSession);
|
| 780 |
+
state.session = { token: res2.access_token, userId: res2.user_id };
|
| 781 |
+
localStorage.setItem('mx_sess', JSON.stringify(state.session));
|
| 782 |
+
initApp();
|
| 783 |
+
return;
|
| 784 |
+
} else if (flows.some(f => f.stages && f.stages.includes('m.login.email.identity'))) {
|
| 785 |
+
// Email required
|
| 786 |
+
state.regFlow = 'email';
|
| 787 |
+
showEmailFields();
|
| 788 |
+
err.textContent = 'Для регистрации требуется email. Введите email и отправьте код.';
|
| 789 |
+
err.classList.remove('hidden');
|
| 790 |
+
btn.disabled = false;
|
| 791 |
+
return;
|
| 792 |
+
} else {
|
| 793 |
+
throw new Error('Сервер не поддерживает доступные методы регистрации');
|
| 794 |
+
}
|
| 795 |
+
} else {
|
| 796 |
+
throw ex;
|
| 797 |
+
}
|
| 798 |
+
}
|
| 799 |
+
} else if (state.regFlow === 'email') {
|
| 800 |
+
// We have session, need to complete email verification
|
| 801 |
+
if (!state.regSid) {
|
| 802 |
+
err.textContent = 'Сначала отправьте код на email.';
|
| 803 |
+
err.classList.remove('hidden');
|
| 804 |
+
btn.disabled = false;
|
| 805 |
+
return;
|
| 806 |
+
}
|
| 807 |
+
if (!code) {
|
| 808 |
+
err.textContent = 'Введите код подтверждения.';
|
| 809 |
err.classList.remove('hidden');
|
| 810 |
btn.disabled = false;
|
| 811 |
return;
|
| 812 |
}
|
| 813 |
+
const res = await mx.registerWithEmail(u, p, state.regSession, state.regClientSecret, state.regSid);
|
| 814 |
+
state.session = { token: res.access_token, userId: res.user_id };
|
| 815 |
+
localStorage.setItem('mx_sess', JSON.stringify(state.session));
|
| 816 |
+
initApp();
|
| 817 |
}
|
| 818 |
}
|
|
|
|
|
|
|
|
|
|
| 819 |
} catch(ex) {
|
| 820 |
err.textContent = ex.message; err.classList.remove('hidden');
|
| 821 |
} finally { btn.disabled = false; }
|
| 822 |
}
|
| 823 |
|
| 824 |
+
function showEmailFields() {
|
| 825 |
+
document.getElementById('register-email-group').classList.remove('hidden');
|
| 826 |
+
document.getElementById('register-send-code-group').classList.remove('hidden');
|
| 827 |
+
}
|
| 828 |
+
|
| 829 |
+
async function sendEmailCode() {
|
| 830 |
+
const email = document.getElementById('register-email').value.trim();
|
| 831 |
+
if (!email) {
|
| 832 |
+
alert('Введите email');
|
| 833 |
+
return;
|
| 834 |
+
}
|
| 835 |
+
// Generate client secret if not exists
|
| 836 |
+
if (!state.regClientSecret) {
|
| 837 |
+
state.regClientSecret = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
| 838 |
+
}
|
| 839 |
+
try {
|
| 840 |
+
const res = await mx.registerRequestEmail(email, state.regClientSecret);
|
| 841 |
+
state.regSid = res.sid;
|
| 842 |
+
document.getElementById('register-code-group').classList.remove('hidden');
|
| 843 |
+
document.getElementById('register-send-code-group').classList.add('hidden');
|
| 844 |
+
// Show success message
|
| 845 |
+
const err = document.getElementById('auth-error');
|
| 846 |
+
err.textContent = 'Код отправлен на email. Введите его ниже.';
|
| 847 |
+
err.classList.remove('hidden');
|
| 848 |
+
} catch (ex) {
|
| 849 |
+
alert('Ошибка отправки кода: ' + ex.message);
|
| 850 |
+
}
|
| 851 |
+
}
|
| 852 |
+
|
| 853 |
function handleLogout() {
|
| 854 |
+
state.syncLoop = false; localStorage.removeItem('mx_sess'); location.reload();
|
| 855 |
}
|
| 856 |
|
| 857 |
async function initApp() {
|
|
|
|
| 899 |
state.rooms[id] = { id, name: "Чат", avatar: null, ts: 0, preview: "" };
|
| 900 |
}
|
| 901 |
|
|
|
|
| 902 |
if (rData.state && rData.state.events) {
|
| 903 |
let rName = null, rAv = null, otherMember = null;
|
| 904 |
for(const ev of rData.state.events) {
|
|
|
|
| 926 |
if(changed) { renderRoomList(); if(state.activeRoom) renderChat(); }
|
| 927 |
}
|
| 928 |
|
| 929 |
+
function processMsg(roomId, ev) {
|
| 930 |
if(!state.msgs[roomId]) state.msgs[roomId] = [];
|
| 931 |
if(state.msgs[roomId].some(m => m.id === ev.event_id)) return;
|
| 932 |
|
| 933 |
+
let text = '';
|
| 934 |
+
let fileUrl = null;
|
| 935 |
+
let fileType = null;
|
| 936 |
+
if(ev.content.msgtype === 'm.text') {
|
| 937 |
+
text = ev.content.body || '';
|
| 938 |
+
} else if(ev.content.msgtype === 'm.image' || ev.content.msgtype === 'm.file') {
|
| 939 |
+
text = ev.content.body || 'Файл';
|
| 940 |
+
fileUrl = ev.content.url ? mx.mxcToHttp(ev.content.url) : null;
|
| 941 |
+
fileType = ev.content.info?.mimetype || null;
|
| 942 |
}
|
| 943 |
|
| 944 |
const msg = {
|
| 945 |
+
id: ev.event_id,
|
| 946 |
+
senderId: ev.sender,
|
| 947 |
senderName: ev.sender.split(':')[0].substring(1),
|
| 948 |
+
text: text,
|
| 949 |
+
fileUrl: fileUrl,
|
| 950 |
+
fileType: fileType,
|
| 951 |
+
replyTo: ev.content['m.relates_to']?.m.in_reply_to?.event_id || null,
|
| 952 |
+
ts: ev.origin_server_ts || Date.now()
|
| 953 |
};
|
| 954 |
|
| 955 |
state.msgs[roomId].push(msg);
|
| 956 |
state.rooms[roomId].ts = msg.ts;
|
| 957 |
+
state.rooms[roomId].preview = fileUrl ? "📎 Файл" : text;
|
| 958 |
}
|
| 959 |
|
| 960 |
function renderRoomList() {
|
|
|
|
| 1054 |
inp.value = '';
|
| 1055 |
const roomId = state.activeRoom;
|
| 1056 |
|
| 1057 |
+
let content = {
|
| 1058 |
+
msgtype: 'm.text',
|
| 1059 |
+
body: text
|
| 1060 |
+
};
|
| 1061 |
if (fileObj) {
|
| 1062 |
+
content = {
|
| 1063 |
+
msgtype: 'm.file',
|
| 1064 |
+
body: fileObj.name || 'Файл',
|
| 1065 |
+
url: fileObj.url,
|
| 1066 |
+
info: { mimetype: fileObj.type }
|
| 1067 |
+
};
|
| 1068 |
+
}
|
| 1069 |
+
if (state.replyTo) {
|
| 1070 |
+
content['m.relates_to'] = { 'm.in_reply_to': { event_id: state.replyTo.id } };
|
| 1071 |
}
|
|
|
|
| 1072 |
|
| 1073 |
cancelReply();
|
| 1074 |
|
|
|
|
| 1078 |
if(!state.msgs[roomId]) state.msgs[roomId] = [];
|
| 1079 |
state.msgs[roomId].push({
|
| 1080 |
id: tempId, senderId: mx.userId, senderName: state.session.name,
|
| 1081 |
+
text: text || (fileObj ? (fileObj.name || 'Файл') : ''),
|
| 1082 |
+
fileUrl: fileObj ? mx.mxcToHttp(fileObj.url) : null,
|
| 1083 |
+
fileType: fileObj ? fileObj.type : null,
|
| 1084 |
+
replyTo: state.replyTo ? state.replyTo.id : null,
|
| 1085 |
+
ts: Date.now()
|
| 1086 |
});
|
| 1087 |
renderChat();
|
| 1088 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1089 |
const res = await mx.sendEvent(roomId, 'm.room.message', content);
|
|
|
|
| 1090 |
const m = state.msgs[roomId].find(x => x.id === tempId);
|
| 1091 |
if(m) m.id = res.event_id;
|
| 1092 |
} catch(e) { console.error(e); alert('Ошибка отправки'); }
|
|
|
|
| 1098 |
e.target.value = '';
|
| 1099 |
try {
|
| 1100 |
const url = await mx.uploadMedia(file);
|
| 1101 |
+
handleSendMessage({ url, type: file.type, name: file.name });
|
| 1102 |
} catch(ex) { alert("Ошибка загрузки файла"); }
|
| 1103 |
}
|
| 1104 |
|
|
|
|
| 1197 |
try {
|
| 1198 |
await mx.req(`/profile/${encodeURIComponent(mx.userId)}/displayname`, { method: 'PUT', body: JSON.stringify({ displayname: n }) });
|
| 1199 |
state.session.name = n;
|
| 1200 |
+
localStorage.setItem('mx_sess', JSON.stringify(state.session));
|
| 1201 |
updateMyProfileUI();
|
| 1202 |
closeSettingsModal();
|
| 1203 |
} catch(e) { alert("Ошибка сохранения"); }
|