mirror of
https://github.com/fromchat-messenger/web.git
synced 2026-09-22 19:15:08 +03:00
Compare commits
142 Commits
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"mdui": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@mdui/mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
When working with this project, follow these rules:
|
||||
|
||||
- NEVER do anything i didn't ask you for!
|
||||
- Use double quotes ("") for strings.
|
||||
- Do NOT "test the implementation" when you are done. The only exception is when you
|
||||
need to typecheck or build the app, in that case:
|
||||
|
||||
- To typecheck, run `npm run frontend:typecheck`.
|
||||
- To build, run `npm run frontend:build`.
|
||||
|
||||
Do NOT execute other commands like "cd".
|
||||
- Do NOT "cd" to the project directory.
|
||||
- If possible, try to update files in a single edit.
|
||||
- When you need a delay, use `await delay(millis);` in an async function. If the current function is not async,
|
||||
make it async. The import is `<project>/frontend/src/utils/utils`.
|
||||
- When you complete your task, remove unused imports if there are any.
|
||||
@@ -4,5 +4,7 @@ alwaysApply: true
|
||||
|
||||
When you work with UI:
|
||||
|
||||
1. Use MDUI components as HTML elements
|
||||
2. Do NOT dynamically create HTML if it's going to be loaded when the page loads, instead put it statically in the HTML.
|
||||
1. Use MDUI components as HTML elements with the name "mdui-***". In JSX/TSX use the same elements and props as in HTML.
|
||||
2. Do NOT dynamically create HTML if it's going to be loaded when the page loads, instead put it statically in the HTML.
|
||||
3. The supporting text slot for MDUI lists is "description".
|
||||
4. When working with lists/sets in states, use the "useImmer" hook.
|
||||
+123
-49
@@ -1,35 +1,133 @@
|
||||
name: Build Electron Apps
|
||||
name: Build Electron app
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
apiBaseUrl:
|
||||
description: "API base URL"
|
||||
required: false
|
||||
default: "fromchat.ru"
|
||||
type: string
|
||||
push:
|
||||
branches: ["main", "electron"]
|
||||
tags: ["v**"]
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'package.json'
|
||||
- 'package-lock.json'
|
||||
- 'frontend/electron/**'
|
||||
- '.github/workflows/build.yml'
|
||||
|
||||
concurrency:
|
||||
group: build-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
build-linux:
|
||||
name: Build Linux
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules
|
||||
key: npm-ubuntu-latest-node-24-${{ hashFiles('package.json') }}
|
||||
restore-keys: |
|
||||
npm-ubuntu-latest-node-24-
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install --ignore-scripts --no-audit --no-fund
|
||||
|
||||
- name: Cache Electron downloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cache/electron
|
||||
~/.cache/electron-builder
|
||||
key: electron-ubuntu-latest-${{ hashFiles('package.json', 'package.json') }}
|
||||
restore-keys: |
|
||||
electron-ubuntu-latest-
|
||||
|
||||
- name: Build Electron app
|
||||
shell: bash
|
||||
env:
|
||||
VITE_API_BASE_URL: ${{ inputs.apiBaseUrl }}
|
||||
run: npm run build:electron
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: FromChat-linux
|
||||
path: |
|
||||
frontend/build/electron/forge/make/*/**
|
||||
if-no-files-found: error
|
||||
|
||||
build-macos:
|
||||
name: Build macOS
|
||||
runs-on: macos-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules
|
||||
key: npm-macos-latest-node-24-${{ hashFiles('package.json') }}
|
||||
restore-keys: |
|
||||
npm-macos-latest-node-24-
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install --ignore-scripts --no-audit --no-fund
|
||||
|
||||
# - name: Cache Electron downloads
|
||||
# uses: actions/cache@v4
|
||||
# with:
|
||||
# path: |
|
||||
# ~/.cache/electron
|
||||
# ~/.cache/electron-builder
|
||||
# key: electron-macos-latest-${{ hashFiles('package.json') }}
|
||||
# restore-keys: |
|
||||
# electron-macos-latest-
|
||||
|
||||
- name: Build Electron app
|
||||
shell: bash
|
||||
env:
|
||||
VITE_API_BASE_URL: ${{ inputs.apiBaseUrl }}
|
||||
run: npm run build:electron
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: FromChat-macOS
|
||||
path: |
|
||||
frontend/build/electron/forge/make/zip/darwin/*/**.zip
|
||||
if-no-files-found: error
|
||||
|
||||
build-windows:
|
||||
name: Build Windows
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Force npm to use Bash
|
||||
if: runner.os == 'Windows'
|
||||
run: npm config set script-shell "C:\Program Files\Git\bin\bash.exe"
|
||||
|
||||
- name: Setup Node.js
|
||||
@@ -37,61 +135,37 @@ jobs:
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Cache npm (Linux/macOS)
|
||||
if: runner.os != 'Windows'
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-node-24-${{ hashFiles('package.json') }}
|
||||
path: node_modules
|
||||
key: npm-windows-latest-node-24-${{ hashFiles('package.json') }}
|
||||
restore-keys: |
|
||||
npm-${{ runner.os }}-node-24-
|
||||
npm-windows-latest-node-24-
|
||||
|
||||
- name: Cache npm (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~\AppData\Local\npm-cache
|
||||
key: npm-${{ runner.os }}-node-24-${{ hashFiles('package.json') }}
|
||||
restore-keys: |
|
||||
npm-${{ runner.os }}-node-24-
|
||||
|
||||
- name: Install root deps (no scripts)
|
||||
- name: Install dependencies
|
||||
run: npm install --ignore-scripts --no-audit --no-fund
|
||||
|
||||
- name: Install Electron Forge deps
|
||||
run: npm run frontend:electron:dependencies
|
||||
|
||||
- name: Cache Electron downloads (Linux/macOS)
|
||||
if: runner.os != 'Windows'
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cache/electron
|
||||
~/.cache/electron-builder
|
||||
key: electron-${{ runner.os }}-${{ hashFiles('package.json', 'frontend/electron/forge/package.json') }}
|
||||
restore-keys: |
|
||||
electron-${{ runner.os }}-
|
||||
|
||||
- name: Cache Electron downloads (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
- name: Cache Electron downloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~\AppData\Local\electron\Cache
|
||||
~\AppData\Local\electron-builder\Cache
|
||||
key: electron-${{ runner.os }}-${{ hashFiles('package.json', 'frontend/electron/forge/package.json') }}
|
||||
key: electron-windows-latest-${{ hashFiles('package.json') }}
|
||||
restore-keys: |
|
||||
electron-${{ runner.os }}-
|
||||
electron-windows-latest-
|
||||
|
||||
- name: Build Electron app
|
||||
shell: bash
|
||||
env:
|
||||
VITE_API_BASE_URL: ${{ inputs.apiBaseUrl }}
|
||||
run: npm run build:electron
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: fromchat-${{ runner.os }}
|
||||
name: FromChat-windows
|
||||
path: |
|
||||
frontend/electron/forge/out/**
|
||||
if-no-files-found: error
|
||||
|
||||
frontend/build/electron/forge/make/zip/win32/x64
|
||||
if-no-files-found: error
|
||||
@@ -5,6 +5,15 @@ on:
|
||||
# Runs on pushes targeting the default branch
|
||||
push:
|
||||
branches: ["main"]
|
||||
paths:
|
||||
- "backend/**"
|
||||
- "frontend/**"
|
||||
- "deployment/**"
|
||||
- "**/package.json"
|
||||
- ".nvmrc"
|
||||
- ".github/workflows/deploy.yml"
|
||||
- "!frontend/electron/**"
|
||||
- "!**.d.ts"
|
||||
workflow_dispatch:
|
||||
|
||||
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
|
||||
@@ -13,6 +22,9 @@ concurrency:
|
||||
group: "pages"
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: self-hosted
|
||||
@@ -20,7 +32,7 @@ jobs:
|
||||
HOME: "/root"
|
||||
environment:
|
||||
name: production
|
||||
url: https://fromchat.toolbox-io.ru
|
||||
url: https://fromchat.ru
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -30,6 +42,8 @@ jobs:
|
||||
touch deployment/.env
|
||||
cat > deployment/.env << EOF
|
||||
JWT_SECRET=${{ secrets.JWT_SECRET }}
|
||||
VAPID_PUBLIC_KEY=${{ secrets.VAPID_PUBLIC_KEY }}
|
||||
VAPID_PRIVATE_KEY=${{ secrets.VAPID_PRIVATE_KEY }}
|
||||
EOF
|
||||
- name: Build container
|
||||
run: |
|
||||
|
||||
+4
-1
@@ -380,4 +380,7 @@ data
|
||||
.vite
|
||||
*.db
|
||||
package-lock.json
|
||||
dist-electron
|
||||
dist-electron
|
||||
backend/migrations/**
|
||||
!backend/migrations/env.py
|
||||
!backend/migrations/script.py.mako
|
||||
Executable
+2
@@ -0,0 +1,2 @@
|
||||
#!/bin/sh
|
||||
npm run frontend:typecheck
|
||||
Vendored
+4
-1
@@ -2,5 +2,8 @@
|
||||
"files.exclude": {
|
||||
"**/__pycache__": true,
|
||||
"**/package-lock.json": true
|
||||
}
|
||||
},
|
||||
"github-actions.workflows.pinned.workflows": [],
|
||||
"github-actions.workflows.pinned.workflows.ignore": true,
|
||||
"github-actions.workflows.pinned.workflows.ignoreContextAccess": true
|
||||
}
|
||||
Vendored
+61
-11
@@ -2,9 +2,9 @@
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "Run",
|
||||
"type": "shell",
|
||||
"command": "npm run dev",
|
||||
"label": "Backend",
|
||||
"type": "npm",
|
||||
"script": "backend:run",
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
@@ -16,23 +16,73 @@
|
||||
},
|
||||
"group": {
|
||||
"kind": "build"
|
||||
},
|
||||
"isBackground": true
|
||||
},
|
||||
{
|
||||
"label": "Frontend (Web)",
|
||||
"type": "npm",
|
||||
"script": "frontend:dev",
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"presentation": {
|
||||
"echo": true,
|
||||
"reveal": "always",
|
||||
"focus": false,
|
||||
"panel": "shared"
|
||||
},
|
||||
"group": {
|
||||
"kind": "build",
|
||||
},
|
||||
"isBackground": true
|
||||
},
|
||||
{
|
||||
"label": "Frontend (Electron)",
|
||||
"type": "npm",
|
||||
"script": "frontend:electron:dev",
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"presentation": {
|
||||
"echo": true,
|
||||
"reveal": "always",
|
||||
"focus": false,
|
||||
"panel": "shared"
|
||||
},
|
||||
"group": {
|
||||
"kind": "build"
|
||||
},
|
||||
"isBackground": true
|
||||
},
|
||||
|
||||
{
|
||||
"label": "Web",
|
||||
"dependsOn": ["Backend", "Frontend (Web)"],
|
||||
"dependsOrder": "parallel",
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
},
|
||||
"presentation": {
|
||||
"echo": true,
|
||||
"reveal": "always",
|
||||
"focus": false,
|
||||
"panel": "shared"
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "Run (Electron)",
|
||||
"type": "shell",
|
||||
"command": "npm run dev:electron",
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
"label": "Electron",
|
||||
"dependsOn": ["Backend", "Frontend (Electron)"],
|
||||
"dependsOrder": "parallel",
|
||||
"group": {
|
||||
"kind": "build"
|
||||
},
|
||||
"presentation": {
|
||||
"echo": true,
|
||||
"reveal": "always",
|
||||
"focus": false,
|
||||
"panel": "shared"
|
||||
},
|
||||
"group": {
|
||||
"kind": "build"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
+14
-2
@@ -1,7 +1,9 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from migration import run_auto_migration
|
||||
from db import engine
|
||||
|
||||
from routes import account, messaging, profile
|
||||
from routes import account, messaging, profile, push
|
||||
|
||||
# Инициализация FastAPI
|
||||
app = FastAPI(title="PixelChat")
|
||||
@@ -18,4 +20,14 @@ app.add_middleware(
|
||||
# Routes
|
||||
app.include_router(account.router)
|
||||
app.include_router(messaging.router)
|
||||
app.include_router(profile.router)
|
||||
app.include_router(profile.router)
|
||||
app.include_router(push.router, prefix="/push")
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def _auto_migrate_on_startup():
|
||||
try:
|
||||
run_auto_migration(engine)
|
||||
except Exception:
|
||||
# Keep startup resilient; errors should be visible in server logs
|
||||
pass
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Generate VAPID keys for push notifications
|
||||
Run this script to generate new VAPID keys for your application
|
||||
"""
|
||||
|
||||
import sys
|
||||
import base64
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
|
||||
def generate_vapid_keys():
|
||||
"""Generate VAPID keys for push notifications"""
|
||||
try:
|
||||
private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
|
||||
public_key = private_key.public_key()
|
||||
|
||||
# Convert to base64 for web push
|
||||
private_key_b64 = base64.urlsafe_b64encode(
|
||||
private_key.private_bytes(
|
||||
encoding=serialization.Encoding.DER,
|
||||
format=serialization.PrivateFormat.PKCS8,
|
||||
encryption_algorithm=serialization.NoEncryption()
|
||||
)
|
||||
).decode('utf-8').rstrip('=')
|
||||
|
||||
# Get the raw uncompressed public key point (65 bytes: 0x04 + 32 bytes x + 32 bytes y)
|
||||
public_numbers = public_key.public_numbers()
|
||||
x_bytes = public_numbers.x.to_bytes(32, 'big')
|
||||
y_bytes = public_numbers.y.to_bytes(32, 'big')
|
||||
public_key_raw = b'\x04' + x_bytes + y_bytes
|
||||
|
||||
public_key_b64 = base64.urlsafe_b64encode(public_key_raw).decode('utf-8').rstrip('=')
|
||||
|
||||
print(f"VAPID_PRIVATE_KEY=\"{private_key_b64}\"")
|
||||
print(f"VAPID_PUBLIC_KEY=\"{public_key_b64}\"")
|
||||
|
||||
return private_key_b64, public_key_b64
|
||||
except Exception as e:
|
||||
print(f"Error generating VAPID keys: {e}", file=sys.stderr)
|
||||
return None, None
|
||||
|
||||
if __name__ == "__main__":
|
||||
generate_vapid_keys()
|
||||
@@ -0,0 +1,92 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from traceback import format_exc
|
||||
import hashlib
|
||||
|
||||
from sqlalchemy.engine import Engine
|
||||
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
from models import Base
|
||||
from constants import DATABASE_URL
|
||||
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parent / "migrations"
|
||||
LOCK_FILE = MIGRATIONS_DIR / ".autogen.lock"
|
||||
SCHEMA_HASH_FILE = MIGRATIONS_DIR / ".schema.hash"
|
||||
|
||||
|
||||
def _ensure_alembic_layout() -> None:
|
||||
"""Create a minimal Alembic environment if missing."""
|
||||
versions = MIGRATIONS_DIR / "versions"
|
||||
versions.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def _alembic_config() -> Config:
|
||||
cfg = Config()
|
||||
cfg.set_main_option("script_location", str(MIGRATIONS_DIR))
|
||||
cfg.set_main_option("sqlalchemy.url", DATABASE_URL)
|
||||
# Provide a minimal ini section so env.py can read config_ini_section
|
||||
cfg.config_file_name = "alembic.ini"
|
||||
cfg.set_section_option("alembic", "sqlalchemy.url", DATABASE_URL)
|
||||
return cfg
|
||||
|
||||
|
||||
def _model_schema_fingerprint() -> str:
|
||||
"""Compute a deterministic fingerprint of the current SQLAlchemy model schema."""
|
||||
parts: list[str] = []
|
||||
md = Base.metadata
|
||||
for table in sorted(md.tables.values(), key=lambda t: t.name):
|
||||
parts.append(f"T:{table.name}")
|
||||
for col in sorted(table.columns, key=lambda c: c.name):
|
||||
col_type = str(col.type)
|
||||
parts.append(f"C:{col.name}:{col_type}:N{int(bool(col.nullable))}")
|
||||
digest = hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()
|
||||
return digest
|
||||
|
||||
|
||||
def run_auto_migration(engine: Engine) -> None:
|
||||
"""Use Alembic to autogenerate and apply migrations automatically on startup."""
|
||||
# Ensure env present
|
||||
_ensure_alembic_layout()
|
||||
cfg = _alembic_config()
|
||||
|
||||
try:
|
||||
# Upgrade existing migrations (if any) first
|
||||
command.upgrade(cfg, "head")
|
||||
except Exception:
|
||||
print("[alembic] upgrade to head failed:\n" + format_exc())
|
||||
|
||||
# Always attempt autogenerate only when model schema fingerprint changed
|
||||
try:
|
||||
# Avoid concurrent autogenerate on dev server reloads
|
||||
try:
|
||||
LOCK_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd = os.open(str(LOCK_FILE), os.O_CREAT | os.O_EXCL | os.O_RDWR)
|
||||
os.close(fd)
|
||||
have_lock = True
|
||||
except FileExistsError:
|
||||
have_lock = False
|
||||
|
||||
if have_lock:
|
||||
try:
|
||||
new_hash = _model_schema_fingerprint()
|
||||
old_hash = SCHEMA_HASH_FILE.read_text(encoding="utf-8").strip() if SCHEMA_HASH_FILE.exists() else ""
|
||||
if new_hash != old_hash:
|
||||
command.revision(cfg, message="auto", autogenerate=True)
|
||||
command.upgrade(cfg, "head")
|
||||
# Update stored fingerprint
|
||||
SCHEMA_HASH_FILE.write_text(new_hash, encoding="utf-8")
|
||||
finally:
|
||||
try:
|
||||
LOCK_FILE.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
print("[alembic] autogenerate failed:\n" + format_exc())
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
from __future__ import annotations
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
from alembic import context
|
||||
from models import Base
|
||||
|
||||
config = context.config
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def _skip_empty_autogenerate(ctx, rev, directives):
|
||||
# Avoid creating empty migrations when there are no schema changes
|
||||
if getattr(config, "cmd_opts", None) and getattr(config.cmd_opts, "autogenerate", False):
|
||||
if directives:
|
||||
script = directives[0]
|
||||
if hasattr(script, "upgrade_ops") and script.upgrade_ops.is_empty():
|
||||
directives[:] = []
|
||||
|
||||
def run_migrations_offline():
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"},
|
||||
render_as_batch=True,
|
||||
process_revision_directives=_skip_empty_autogenerate
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
def run_migrations_online():
|
||||
connectable = engine_from_config(config.get_section(config.config_ini_section) or {}, prefix="sqlalchemy.", poolclass=pool.NullPool)
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
render_as_batch=True,
|
||||
process_revision_directives=_skip_empty_autogenerate
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,23 @@
|
||||
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '${up_revision}'
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
+76
-6
@@ -1,5 +1,5 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey, inspect, text
|
||||
from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey, inspect, null, text
|
||||
from sqlalchemy.orm import relationship
|
||||
from datetime import datetime
|
||||
from db import engine
|
||||
@@ -36,6 +36,75 @@ class Message(Base):
|
||||
|
||||
author = relationship("User", back_populates="messages")
|
||||
reply_to = relationship("Message", remote_side=[id])
|
||||
files = relationship("MessageFile", back_populates="message", cascade="all, delete-orphan", lazy="select")
|
||||
|
||||
|
||||
class MessageFile(Base):
|
||||
__tablename__ = "message_file"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
message_id = Column(Integer, ForeignKey("message.id"), nullable=False, index=True)
|
||||
path = Column(Text, nullable=False)
|
||||
name = Column(Text, nullable=False)
|
||||
|
||||
message = relationship("Message", back_populates="files")
|
||||
|
||||
|
||||
class CryptoPublicKey(Base):
|
||||
__tablename__ = "crypto_public_key"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("user.id"), nullable=False, unique=True)
|
||||
public_key_b64 = Column(Text, nullable=False)
|
||||
|
||||
|
||||
class CryptoBackup(Base):
|
||||
__tablename__ = "crypto_backup"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("user.id"), nullable=False, unique=True)
|
||||
blob_json = Column(Text, nullable=False)
|
||||
|
||||
|
||||
class DMEnvelope(Base):
|
||||
__tablename__ = "dm_envelope"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
sender_id = Column(Integer, ForeignKey("user.id"), nullable=False)
|
||||
recipient_id = Column(Integer, ForeignKey("user.id"), nullable=False)
|
||||
iv_b64 = Column(Text, nullable=False)
|
||||
ciphertext_b64 = Column(Text, nullable=False)
|
||||
salt_b64 = Column(Text, nullable=False)
|
||||
iv2_b64 = Column(Text, nullable=False)
|
||||
wrapped_mk_b64 = Column(Text, nullable=False)
|
||||
reply_to_id = Column(Integer, nullable=True)
|
||||
timestamp = Column(DateTime, default=datetime.now)
|
||||
files = relationship("DMFile", back_populates="message", cascade="all, delete-orphan", lazy="select")
|
||||
|
||||
|
||||
class DMFile(Base):
|
||||
__tablename__ = "dm_file"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
message_id = Column(Integer, ForeignKey("dm_envelope.id"), nullable=False, index=True)
|
||||
sender_id = Column(Integer, ForeignKey("user.id"), nullable=False)
|
||||
recipient_id = Column(Integer, ForeignKey("user.id"), nullable=False)
|
||||
name = Column(Text, nullable=False)
|
||||
path = Column(Text, nullable=False)
|
||||
|
||||
message = relationship("DMEnvelope", back_populates="files")
|
||||
|
||||
|
||||
class PushSubscription(Base):
|
||||
__tablename__ = "push_subscription"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("user.id"), nullable=False)
|
||||
endpoint = Column(Text, nullable=False)
|
||||
p256dh_key = Column(Text, nullable=False)
|
||||
auth_key = Column(Text, nullable=False)
|
||||
created_at = Column(DateTime, default=datetime.now)
|
||||
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
||||
|
||||
|
||||
# Pydantic модели
|
||||
@@ -52,17 +121,13 @@ class RegisterRequest(BaseModel):
|
||||
|
||||
class SendMessageRequest(BaseModel):
|
||||
content: str
|
||||
reply_to_id: int | None
|
||||
|
||||
|
||||
class EditMessageRequest(BaseModel):
|
||||
content: str
|
||||
|
||||
|
||||
class ReplyMessageRequest(BaseModel):
|
||||
content: str
|
||||
reply_to_id: int
|
||||
|
||||
|
||||
class DeleteMessageRequest(BaseModel):
|
||||
message_id: int
|
||||
|
||||
@@ -71,6 +136,11 @@ class UpdateBioRequest(BaseModel):
|
||||
bio: str
|
||||
|
||||
|
||||
class PushSubscriptionRequest(BaseModel):
|
||||
endpoint: str
|
||||
keys: dict
|
||||
|
||||
|
||||
class UserProfileResponse(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from pywebpush import webpush, WebPushException
|
||||
from models import PushSubscription, User, Message, DMEnvelope
|
||||
|
||||
logger = logging.getLogger("uvicorn.error")
|
||||
|
||||
class PushNotificationService:
|
||||
def __init__(self):
|
||||
self.vapid_private_key = os.getenv("VAPID_PRIVATE_KEY")
|
||||
self.vapid_public_key = os.getenv("VAPID_PUBLIC_KEY")
|
||||
|
||||
if (not self.vapid_public_key) or (not self.vapid_private_key):
|
||||
raise ValueError("VAPID public or private key is None")
|
||||
|
||||
self.vapid_claims = {
|
||||
"sub": "mailto:support@fromchat.ru",
|
||||
"aud": "https://fcm.googleapis.com"
|
||||
}
|
||||
|
||||
async def subscribe_user(self, db: Session, user_id: int, endpoint: str, p256dh_key: str, auth_key: str) -> bool:
|
||||
"""Subscribe a user to push notifications"""
|
||||
try:
|
||||
# Check if user already has a subscription
|
||||
existing_sub = db.query(PushSubscription).filter(PushSubscription.user_id == user_id).first()
|
||||
|
||||
if existing_sub:
|
||||
# Update existing subscription
|
||||
existing_sub.endpoint = endpoint
|
||||
existing_sub.p256dh_key = p256dh_key
|
||||
existing_sub.auth_key = auth_key
|
||||
else:
|
||||
# Create new subscription
|
||||
new_sub = PushSubscription(
|
||||
user_id=user_id,
|
||||
endpoint=endpoint,
|
||||
p256dh_key=p256dh_key,
|
||||
auth_key=auth_key
|
||||
)
|
||||
db.add(new_sub)
|
||||
|
||||
db.commit()
|
||||
logger.info(f"Push subscription saved for user {user_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save push subscription for user {user_id}: {e}")
|
||||
db.rollback()
|
||||
return False
|
||||
|
||||
async def send_public_message_notification(self, db: Session, message: Message, exclude_user_id: Optional[int] = None):
|
||||
"""Send push notification for a new public chat message"""
|
||||
try:
|
||||
# Get all users except the sender
|
||||
users = db.query(User).filter(User.id != message.user_id)
|
||||
if exclude_user_id:
|
||||
users = users.filter(User.id != exclude_user_id)
|
||||
|
||||
for user in users:
|
||||
# Check if user has push subscription before trying to send
|
||||
subscription = db.query(PushSubscription).filter(PushSubscription.user_id == user.id).first()
|
||||
if not subscription:
|
||||
continue
|
||||
|
||||
await self._send_notification_to_user(
|
||||
db, user.id,
|
||||
f"New message from {message.author.username}",
|
||||
message.content[:100] + ("..." if len(message.content) > 100 else ""),
|
||||
message.author.profile_picture,
|
||||
{
|
||||
"type": "public_message",
|
||||
"message_id": message.id,
|
||||
"sender_id": message.user_id,
|
||||
"sender_username": message.author.username
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send public message notifications: {e}")
|
||||
|
||||
async def send_dm_notification(self, db: Session, dm_envelope: DMEnvelope, sender: User):
|
||||
"""Send push notification for a new DM"""
|
||||
try:
|
||||
await self._send_notification_to_user(
|
||||
db, dm_envelope.recipient_id,
|
||||
f"New message from {sender.username}",
|
||||
"You have a new direct message",
|
||||
sender.profile_picture,
|
||||
{
|
||||
"type": "dm",
|
||||
"dm_id": dm_envelope.id,
|
||||
"sender_id": sender.id,
|
||||
"sender_username": sender.username
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send DM notification: {e}")
|
||||
|
||||
async def _send_notification_to_user(self, db: Session, user_id: int, title: str, body: str, icon: Optional[str], data: dict):
|
||||
"""Send a push notification to a specific user"""
|
||||
try:
|
||||
subscription = db.query(PushSubscription).filter(PushSubscription.user_id == user_id).first()
|
||||
if not subscription:
|
||||
return
|
||||
|
||||
payload = {
|
||||
"title": title,
|
||||
"body": body,
|
||||
"icon": icon or "/logo.png",
|
||||
"tag": f"message_{user_id}",
|
||||
"data": data
|
||||
}
|
||||
|
||||
subscription_info = {
|
||||
"endpoint": subscription.endpoint,
|
||||
"keys": {
|
||||
"p256dh": subscription.p256dh_key,
|
||||
"auth": subscription.auth_key
|
||||
}
|
||||
}
|
||||
|
||||
webpush(
|
||||
subscription_info=subscription_info,
|
||||
data=json.dumps(payload),
|
||||
vapid_private_key=self.vapid_private_key,
|
||||
vapid_claims=self.vapid_claims
|
||||
)
|
||||
|
||||
except WebPushException as e:
|
||||
logger.error(f"WebPush error for user {user_id}: {e}")
|
||||
# If the subscription is invalid, remove it
|
||||
if hasattr(e, 'response') and e.response and e.response.status_code in [410, 404]:
|
||||
db.query(PushSubscription).filter(PushSubscription.user_id == user_id).delete()
|
||||
db.commit()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send push notification to user {user_id}: {e}")
|
||||
|
||||
async def unsubscribe_user(self, db: Session, user_id: int) -> bool:
|
||||
"""Unsubscribe a user from push notifications"""
|
||||
try:
|
||||
db.query(PushSubscription).filter(PushSubscription.user_id == user_id).delete()
|
||||
db.commit()
|
||||
logger.info(f"Push subscription removed for user {user_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to remove push subscription for user {user_id}: {e}")
|
||||
db.rollback()
|
||||
return False
|
||||
|
||||
# Global instance
|
||||
push_service = PushNotificationService()
|
||||
@@ -5,4 +5,8 @@ sqlalchemy>=2.0.43
|
||||
bcrypt>=4.3.0
|
||||
websockets>=15.0.1
|
||||
Pillow>=10.0.0
|
||||
python-multipart>=0.0.6
|
||||
python-multipart>=0.0.6
|
||||
pywebpush>=1.14.0
|
||||
cryptography>=41.0.0
|
||||
alembic>=1.13.2
|
||||
better-profanity>=0.7.0
|
||||
@@ -2,10 +2,9 @@ from datetime import datetime
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from routes.messaging import convert_message
|
||||
from constants import OWNER_USERNAME
|
||||
from dependencies import get_current_user, get_db
|
||||
from models import LoginRequest, RegisterRequest, User
|
||||
from models import LoginRequest, RegisterRequest, User, CryptoPublicKey, CryptoBackup
|
||||
from utils import create_token, get_password_hash, verify_password
|
||||
from validation import is_valid_password, is_valid_username
|
||||
|
||||
@@ -18,6 +17,8 @@ def convert_user(user: User) -> dict:
|
||||
"last_seen": user.last_seen.isoformat(),
|
||||
"online": user.online,
|
||||
"username": user.username,
|
||||
"profile_picture": user.profile_picture,
|
||||
"bio": user.bio,
|
||||
"admin": user.username == OWNER_USERNAME
|
||||
}
|
||||
|
||||
@@ -120,6 +121,47 @@ def register(request: RegisterRequest, db: Session = Depends(get_db)):
|
||||
"message": "Регистрация прошла успешно Теперь вы можете войти."
|
||||
}
|
||||
|
||||
@router.get("/crypto/public-key")
|
||||
def get_public_key(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
row = db.query(CryptoPublicKey).filter(CryptoPublicKey.user_id == current_user.id).first()
|
||||
return {"publicKey": row.public_key_b64 if row else None}
|
||||
|
||||
|
||||
@router.post("/crypto/public-key")
|
||||
def set_public_key(payload: dict, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
pk = payload.get("publicKey")
|
||||
if not pk:
|
||||
raise HTTPException(status_code=400, detail="publicKey required")
|
||||
row = db.query(CryptoPublicKey).filter(CryptoPublicKey.user_id == current_user.id).first()
|
||||
if row:
|
||||
row.public_key_b64 = pk
|
||||
else:
|
||||
row = CryptoPublicKey(user_id=current_user.id, public_key_b64=pk)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/crypto/backup")
|
||||
def get_backup(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
row = db.query(CryptoBackup).filter(CryptoBackup.user_id == current_user.id).first()
|
||||
return {"blob": row.blob_json if row else None}
|
||||
|
||||
|
||||
@router.post("/crypto/backup")
|
||||
def set_backup(payload: dict, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
blob = payload.get("blob")
|
||||
if not blob:
|
||||
raise HTTPException(status_code=400, detail="blob required")
|
||||
row = db.query(CryptoBackup).filter(CryptoBackup.user_id == current_user.id).first()
|
||||
if row:
|
||||
row.blob_json = blob
|
||||
else:
|
||||
row = CryptoBackup(user_id=current_user.id, blob_json=blob)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.delete("/admin/user/{user_id}")
|
||||
def delete_user_as_owner(
|
||||
@@ -160,4 +202,20 @@ def logout(
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Logged out successfully"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
def list_users(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
users = db.query(User).order_by(User.username.asc()).all()
|
||||
return {
|
||||
"users": [
|
||||
convert_user(u) for u in users if u.id != current_user.id
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.get("/crypto/public-key/of/{user_id}")
|
||||
def get_public_key_of(user_id: int, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
row = db.query(CryptoPublicKey).filter(CryptoPublicKey.user_id == user_id).first()
|
||||
return {"publicKey": row.public_key_b64 if row else None}
|
||||
+520
-54
@@ -1,15 +1,35 @@
|
||||
from datetime import datetime
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, UploadFile, File, Form
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
from dependencies import get_current_user, get_db
|
||||
from constants import OWNER_USERNAME
|
||||
from models import Message, SendMessageRequest, EditMessageRequest, ReplyMessageRequest, User
|
||||
from models import Message, SendMessageRequest, EditMessageRequest, User, DMEnvelope, MessageFile, DMFile
|
||||
from push_service import push_service
|
||||
from PIL import Image
|
||||
import io
|
||||
import json
|
||||
from better_profanity import profanity as _bp
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger("uvicorn.error")
|
||||
|
||||
MAX_TOTAL_SIZE = 4 * 1024 * 1024 * 1024 # 4 GB
|
||||
|
||||
FILES_BASE_DIR = Path("data/uploads/files")
|
||||
FILES_NORMAL_DIR = FILES_BASE_DIR / "normal"
|
||||
FILES_ENCRYPTED_DIR = FILES_BASE_DIR / "encrypted"
|
||||
|
||||
os.makedirs(FILES_NORMAL_DIR, exist_ok=True)
|
||||
os.makedirs(FILES_ENCRYPTED_DIR, exist_ok=True)
|
||||
|
||||
|
||||
def convert_message(msg: Message) -> dict:
|
||||
return {
|
||||
"id": msg.id,
|
||||
@@ -19,31 +39,103 @@ def convert_message(msg: Message) -> dict:
|
||||
"is_edited": msg.is_edited,
|
||||
"username": msg.author.username,
|
||||
"profile_picture": msg.author.profile_picture,
|
||||
"reply_to": convert_message(msg.reply_to) if msg.reply_to else None
|
||||
"reply_to": convert_message(msg.reply_to) if msg.reply_to else None,
|
||||
"files": [
|
||||
{
|
||||
"path": f"/api/uploads/files/normal/{Path(f.path).name}",
|
||||
"id": f.id,
|
||||
"name": f.name,
|
||||
"message_id": f.message_id
|
||||
}
|
||||
for f in (msg.files or [])
|
||||
]
|
||||
}
|
||||
|
||||
# для тех кто читает этот код я эти маты не писал
|
||||
# мат писал ии а я сам не матерюсь))
|
||||
# - denis0001-dev
|
||||
_RU_EXTRA = [
|
||||
"бляд", "блять", "бля", "сука", "суки", "сучка", "мразь", "ебан",
|
||||
"ебать", "ебёт", "ебет", "уёбок", "уебок", "уебище", "пизда",
|
||||
"пиздец", "пизд", "хуй", "хуя", "хуе", "хуё", "хер", "гондон",
|
||||
"долбоёб", "долбоеб", "дебил"
|
||||
]
|
||||
|
||||
_bp.load_censor_words()
|
||||
_bp.add_censor_words(_RU_EXTRA)
|
||||
|
||||
# Additional phrase-level filters (case-insensitive)
|
||||
_PHRASE_PATTERNS: list[re.Pattern] = [
|
||||
re.compile(r"\bmax\s+is\s+better\b", re.IGNORECASE | re.UNICODE),
|
||||
re.compile(r"\bмакс\s+лучше\b", re.IGNORECASE | re.UNICODE),
|
||||
re.compile(r"\bfromchat\s+г[ао]вно\b", re.IGNORECASE | re.UNICODE),
|
||||
re.compile(r"\bфромчат\s+г[ао]вно\b", re.IGNORECASE | re.UNICODE),
|
||||
]
|
||||
|
||||
def _mask_span(text: str, start: int, end: int) -> str:
|
||||
return text[:start] + ("\\*" * (end - start)) + text[end:]
|
||||
|
||||
def _apply_phrase_filters(text: str) -> str:
|
||||
result = text
|
||||
for pattern in _PHRASE_PATTERNS:
|
||||
# Replace all occurrences; iterate until no more matches to avoid overlapping issues
|
||||
while True:
|
||||
m = pattern.search(result)
|
||||
if not m:
|
||||
break
|
||||
result = _mask_span(result, m.start(), m.end())
|
||||
return result
|
||||
|
||||
def filter_profanity(text: str) -> str:
|
||||
preprocessed = _apply_phrase_filters(text)
|
||||
return _bp.censor(preprocessed, censor_char="\\*")
|
||||
|
||||
|
||||
@router.post("/send_message")
|
||||
async def send_message(
|
||||
request: SendMessageRequest,
|
||||
request: SendMessageRequest | None = None,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
db: Session = Depends(get_db),
|
||||
# Optional multipart form support
|
||||
payload: str | None = Form(default=None),
|
||||
files: list[UploadFile] = File(default=[]),
|
||||
):
|
||||
# If payload is provided, prefer it for multipart requests
|
||||
if payload and request is None:
|
||||
# Expect JSON: {"type":"text","data":{"content": str}, "reply_to_id": number|null}
|
||||
try:
|
||||
obj = json.loads(payload)
|
||||
content = obj.get("content", "")
|
||||
reply_to_id = obj.get("reply_to_id", None)
|
||||
request = SendMessageRequest(content=content, reply_to_id=reply_to_id)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid payload JSON")
|
||||
|
||||
if request.reply_to_id:
|
||||
# Check if the message being replied to exists
|
||||
original_message = db.query(Message).filter(Message.id == request.reply_to_id).first()
|
||||
if not original_message:
|
||||
raise HTTPException(status_code=404, detail="Original message not found")
|
||||
|
||||
if not request.content.strip():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="No content provided"
|
||||
)
|
||||
|
||||
if len(request.content.strip()) > 4096:
|
||||
# Apply profanity filter before storing
|
||||
filtered_content = filter_profanity(request.content.strip())
|
||||
|
||||
if len(filtered_content) > 4096:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Message too long"
|
||||
)
|
||||
|
||||
new_message = Message(
|
||||
content=request.content.strip(),
|
||||
content=filtered_content,
|
||||
user_id=current_user.id,
|
||||
reply_to_id=request.reply_to_id,
|
||||
timestamp=datetime.now()
|
||||
)
|
||||
|
||||
@@ -51,6 +143,77 @@ async def send_message(
|
||||
db.commit()
|
||||
db.refresh(new_message)
|
||||
|
||||
# Handle files if provided (normal, not encrypted)
|
||||
if files:
|
||||
total_size = 0
|
||||
for up in files:
|
||||
# Accumulate size if available
|
||||
if hasattr(up, "size") and up.size is not None:
|
||||
total_size += int(up.size)
|
||||
else:
|
||||
# If size unknown, read into memory to determine
|
||||
data = await up.read()
|
||||
up.file.seek(0)
|
||||
total_size += len(data)
|
||||
if total_size > MAX_TOTAL_SIZE:
|
||||
raise HTTPException(status_code=400, detail="Total attachments size exceeds 4GB")
|
||||
|
||||
for up in files:
|
||||
# Sanitize filename
|
||||
original_name = Path(up.filename or "file").name
|
||||
ext = Path(original_name).suffix.lower()
|
||||
uid = uuid.uuid4().hex
|
||||
safe_name = f"{new_message.id}_{uid}{ext or ''}"
|
||||
out_path = FILES_NORMAL_DIR / safe_name
|
||||
|
||||
content = await up.read()
|
||||
up.file.seek(0)
|
||||
|
||||
# If image, try lossless optimization
|
||||
try:
|
||||
if up.content_type and up.content_type.startswith("image/"):
|
||||
image = Image.open(io.BytesIO(content))
|
||||
img_format = image.format or ("PNG" if ext == ".png" else "JPEG")
|
||||
buf = io.BytesIO()
|
||||
save_kwargs = {"optimize": True}
|
||||
if img_format.upper() == "JPEG":
|
||||
# Use quality=95 with optimize to keep high quality (not truly lossless but near)
|
||||
save_kwargs["quality"] = 95
|
||||
image.save(buf, format=img_format, **save_kwargs)
|
||||
buf.seek(0)
|
||||
content = buf.read()
|
||||
except Exception:
|
||||
# Fallback to original content
|
||||
pass
|
||||
|
||||
with open(out_path, "wb") as f:
|
||||
f.write(content)
|
||||
|
||||
mf = MessageFile(
|
||||
message_id=new_message.id,
|
||||
name=original_name,
|
||||
path=str(out_path)
|
||||
)
|
||||
db.add(mf)
|
||||
db.commit()
|
||||
db.refresh(new_message)
|
||||
|
||||
# Send push notifications for public messages
|
||||
try:
|
||||
await push_service.send_public_message_notification(db, new_message, exclude_user_id=current_user.id)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send push notification for message {new_message.id}: {e}")
|
||||
|
||||
# Realtime broadcast for HTTP uploads as well
|
||||
try:
|
||||
from .messaging import messagingManager # self import safe here
|
||||
await messagingManager.broadcast({
|
||||
"type": "newMessage",
|
||||
"data": convert_message(new_message)
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {"status": "success", "message": convert_message(new_message)}
|
||||
|
||||
|
||||
@@ -68,6 +231,164 @@ async def get_messages(db: Session = Depends(get_db)):
|
||||
}
|
||||
|
||||
|
||||
@router.post("/dm/send")
|
||||
async def dm_send(
|
||||
payload: dict | None = None,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
# Multipart support
|
||||
dm_payload: str | None = Form(default=None),
|
||||
files: list[UploadFile] = File(default=[]),
|
||||
fileNames: str | None = Form(default=None), # JSON array of filenames corresponding to files
|
||||
):
|
||||
if dm_payload and payload is None:
|
||||
try:
|
||||
payload = json.loads(dm_payload)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid dm_payload JSON")
|
||||
|
||||
if payload is None:
|
||||
raise HTTPException(status_code=400, detail="Missing payload")
|
||||
|
||||
required = ["recipientId", "iv", "ciphertext", "salt", "iv2", "wrappedMk"]
|
||||
for key in required:
|
||||
if key not in payload:
|
||||
raise HTTPException(status_code=400, detail=f"Missing {key}")
|
||||
|
||||
env = DMEnvelope(
|
||||
sender_id=current_user.id,
|
||||
recipient_id=int(payload["recipientId"]),
|
||||
iv_b64=payload["iv"],
|
||||
ciphertext_b64=payload["ciphertext"],
|
||||
salt_b64=payload["salt"],
|
||||
iv2_b64=payload["iv2"],
|
||||
wrapped_mk_b64=payload["wrappedMk"],
|
||||
reply_to_id=payload.get("replyToId") if isinstance(payload.get("replyToId"), int) else None,
|
||||
)
|
||||
db.add(env)
|
||||
db.commit()
|
||||
db.refresh(env)
|
||||
|
||||
# Save encrypted files if any (no processing)
|
||||
if files:
|
||||
# Validate total size
|
||||
total_size = 0
|
||||
for file in files:
|
||||
if hasattr(file, "size") and file.size is not None:
|
||||
total_size += int(file.size)
|
||||
else:
|
||||
data = await file.read()
|
||||
file.file.seek(0)
|
||||
total_size += len(data)
|
||||
if total_size > MAX_TOTAL_SIZE:
|
||||
raise HTTPException(status_code=400, detail="Total attachments size exceeds 4GB")
|
||||
|
||||
names: list[str] = []
|
||||
if fileNames:
|
||||
try:
|
||||
decoded = json.loads(fileNames)
|
||||
if isinstance(decoded, list):
|
||||
names = [str(x) for x in decoded]
|
||||
except Exception:
|
||||
names = []
|
||||
|
||||
for i, file in enumerate(files):
|
||||
provided = names[i] if i < len(names) else None
|
||||
# Sanitize provided name to avoid path traversal
|
||||
if provided and not re.match(r"^[A-Za-z0-9._-]{1,200}$", provided):
|
||||
provided = None
|
||||
original_name = provided or Path(file.filename or "file").name
|
||||
# Save using provided/original name to allow client to reference path directly
|
||||
safe_name = uid = uuid.uuid4().hex
|
||||
out_name = f"{current_user.id}_{env.recipient_id}_{env.id}_{safe_name}"
|
||||
out_path = FILES_ENCRYPTED_DIR / out_name
|
||||
|
||||
content = await file.read()
|
||||
with open(out_path, "wb") as f:
|
||||
f.write(content)
|
||||
|
||||
# Save DM file record
|
||||
df = DMFile(
|
||||
message_id=env.id,
|
||||
sender_id=current_user.id,
|
||||
recipient_id=env.recipient_id,
|
||||
path=f"/api/uploads/files/encrypted/{out_name}",
|
||||
name=original_name
|
||||
)
|
||||
db.add(df)
|
||||
db.commit()
|
||||
|
||||
# Send push notification for DM
|
||||
try:
|
||||
await push_service.send_dm_notification(db, env, current_user)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send push notification for DM {env.id}: {e}")
|
||||
|
||||
# Realtime notify both users for HTTP requests
|
||||
try:
|
||||
payload_ws = {
|
||||
"type": "dmNew",
|
||||
"data": {
|
||||
"id": env.id,
|
||||
"senderId": env.sender_id,
|
||||
"recipientId": env.recipient_id,
|
||||
"iv": env.iv_b64,
|
||||
"ciphertext": env.ciphertext_b64,
|
||||
"salt": env.salt_b64,
|
||||
"iv2": env.iv2_b64,
|
||||
"wrappedMk": env.wrapped_mk_b64,
|
||||
"timestamp": env.timestamp.isoformat(),
|
||||
"replyToId": env.reply_to_id,
|
||||
}
|
||||
}
|
||||
await messagingManager.send_to_user(env.recipient_id, payload_ws)
|
||||
await messagingManager.send_to_user(env.sender_id, payload_ws)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {"status": "ok", "id": env.id}
|
||||
|
||||
def convert_envelopes(envs: list[DMEnvelope]):
|
||||
return {
|
||||
"status": "ok",
|
||||
"messages": [
|
||||
{
|
||||
"id": e.id,
|
||||
"senderId": e.sender_id,
|
||||
"recipientId": e.recipient_id,
|
||||
"iv": e.iv_b64,
|
||||
"ciphertext": e.ciphertext_b64,
|
||||
"salt": e.salt_b64,
|
||||
"iv2": e.iv2_b64,
|
||||
"wrappedMk": e.wrapped_mk_b64,
|
||||
"timestamp": e.timestamp.isoformat(),
|
||||
"files": [{"name": file.name, "path": file.path, "id": file.id} for file in e.files]
|
||||
}
|
||||
for e in envs
|
||||
]
|
||||
}
|
||||
|
||||
@router.get("/dm/fetch")
|
||||
async def dm_fetch(since: int | None = None, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
q = db.query(DMEnvelope).filter(DMEnvelope.recipient_id == current_user.id)
|
||||
if since:
|
||||
q = q.filter(DMEnvelope.id > since)
|
||||
return convert_envelopes(q.order_by(DMEnvelope.id.asc()).all())
|
||||
|
||||
|
||||
@router.get("/dm/history/{other_user_id}")
|
||||
async def dm_history(other_user_id: int, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
return convert_envelopes(
|
||||
db.query(DMEnvelope)
|
||||
.filter(
|
||||
((DMEnvelope.sender_id == current_user.id) & (DMEnvelope.recipient_id == other_user_id))
|
||||
| ((DMEnvelope.sender_id == other_user_id) & (DMEnvelope.recipient_id == current_user.id))
|
||||
)
|
||||
.order_by(DMEnvelope.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
@router.put("/edit_message/{message_id}")
|
||||
async def edit_message(
|
||||
message_id: int,
|
||||
@@ -115,38 +436,10 @@ async def delete_message(
|
||||
|
||||
return {"status": "success", "message_id": message_id}
|
||||
|
||||
|
||||
@router.post("/reply_message")
|
||||
async def reply_message(
|
||||
request: ReplyMessageRequest,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
# Check if the message being replied to exists
|
||||
original_message = db.query(Message).filter(Message.id == request.reply_to_id).first()
|
||||
if not original_message:
|
||||
raise HTTPException(status_code=404, detail="Original message not found")
|
||||
|
||||
if not request.content.strip():
|
||||
raise HTTPException(status_code=400, detail="No content provided")
|
||||
|
||||
new_message = Message(
|
||||
content=request.content.strip(),
|
||||
user_id=current_user.id,
|
||||
timestamp=datetime.now(),
|
||||
reply_to_id=request.reply_to_id
|
||||
)
|
||||
|
||||
db.add(new_message)
|
||||
db.commit()
|
||||
db.refresh(new_message)
|
||||
|
||||
return {"status": "success", "message": convert_message(new_message)}
|
||||
|
||||
|
||||
class MessaggingSocketManager:
|
||||
def __init__(self) -> None:
|
||||
self.connections: list[WebSocket] = []
|
||||
self.user_by_ws: dict[WebSocket, int] = {}
|
||||
|
||||
async def send_error(self, websocket: WebSocket, type: str, e: HTTPException):
|
||||
await websocket.send_json({"type": type, "error": {"code": e.status_code, "detail": e.detail}})
|
||||
@@ -169,12 +462,39 @@ class MessaggingSocketManager:
|
||||
return None
|
||||
|
||||
if type == "ping":
|
||||
try:
|
||||
current_user = get_current_user_inner()
|
||||
if current_user:
|
||||
self.user_by_ws[websocket] = current_user.id
|
||||
else:
|
||||
await websocket.send_json({
|
||||
"type": "ping",
|
||||
"data": {
|
||||
"status": "error",
|
||||
"error": {
|
||||
"detail": "Failed to authorize",
|
||||
"code": 401
|
||||
}
|
||||
}
|
||||
})
|
||||
except HTTPException:
|
||||
await websocket.send_json({
|
||||
"type": "ping",
|
||||
"data": {
|
||||
"status": "error",
|
||||
"error": {
|
||||
"detail": "Failed to authorize",
|
||||
"code": 401
|
||||
}
|
||||
}
|
||||
})
|
||||
await websocket.send_json({"type": "ping", "data": {"status": "success"}})
|
||||
elif type == "getMessages":
|
||||
try:
|
||||
current_user = get_current_user_inner()
|
||||
if not current_user:
|
||||
raise HTTPException(401)
|
||||
self.user_by_ws[websocket] = current_user.id
|
||||
|
||||
await websocket.send_json({"type": type, "data": await get_messages(current_user, db)})
|
||||
except HTTPException as e:
|
||||
@@ -184,10 +504,11 @@ class MessaggingSocketManager:
|
||||
current_user = get_current_user_inner()
|
||||
if not current_user:
|
||||
raise HTTPException(401)
|
||||
self.user_by_ws[websocket] = current_user.id
|
||||
|
||||
request: SendMessageRequest = SendMessageRequest.model_validate(data["data"])
|
||||
|
||||
response = await send_message(request, current_user, db)
|
||||
response = await send_message(request, current_user, db, None, [])
|
||||
await self.broadcast({
|
||||
"type": "newMessage",
|
||||
"data": response["message"]
|
||||
@@ -196,6 +517,58 @@ class MessaggingSocketManager:
|
||||
await websocket.send_json({"type": type, "data": response})
|
||||
except HTTPException as e:
|
||||
await self.send_error(websocket, type, e)
|
||||
elif type == "dmSend":
|
||||
try:
|
||||
current_user = get_current_user_inner()
|
||||
if not current_user:
|
||||
raise HTTPException(401)
|
||||
self.user_by_ws[websocket] = current_user.id
|
||||
payload = data["data"]
|
||||
required = ["recipientId", "iv", "ciphertext", "salt", "iv2", "wrappedMk"]
|
||||
for key in required:
|
||||
if key not in payload:
|
||||
raise HTTPException(status_code=400, detail=f"Missing {key}")
|
||||
env = DMEnvelope(
|
||||
sender_id=current_user.id,
|
||||
recipient_id=int(payload["recipientId"]),
|
||||
iv_b64=payload["iv"],
|
||||
ciphertext_b64=payload["ciphertext"],
|
||||
salt_b64=payload["salt"],
|
||||
iv2_b64=payload["iv2"],
|
||||
wrapped_mk_b64=payload["wrappedMk"],
|
||||
reply_to_id=payload.get("replyToId") if isinstance(payload.get("replyToId"), int) else None,
|
||||
)
|
||||
db.add(env)
|
||||
db.commit()
|
||||
db.refresh(env)
|
||||
|
||||
payload = {
|
||||
"type": "dmNew",
|
||||
"data": {
|
||||
"id": env.id,
|
||||
"senderId": env.sender_id,
|
||||
"recipientId": env.recipient_id,
|
||||
"iv": env.iv_b64,
|
||||
"ciphertext": env.ciphertext_b64,
|
||||
"salt": env.salt_b64,
|
||||
"iv2": env.iv2_b64,
|
||||
"wrappedMk": env.wrapped_mk_b64,
|
||||
"timestamp": env.timestamp.isoformat(),
|
||||
"replyToId": env.reply_to_id,
|
||||
}
|
||||
}
|
||||
|
||||
# Send push notification for DM
|
||||
try:
|
||||
await push_service.send_dm_notification(db, env, current_user)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send push notification for DM {env.id}: {e}")
|
||||
|
||||
await self.send_to_user(env.recipient_id, payload);
|
||||
await websocket.send_json({"type": type, "data": {"status": "ok", "id": env.id}});
|
||||
await self.send_to_user(env.sender_id, payload);
|
||||
except HTTPException as e:
|
||||
await self.send_error(websocket, type, e)
|
||||
elif type == "editMessage":
|
||||
try:
|
||||
current_user = get_current_user_inner()
|
||||
@@ -214,6 +587,76 @@ class MessaggingSocketManager:
|
||||
await websocket.send_json({"type": type, "data": response})
|
||||
except HTTPException as e:
|
||||
await self.send_error(websocket, type, e)
|
||||
elif type == "dmEdit":
|
||||
try:
|
||||
current_user = get_current_user_inner()
|
||||
if not current_user:
|
||||
raise HTTPException(401)
|
||||
|
||||
payload = data["data"]
|
||||
env_id = int(payload["id"])
|
||||
env: DMEnvelope | None = db.query(DMEnvelope).filter(DMEnvelope.id == env_id).first()
|
||||
if not env:
|
||||
raise HTTPException(status_code=404, detail="DM not found")
|
||||
if env.sender_id != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="You can only edit your own messages")
|
||||
|
||||
# Replace ciphertext and iv
|
||||
env.iv_b64 = payload["iv"]
|
||||
env.ciphertext_b64 = payload["ciphertext"]
|
||||
env.iv2_b64 = payload["iv2"]
|
||||
env.wrapped_mk_b64 = payload["wrappedMk"]
|
||||
env.salt_b64 = payload["salt"]
|
||||
db.commit()
|
||||
db.refresh(env)
|
||||
|
||||
payload_ws = {
|
||||
"type": "dmEdited",
|
||||
"data": {
|
||||
"id": env.id,
|
||||
"iv": env.iv_b64,
|
||||
"ciphertext": env.ciphertext_b64,
|
||||
"iv2": env.iv2_b64,
|
||||
"wrappedMk": env.wrapped_mk_b64,
|
||||
"salt": env.salt_b64,
|
||||
"timestamp": env.timestamp.isoformat(),
|
||||
}
|
||||
}
|
||||
await self.send_to_user(env.recipient_id, payload_ws)
|
||||
await self.send_to_user(env.sender_id, payload_ws)
|
||||
await websocket.send_json({"type": type, "data": {"status": "ok", "id": env.id}})
|
||||
except HTTPException as e:
|
||||
await self.send_error(websocket, type, e)
|
||||
elif type == "dmDelete":
|
||||
try:
|
||||
current_user = get_current_user_inner()
|
||||
if not current_user:
|
||||
raise HTTPException(401)
|
||||
|
||||
payload = data["data"]
|
||||
env_id = int(payload["id"])
|
||||
env: DMEnvelope | None = db.query(DMEnvelope).filter(DMEnvelope.id == env_id).first()
|
||||
if not env:
|
||||
raise HTTPException(status_code=404, detail="DM not found")
|
||||
if env.sender_id != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="You can only delete your own messages")
|
||||
|
||||
db.delete(env)
|
||||
db.commit()
|
||||
|
||||
payload_ws = {
|
||||
"type": "dmDeleted",
|
||||
"data": {
|
||||
"id": env_id,
|
||||
"senderId": current_user.id,
|
||||
"recipientId": payload.get("recipientId")
|
||||
}
|
||||
}
|
||||
await self.send_to_user(env.recipient_id, payload_ws)
|
||||
await websocket.send_json({"type": type, "data": {"status": "ok", "id": env_id}})
|
||||
await self.send_to_user(env.sender_id, payload_ws)
|
||||
except HTTPException as e:
|
||||
await self.send_error(websocket, type, e)
|
||||
elif type == "deleteMessage":
|
||||
try:
|
||||
current_user = get_current_user_inner()
|
||||
@@ -227,22 +670,6 @@ class MessaggingSocketManager:
|
||||
"data": {"message_id": message_id}
|
||||
})
|
||||
|
||||
await websocket.send_json({"type": type, "data": response})
|
||||
except HTTPException as e:
|
||||
await self.send_error(websocket, type, e)
|
||||
elif type == "replyMessage":
|
||||
try:
|
||||
current_user = get_current_user_inner()
|
||||
if not current_user:
|
||||
raise HTTPException(401)
|
||||
|
||||
request: ReplyMessageRequest = ReplyMessageRequest.model_validate(data["data"])
|
||||
response = await reply_message(request, current_user, db)
|
||||
await self.broadcast({
|
||||
"type": "newMessage",
|
||||
"data": response["message"]
|
||||
})
|
||||
|
||||
await websocket.send_json({"type": type, "data": response})
|
||||
except HTTPException as e:
|
||||
await self.send_error(websocket, type, e)
|
||||
@@ -264,11 +691,18 @@ class MessaggingSocketManager:
|
||||
logger.info(f"WebSocket disconnected with code {e.code}: {e.reason}")
|
||||
finally:
|
||||
self.connections.remove(websocket)
|
||||
if websocket in self.user_by_ws:
|
||||
del self.user_by_ws[websocket]
|
||||
|
||||
async def broadcast(self, message: dict):
|
||||
for websocket in self.connections:
|
||||
await websocket.send_json(message)
|
||||
|
||||
async def send_to_user(self, user_id: int, message: dict):
|
||||
for websocket in self.connections:
|
||||
if self.user_by_ws.get(websocket) == user_id:
|
||||
await websocket.send_json(message)
|
||||
|
||||
messagingManager = MessaggingSocketManager()
|
||||
|
||||
@router.websocket("/chat/ws")
|
||||
@@ -276,4 +710,36 @@ async def chat_websocket(
|
||||
websocket: WebSocket,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
await messagingManager.connect(websocket, db)
|
||||
await messagingManager.connect(websocket, db)
|
||||
|
||||
|
||||
# File serving endpoints
|
||||
@router.get("/uploads/files/normal/{filename}")
|
||||
async def get_file_normal(filename: str):
|
||||
if not re.match(r"^[A-Za-z0-9._-]+$", filename):
|
||||
raise HTTPException(status_code=400, detail="Invalid file name")
|
||||
path = FILES_NORMAL_DIR / filename
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
return FileResponse(str(path))
|
||||
|
||||
|
||||
@router.get("/uploads/files/encrypted/{filename}")
|
||||
async def get_file_encrypted(filename: str, current_user: User = Depends(get_current_user)):
|
||||
if not re.match(r"^[A-Za-z0-9._-]+$", filename):
|
||||
raise HTTPException(status_code=400, detail="Invalid file name")
|
||||
path = FILES_ENCRYPTED_DIR / filename
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
|
||||
match = re.match(r"^(\d+)_(\d+)_(\d+)_.*$", path.resolve().name)
|
||||
if match:
|
||||
sender_id = int(match.group(1))
|
||||
recipient_id = int(match.group(2))
|
||||
|
||||
if not current_user.id in [sender_id, recipient_id]:
|
||||
raise HTTPException(403)
|
||||
else:
|
||||
raise HTTPException(500)
|
||||
|
||||
return FileResponse(str(path))
|
||||
@@ -1,5 +1,7 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from PIL import Image
|
||||
import os
|
||||
@@ -8,9 +10,15 @@ import io
|
||||
|
||||
from dependencies import get_db, get_current_user
|
||||
from models import User, UpdateBioRequest, UserProfileResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Request models
|
||||
class UpdateProfileRequest(BaseModel):
|
||||
nickname: str | None = None
|
||||
description: str | None = None
|
||||
|
||||
# Create uploads directory if it doesn't exist
|
||||
PROFILE_PICTURES_DIR = Path("data/uploads/pfp")
|
||||
|
||||
@@ -72,12 +80,15 @@ async def get_profile_picture(filename: str):
|
||||
"""
|
||||
Serve profile picture files
|
||||
"""
|
||||
|
||||
if not re.match(r"^\d+_[0-9a-z]+\.jpg$", filename):
|
||||
raise HTTPException(status_code=400, detail="Invalid file name")
|
||||
|
||||
filepath = os.path.join(PROFILE_PICTURES_DIR, filename)
|
||||
|
||||
if not os.path.exists(filepath):
|
||||
raise HTTPException(status_code=404, detail="Profile picture not found")
|
||||
|
||||
from fastapi.responses import FileResponse
|
||||
return FileResponse(filepath, media_type="image/jpeg")
|
||||
|
||||
@router.get("/user/profile")
|
||||
@@ -98,6 +109,56 @@ async def get_user_profile(
|
||||
"created_at": current_user.created_at
|
||||
}
|
||||
|
||||
@router.put("/user/profile")
|
||||
async def update_user_profile(
|
||||
request: UpdateProfileRequest,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Update current user's profile information
|
||||
"""
|
||||
updated = False
|
||||
|
||||
# Update username if provided
|
||||
if request.nickname is not None:
|
||||
nickname = request.nickname.strip()
|
||||
if len(nickname) < 3:
|
||||
raise HTTPException(status_code=400, detail="Username must be at least 3 characters long")
|
||||
if len(nickname) > 50:
|
||||
raise HTTPException(status_code=400, detail="Username must be 50 characters or less")
|
||||
|
||||
# Check if username is already taken by another user
|
||||
existing_user = db.query(User).filter(User.username == nickname, User.id != current_user.id).first()
|
||||
if existing_user:
|
||||
raise HTTPException(status_code=400, detail="Username already taken")
|
||||
|
||||
current_user.username = nickname
|
||||
updated = True
|
||||
|
||||
# Update bio if provided
|
||||
if request.description is not None:
|
||||
bio = request.description.strip()
|
||||
if len(bio) > 500:
|
||||
raise HTTPException(status_code=400, detail="Bio must be 500 characters or less")
|
||||
|
||||
current_user.bio = bio
|
||||
updated = True
|
||||
|
||||
if updated:
|
||||
db.commit()
|
||||
return {
|
||||
"message": "Profile updated successfully",
|
||||
"username": current_user.username,
|
||||
"bio": current_user.bio
|
||||
}
|
||||
else:
|
||||
return {
|
||||
"message": "No changes made",
|
||||
"username": current_user.username,
|
||||
"bio": current_user.bio
|
||||
}
|
||||
|
||||
|
||||
@router.put("/user/bio")
|
||||
async def update_user_bio(
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from dependencies import get_current_user, get_db
|
||||
from models import User, PushSubscriptionRequest
|
||||
from push_service import push_service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/subscribe")
|
||||
async def subscribe_to_push_notifications(
|
||||
request: PushSubscriptionRequest,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Subscribe user to push notifications"""
|
||||
try:
|
||||
success = await push_service.subscribe_user(
|
||||
db=db,
|
||||
user_id=current_user.id,
|
||||
endpoint=request.endpoint,
|
||||
p256dh_key=request.keys["p256dh"],
|
||||
auth_key=request.keys["auth"]
|
||||
)
|
||||
|
||||
if success:
|
||||
return {"status": "success", "message": "Push notifications enabled"}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="Failed to enable push notifications")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.delete("/unsubscribe")
|
||||
async def unsubscribe_from_push_notifications(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Unsubscribe user from push notifications"""
|
||||
try:
|
||||
success = await push_service.unsubscribe_user(db=db, user_id=current_user.id)
|
||||
|
||||
if success:
|
||||
return {"status": "success", "message": "Push notifications disabled"}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="Failed to disable push notifications")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@@ -1 +0,0 @@
|
||||
JWT_SECRET="jwt-secret-change-in-production"
|
||||
@@ -6,6 +6,8 @@ services:
|
||||
environment:
|
||||
PORT: 8300
|
||||
JWT_SECRET: ${JWT_SECRET}
|
||||
VAPID_PUBLIC_KEY: ${VAPID_PUBLIC_KEY}
|
||||
VAPID_PRIVATE_KEY: ${VAPID_PRIVATE_KEY}
|
||||
volumes:
|
||||
- "data:/app/data"
|
||||
develop:
|
||||
|
||||
@@ -36,7 +36,7 @@ USER app
|
||||
|
||||
# 3.1. Frontend static files
|
||||
WORKDIR /app
|
||||
COPY --from=frontend --chown=app /app/frontend/dist .
|
||||
COPY --from=frontend --chown=app /app/frontend/build/normal/dist .
|
||||
|
||||
# 3.2. Static file server
|
||||
WORKDIR /server
|
||||
|
||||
Vendored
+14
-1
@@ -1,8 +1,21 @@
|
||||
export type Platform = "win32" | "darwin" | "linux"
|
||||
|
||||
export interface NotificationShowOptions {
|
||||
title: string;
|
||||
body: string;
|
||||
icon?: string;
|
||||
tag?: string;
|
||||
}
|
||||
|
||||
export interface ElectronNotifications {
|
||||
requestPermission: () => Promise<NotificationPermission>;
|
||||
show: (options: NotificationShowOptions) => Promise<boolean>;
|
||||
}
|
||||
|
||||
export interface ElectronInterface {
|
||||
desktop: true,
|
||||
platform: Platform
|
||||
platform: Platform,
|
||||
notifications: ElectronNotifications
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Hello World!</title>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<h1>💖 Hello World!</h1>
|
||||
<p>Welcome to your Electron application.</p>
|
||||
<script type="module" src="/src/renderer.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,33 +0,0 @@
|
||||
{
|
||||
"name": "FromChat",
|
||||
"productName": "FromChat",
|
||||
"version": "1.0.0",
|
||||
"description": "A 100% Open Source Messenger",
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"package": "electron-forge package",
|
||||
"make": "electron-forge make",
|
||||
"publish": "electron-forge publish"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": {
|
||||
"name": "denis0001-dev",
|
||||
"email": "denis0001.dev@ya.ru"
|
||||
},
|
||||
"license": "GPL-2.0",
|
||||
"devDependencies": {
|
||||
"@electron-forge/cli": "^7.8.3",
|
||||
"@electron-forge/maker-deb": "^7.8.3",
|
||||
"@electron-forge/maker-rpm": "^7.8.3",
|
||||
"@electron-forge/maker-squirrel": "^7.8.3",
|
||||
"@electron-forge/maker-zip": "^7.8.3",
|
||||
"@electron-forge/plugin-auto-unpack-natives": "^7.8.3",
|
||||
"@electron-forge/plugin-fuses": "^7.8.3",
|
||||
"@electron/fuses": "^1.8.0",
|
||||
"electron": "37.3.1",
|
||||
"vite": "^5.4.19"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron-squirrel-startup": "^1.0.1"
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
import { app, BrowserWindow } from 'electron';
|
||||
import { app, BrowserWindow, Notification, ipcMain } from 'electron';
|
||||
import path from "node:path";
|
||||
import { NotificationShowOptions } from '../electron';
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const win = new BrowserWindow({
|
||||
mainWindow = new BrowserWindow({
|
||||
title: 'Main window',
|
||||
minWidth: 650,
|
||||
minWidth: 800,
|
||||
minHeight: 420,
|
||||
webPreferences: {
|
||||
preload: path.join(import.meta.dirname, "preload.mjs")
|
||||
@@ -16,13 +19,48 @@ app.whenReady().then(() => {
|
||||
y: 16 - 4
|
||||
},
|
||||
titleBarOverlay: process.platform !== "darwin"
|
||||
})
|
||||
});
|
||||
|
||||
// You can use `process.env.VITE_DEV_SERVER_URL` when the vite command is called `serve`
|
||||
if (process.env.VITE_DEV_SERVER_URL) {
|
||||
win.loadURL(process.env.VITE_DEV_SERVER_URL)
|
||||
mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
|
||||
} else {
|
||||
// Load your file
|
||||
win.loadFile('dist/index.html');
|
||||
mainWindow.loadFile('frontend/build/electron/dist/index.html');
|
||||
}
|
||||
|
||||
// Handle notification permission requests
|
||||
ipcMain.handle('request-notification-permission', async () => {
|
||||
if (Notification.isSupported()) {
|
||||
return 'granted';
|
||||
}
|
||||
return 'denied';
|
||||
});
|
||||
|
||||
// Handle showing notifications
|
||||
ipcMain.handle('show-notification', async (event, options: NotificationShowOptions) => {
|
||||
if (Notification.isSupported()) {
|
||||
try {
|
||||
const notification = new Notification({
|
||||
title: options.title,
|
||||
body: options.body,
|
||||
icon: options.icon,
|
||||
silent: false,
|
||||
urgency: 'normal'
|
||||
});
|
||||
|
||||
notification.on('click', () => {
|
||||
if (mainWindow) {
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
}
|
||||
});
|
||||
|
||||
notification.show();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error creating notification:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import { contextBridge } from "electron";
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
import type { ElectronInterface, Platform } from "../electron";
|
||||
|
||||
const electronInterface: ElectronInterface = {
|
||||
contextBridge.exposeInMainWorld("electronInterface", {
|
||||
desktop: true,
|
||||
platform: process.platform as Platform
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld("electronInterface", electronInterface);
|
||||
platform: process.platform as Platform,
|
||||
notifications: {
|
||||
requestPermission: () => ipcRenderer.invoke('request-notification-permission'),
|
||||
show: (options) => ipcRenderer.invoke('show-notification', options)
|
||||
}
|
||||
} satisfies ElectronInterface);
|
||||
@@ -1,29 +1,28 @@
|
||||
import { FusesPlugin } from '@electron-forge/plugin-fuses';
|
||||
import { FuseV1Options, FuseVersion } from '@electron/fuses';
|
||||
import type { ForgeConfig } from "@electron-forge/shared-types";
|
||||
import type { ForgeConfig } from '@electron-forge/shared-types';
|
||||
|
||||
const config: ForgeConfig = {
|
||||
export default {
|
||||
packagerConfig: {
|
||||
asar: true
|
||||
asar: true,
|
||||
},
|
||||
outDir: "frontend/build/electron/forge",
|
||||
rebuildConfig: {},
|
||||
makers: [
|
||||
{
|
||||
name: '@electron-forge/maker-squirrel',
|
||||
config: {},
|
||||
},
|
||||
{
|
||||
name: '@electron-forge/maker-zip',
|
||||
config: {},
|
||||
platforms: ['darwin'],
|
||||
platforms: ['win32', 'darwin'],
|
||||
},
|
||||
{
|
||||
name: '@electron-forge/maker-deb',
|
||||
config: {},
|
||||
platforms: ['linux'],
|
||||
},
|
||||
{
|
||||
name: '@electron-forge/maker-rpm',
|
||||
config: {},
|
||||
platforms: ['linux'],
|
||||
},
|
||||
],
|
||||
plugins: [
|
||||
@@ -43,6 +42,4 @@ const config: ForgeConfig = {
|
||||
[FuseV1Options.OnlyLoadAppFromAsar]: true,
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
export default config;
|
||||
} satisfies ForgeConfig;
|
||||
+3
-410
@@ -4,417 +4,10 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Loading...</title>
|
||||
<link rel="icon" href="./src/images/logo.png" />
|
||||
<link rel="icon" href="./src/resources/images/logo.png" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="electron-title-bar">
|
||||
<div class="macos-padding"></div>
|
||||
<div id="window-title"></div>
|
||||
<!-- <div class="window-controls">
|
||||
<mdui-button-icon icon="remove" id="window-minimize"></mdui-button-icon>
|
||||
<mdui-button-icon icon="stack--outlined" id="window-restore" class="hidden"></mdui-button-icon>
|
||||
<mdui-button-icon icon="ad--outlined" id="window-maximize"></mdui-button-icon>
|
||||
<mdui-button-icon icon="close" id="window-close"></mdui-button-icon>
|
||||
</div> -->
|
||||
</div>
|
||||
<div id="main-wrapper">
|
||||
<!-- Login Form -->
|
||||
<div id="login-form" class="auth-container">
|
||||
<div class="auth-card fade-in">
|
||||
<div class="auth-header">
|
||||
<h2>
|
||||
<span class="material-symbols filled large">login</span>
|
||||
Добро пожаловать!
|
||||
</h2>
|
||||
<p>Войдите в свой аккаунт</p>
|
||||
</div>
|
||||
<div class="auth-body">
|
||||
<div id="login-alerts"></div>
|
||||
|
||||
<form id="login-form-element">
|
||||
<mdui-text-field
|
||||
label="Имя пользователя"
|
||||
id="login-username"
|
||||
name="username"
|
||||
variant="outlined"
|
||||
icon="person--filled"
|
||||
autocomplete="username"
|
||||
required>
|
||||
</mdui-text-field>
|
||||
<mdui-text-field
|
||||
label="Пароль"
|
||||
id="login-password"
|
||||
name="password"
|
||||
variant="outlined"
|
||||
type="password"
|
||||
toggle-password
|
||||
icon="password--filled"
|
||||
autocomplete="current-password"
|
||||
required>
|
||||
</mdui-text-field>
|
||||
|
||||
<mdui-button type="submit">Войти</mdui-button>
|
||||
</form>
|
||||
|
||||
<div class="text-center">
|
||||
<p>Ещё нет аккаунта? <a href="#" id="register-link" class="link">Зарегистрируйтесь</a></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Register Form -->
|
||||
<div id="register-form" class="auth-container" style="display: none;">
|
||||
<div class="auth-card fade-in">
|
||||
<div class="auth-header">
|
||||
<h2>
|
||||
<span class="material-symbols filled large">person_add</span>
|
||||
Регистрация
|
||||
</h2>
|
||||
<p>Создайте новый аккаунт</p>
|
||||
</div>
|
||||
<div class="auth-body">
|
||||
<div id="register-alerts"></div>
|
||||
|
||||
<form id="register-form-element">
|
||||
<mdui-text-field
|
||||
label="Имя пользователя"
|
||||
id="register-username"
|
||||
name="username"
|
||||
variant="outlined"
|
||||
icon="person--filled"
|
||||
autocomplete="username"
|
||||
maxlength="20"
|
||||
counter
|
||||
required>
|
||||
</mdui-text-field>
|
||||
<mdui-text-field
|
||||
label="Пароль"
|
||||
id="register-password"
|
||||
name="password"
|
||||
variant="outlined"
|
||||
type="password"
|
||||
toggle-password
|
||||
icon="password--filled"
|
||||
autocomplete="new-password"
|
||||
required>
|
||||
</mdui-text-field>
|
||||
<mdui-text-field
|
||||
label="Подтвердите пароль"
|
||||
id="register-confirm-password"
|
||||
name="confirm_password"
|
||||
variant="outlined"
|
||||
type="password"
|
||||
toggle-password
|
||||
icon="password--filled"
|
||||
autocomplete="new-password"
|
||||
required>
|
||||
</mdui-text-field>
|
||||
|
||||
<mdui-button type="submit">Зарегистрироваться</mdui-button>
|
||||
</form>
|
||||
|
||||
<div class="text-center">
|
||||
<p>
|
||||
Уже есть аккаунт?
|
||||
<a href="#" id="login-link" class="link">Войдите</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Chat Interface -->
|
||||
<div id="chat-interface" style="display: none;">
|
||||
<div class="all-container">
|
||||
<div class="chat-list" id="chat-list">
|
||||
<header class="chat-header-left">
|
||||
<div id="productname">Loading...</div>
|
||||
<div class="profile">
|
||||
<a href="#" id="profile-open">
|
||||
<img src="./src/images/default-avatar.png" alt="" id="preview1" />
|
||||
</a>
|
||||
</div>
|
||||
</header>
|
||||
<div class="chat-tabs">
|
||||
<mdui-tabs value="chats" full-width>
|
||||
<mdui-tab value="chats">
|
||||
Чаты
|
||||
</mdui-tab>
|
||||
<mdui-tab value="channels">
|
||||
Каналы
|
||||
</mdui-tab>
|
||||
<mdui-tab value="contacts">
|
||||
Контакты
|
||||
</mdui-tab>
|
||||
|
||||
<mdui-tab-panel slot="panel" value="chats">
|
||||
<mdui-list>
|
||||
<mdui-list-item headline="Общий чат" description="Вы: Последнее сообщение" id="chat-list-chat-1">
|
||||
<img src="./src/images/default-avatar.png" alt="" slot="icon" />
|
||||
</mdui-list-item>
|
||||
<mdui-list-item headline="Общий чат 2" description="Вы: Последнее сообщение" id="chat-list-chat-2">
|
||||
<img src="./src/images/default-avatar.png" alt="" slot="icon" />
|
||||
</mdui-list-item>
|
||||
</mdui-list>
|
||||
</mdui-tab-panel>
|
||||
<mdui-tab-panel slot="panel" value="channels">Скоро будет...</mdui-tab-panel>
|
||||
<mdui-tab-panel slot="panel" value="contacts">Скоро будет...</mdui-tab-panel>
|
||||
</mdui-tabs>
|
||||
</div>
|
||||
<mdui-bottom-app-bar>
|
||||
<mdui-button-icon icon="settings--filled" id="settings-open"></mdui-button-icon>
|
||||
<mdui-button-icon icon="group_add--filled"></mdui-button-icon>
|
||||
<div style="flex-grow: 1"></div>
|
||||
<mdui-fab icon="edit--filled"></mdui-fab>
|
||||
</mdui-bottom-app-bar>
|
||||
</div>
|
||||
<div class="chat-container">
|
||||
<div class="chat-main" id="chat-inner">
|
||||
<div class="chat-header">
|
||||
<img src="src/images/default-avatar.png" alt="Avatar" class="chat-header-avatar">
|
||||
<div class="chat-header-info">
|
||||
<div class="info-chat">
|
||||
<h4 id="chat-name">Общий чат</h4>
|
||||
<p>
|
||||
<span class="online-status"></span>
|
||||
Онлайн
|
||||
</p>
|
||||
</div>
|
||||
<a href="#" id="hide-chat">Свернуть чат</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chat-messages" id="chat-messages">
|
||||
<!-- Messages will be loaded here dynamically -->
|
||||
</div>
|
||||
|
||||
<div class="chat-input-wrapper">
|
||||
<div class="chat-input">
|
||||
<form class="input-group" id="message-form">
|
||||
<input type="text" class="message-input" id="message-input" placeholder="Напишите сообщение..." autocomplete="off">
|
||||
<button type="submit" class="send-btn">
|
||||
<span class="material-symbols filled">send</span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<mdui-dialog id="profile-dialog" close-on-overlay-click close-on-esc>
|
||||
<div class="content">
|
||||
<div class="header-top">
|
||||
<div class="profile-picture-container">
|
||||
<img id="profile-picture" src="./src/images/default-avatar.png" alt="Ваше фото" />
|
||||
<mdui-button-icon icon="camera_alt--filled" id="upload-pfp-btn" class="upload-overlay" variant="filled"></mdui-button-icon>
|
||||
<input type="file" id="pfp-file-input" accept="image/*" style="display: none;">
|
||||
</div>
|
||||
<mdui-text-field id="username-field" label="Имя пользователя" variant="outlined" value="user123" autocomplete="username"></mdui-text-field>
|
||||
</div>
|
||||
|
||||
<form id="profile-form">
|
||||
<mdui-text-field
|
||||
id="description-field"
|
||||
label="О себе"
|
||||
variant="outlined"
|
||||
multiline
|
||||
rows="3"
|
||||
placeholder="Расскажите о себе..."
|
||||
autocomplete="none"></mdui-text-field>
|
||||
<div class="dialog-actions">
|
||||
<mdui-button type="submit" id="profile-submit">Сохранить изменения</mdui-button>
|
||||
<mdui-button id="profile-dialog-close" variant="outlined">Закрыть</mdui-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</mdui-dialog>
|
||||
|
||||
<!-- Profile Picture Cropper Dialog -->
|
||||
<mdui-dialog id="cropper-dialog" close-on-overlay-click close-on-esc>
|
||||
<div class="cropper-dialog-content">
|
||||
<div class="cropper-header">
|
||||
<h3>Обрезать фото профиля</h3>
|
||||
<mdui-button-icon icon="close" id="cropper-close"></mdui-button-icon>
|
||||
</div>
|
||||
<div class="cropper-container">
|
||||
<div id="cropper-area"></div>
|
||||
</div>
|
||||
<div class="cropper-actions">
|
||||
<mdui-button id="crop-cancel" variant="outlined">Отмена</mdui-button>
|
||||
<mdui-button id="crop-save">Сохранить</mdui-button>
|
||||
</div>
|
||||
</div>
|
||||
</mdui-dialog>
|
||||
|
||||
<mdui-dialog id="settings-dialog" close-on-overlay-click close-on-esc fullscreen>
|
||||
<div class="fullscreen-wrapper">
|
||||
<div id="settings-dialog-inner">
|
||||
<div class="header">
|
||||
<mdui-button-icon icon="close" id="settings-close"></mdui-button-icon>
|
||||
<mdui-top-app-bar-title>Настройки</mdui-top-app-bar-title>
|
||||
</div>
|
||||
<div id="settings-menu">
|
||||
<mdui-list>
|
||||
<mdui-list-item icon="notifications--filled" rounded active>Уведомления</mdui-list-item>
|
||||
<mdui-list-item icon="palette--filled" rounded>Внешний вид</mdui-list-item>
|
||||
<mdui-list-item icon="security--filled" rounded>Безопасность</mdui-list-item>
|
||||
<mdui-list-item icon="language--filled" rounded>Язык</mdui-list-item>
|
||||
<mdui-list-item icon="storage--filled" rounded>Хранилище</mdui-list-item>
|
||||
<mdui-list-item icon="help--filled" rounded>Помощь</mdui-list-item>
|
||||
<mdui-list-item icon="info--filled" rounded>О приложении</mdui-list-item>
|
||||
</mdui-list>
|
||||
<div class="screen">
|
||||
<div id="notifications-settings" class="settings-panel active">
|
||||
<h3>Уведомления</h3>
|
||||
<mdui-switch checked>Новые сообщения</mdui-switch>
|
||||
<mdui-switch checked>Звуковые уведомления</mdui-switch>
|
||||
<mdui-switch>Уведомления о статусе</mdui-switch>
|
||||
<mdui-switch checked>Email уведомления</mdui-switch>
|
||||
</div>
|
||||
|
||||
<div id="appearance-settings" class="settings-panel">
|
||||
<h3>Внешний вид</h3>
|
||||
<mdui-select label="Тема" variant="outlined">
|
||||
<mdui-menu-item value="dark">Тёмная</mdui-menu-item>
|
||||
<mdui-menu-item value="light">Светлая</mdui-menu-item>
|
||||
<mdui-menu-item value="auto">Авто</mdui-menu-item>
|
||||
</mdui-select>
|
||||
<mdui-select label="Размер шрифта" variant="outlined">
|
||||
<mdui-menu-item value="small">Маленький</mdui-menu-item>
|
||||
<mdui-menu-item value="medium">Средний</mdui-menu-item>
|
||||
<mdui-menu-item value="large">Большой</mdui-menu-item>
|
||||
</mdui-select>
|
||||
</div>
|
||||
|
||||
<div id="security-settings" class="settings-panel">
|
||||
<h3>Безопасность</h3>
|
||||
<mdui-button variant="outlined">Изменить пароль</mdui-button>
|
||||
<mdui-button variant="outlined">Двухфакторная аутентификация</mdui-button>
|
||||
<mdui-switch>Автоматический выход</mdui-switch>
|
||||
</div>
|
||||
|
||||
<div id="language-settings" class="settings-panel">
|
||||
<h3>Язык</h3>
|
||||
<mdui-select label="Выберите язык" variant="outlined">
|
||||
<mdui-menu-item value="ru">Русский</mdui-menu-item>
|
||||
<mdui-menu-item value="en">English</mdui-menu-item>
|
||||
<mdui-menu-item value="es">Español</mdui-menu-item>
|
||||
</mdui-select>
|
||||
</div>
|
||||
|
||||
<div id="storage-settings" class="settings-panel">
|
||||
<h3>Хранилище</h3>
|
||||
<p>Использовано: 2.5 ГБ из 10 ГБ</p>
|
||||
<mdui-linear-progress value="25"></mdui-linear-progress>
|
||||
<mdui-button variant="outlined">Очистить кэш</mdui-button>
|
||||
</div>
|
||||
|
||||
<div id="help-settings" class="settings-panel">
|
||||
<h3>Помощь</h3>
|
||||
<mdui-button variant="outlined">Руководство пользователя</mdui-button>
|
||||
<mdui-button variant="outlined">Связаться с поддержкой</mdui-button>
|
||||
<mdui-button variant="outlined">FAQ</mdui-button>
|
||||
</div>
|
||||
|
||||
<div id="about-settings" class="settings-panel">
|
||||
<h3>О приложении</h3>
|
||||
<p>Версия: 1.0.0</p>
|
||||
<p>© 2024 From Chat. Все права защищены.</p>
|
||||
<mdui-button variant="outlined">Политика конфиденциальности</mdui-button>
|
||||
<mdui-button variant="outlined">Условия использования</mdui-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</mdui-dialog>
|
||||
|
||||
<div id="message-context-menu" class="context-menu">
|
||||
<div class="context-menu-item" data-action="reply">
|
||||
<span class="material-symbols">reply</span>
|
||||
Reply
|
||||
</div>
|
||||
<div class="context-menu-item" data-action="edit">
|
||||
<span class="material-symbols">edit</span>
|
||||
Edit
|
||||
</div>
|
||||
<div class="context-menu-item" data-action="delete">
|
||||
<span class="material-symbols">delete</span>
|
||||
Delete
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<mdui-dialog id="edit-message-dialog" close-on-overlay-click close-on-esc>
|
||||
<div class="dialog-content">
|
||||
<h3>Edit Message</h3>
|
||||
<mdui-text-field
|
||||
id="edit-message-input"
|
||||
label="Edit Message"
|
||||
variant="outlined"
|
||||
multiline
|
||||
rows="4"
|
||||
placeholder="Edit your message..."
|
||||
maxlength="1000">
|
||||
</mdui-text-field>
|
||||
<div class="dialog-actions">
|
||||
<mdui-button id="edit-cancel" variant="outlined">Cancel</mdui-button>
|
||||
<mdui-button id="edit-save">Save</mdui-button>
|
||||
</div>
|
||||
</div>
|
||||
</mdui-dialog>
|
||||
|
||||
<mdui-dialog id="reply-message-dialog" close-on-overlay-click close-on-esc>
|
||||
<div class="dialog-content">
|
||||
<h3>Reply to Message</h3>
|
||||
<div class="reply-preview" id="reply-preview"></div>
|
||||
<mdui-text-field
|
||||
id="reply-message-input"
|
||||
label="Reply"
|
||||
variant="outlined"
|
||||
multiline
|
||||
rows="4"
|
||||
placeholder="Type your reply..."
|
||||
maxlength="1000">
|
||||
</mdui-text-field>
|
||||
<div class="dialog-actions">
|
||||
<mdui-button id="reply-cancel" variant="outlined">Cancel</mdui-button>
|
||||
<mdui-button id="reply-send">Send Reply</mdui-button>
|
||||
</div>
|
||||
</div>
|
||||
</mdui-dialog>
|
||||
|
||||
<mdui-dialog id="user-profile-dialog" close-on-overlay-click close-on-esc>
|
||||
<div class="content">
|
||||
<div class="profile-picture-section">
|
||||
<img class="profile-picture" src="" alt="Profile Picture">
|
||||
</div>
|
||||
<div class="profile-info">
|
||||
<div class="username-section">
|
||||
<h4 class="username"></h4>
|
||||
<div class="online-status"></div>
|
||||
</div>
|
||||
<div class="bio-section">
|
||||
<label>Bio:</label>
|
||||
<div class="bio-display"></div>
|
||||
</div>
|
||||
<div class="profile-stats">
|
||||
<div class="stat">
|
||||
<span class="stat-label">Member since:</span>
|
||||
<span class="stat-value member-since"></span>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat-label">Last seen:</span>
|
||||
<span class="stat-value last-seen"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</mdui-dialog>
|
||||
|
||||
<script src="src/main.ts" type="module"></script>
|
||||
<div id="root"></div>
|
||||
<script src="src/main.tsx" type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,171 @@
|
||||
import { API_BASE_URL } from "../core/config";
|
||||
import { getAuthHeaders } from "../auth/api";
|
||||
import { ecdhSharedSecret, deriveWrappingKey } from "../utils/crypto/asymmetric";
|
||||
import { importAesGcmKey, aesGcmEncrypt, aesGcmDecrypt } from "../utils/crypto/symmetric";
|
||||
import { randomBytes } from "../utils/crypto/kdf";
|
||||
import { getCurrentKeys } from "../auth/crypto";
|
||||
import { request } from "../core/websocket";
|
||||
import type { SendDMRequest, DmEnvelope, User, DMEditRequest, DmEncryptedJSON, BaseDmEnvelope } from "../core/types";
|
||||
import { b64, ub64 } from "../utils/utils";
|
||||
|
||||
export async function decryptDm(envelope: DmEnvelope, senderPublicKeyB64: string): Promise<string> {
|
||||
const keys = getCurrentKeys();
|
||||
if (!keys) throw new Error("Keys not initialized");
|
||||
|
||||
// Obtain the key
|
||||
const shared = ecdhSharedSecret(keys.privateKey, ub64(senderPublicKeyB64));
|
||||
const wkRaw = await deriveWrappingKey(shared, ub64(envelope.salt), new Uint8Array([1]));
|
||||
const wk = await importAesGcmKey(wkRaw);
|
||||
const mk = await aesGcmDecrypt(wk, ub64(envelope.iv2), ub64(envelope.wrappedMk));
|
||||
|
||||
// Decrypt
|
||||
const msg = await aesGcmDecrypt(await importAesGcmKey(mk), ub64(envelope.iv), ub64(envelope.ciphertext));
|
||||
return new TextDecoder().decode(msg);
|
||||
}
|
||||
|
||||
export async function fetchUsers(token: string): Promise<User[]> {
|
||||
const res = await fetch(`${API_BASE_URL}/users`, { headers: getAuthHeaders(token, true) });
|
||||
if (!res.ok) return [];
|
||||
const data = await res.json();
|
||||
return data.users || [];
|
||||
}
|
||||
|
||||
export async function fetchUserPublicKey(userId: number, token: string): Promise<string | null> {
|
||||
const res = await fetch(`${API_BASE_URL}/crypto/public-key/of/${userId}`, { headers: getAuthHeaders(token, true) });
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
return data.publicKey;
|
||||
}
|
||||
|
||||
export async function fetchDMHistory(userId: number, token: string, limit: number = 50): Promise<DmEnvelope[]> {
|
||||
const response = await fetch(`${API_BASE_URL}/dm/history/${userId}?limit=${limit}`, {
|
||||
headers: getAuthHeaders(token, true)
|
||||
});
|
||||
if (!response.ok) return [];
|
||||
const data = await response.json();
|
||||
return data.messages || [];
|
||||
}
|
||||
|
||||
export async function sendDMViaWebSocket(recipientId: number, recipientPublicKeyB64: string, plaintext: string, authToken: string, replyToId?: number): Promise<void> {
|
||||
const keys = getCurrentKeys();
|
||||
if (!keys) throw new Error("Keys not initialized");
|
||||
|
||||
// Encryption key
|
||||
const mk = randomBytes(32);
|
||||
const wkSalt = randomBytes(16);
|
||||
const shared = ecdhSharedSecret(keys.privateKey, ub64(recipientPublicKeyB64));
|
||||
const wkRaw = await deriveWrappingKey(shared, wkSalt, new Uint8Array([1]));
|
||||
const wk = await importAesGcmKey(wkRaw);
|
||||
|
||||
// Encrypt the message
|
||||
const encMsg = await aesGcmEncrypt(await importAesGcmKey(mk), new TextEncoder().encode(plaintext));
|
||||
const wrap = await aesGcmEncrypt(wk, mk);
|
||||
|
||||
const payload: SendDMRequest = {
|
||||
recipientId: recipientId,
|
||||
iv: b64(encMsg.iv),
|
||||
ciphertext: b64(encMsg.ciphertext),
|
||||
salt: b64(wkSalt),
|
||||
iv2: b64(wrap.iv),
|
||||
wrappedMk: b64(wrap.ciphertext)
|
||||
};
|
||||
if (replyToId) payload.replyToId = replyToId;
|
||||
|
||||
await request({
|
||||
type: "dmSend",
|
||||
credentials: {
|
||||
scheme: "Bearer",
|
||||
credentials: authToken
|
||||
},
|
||||
data: payload
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendDmWithFiles(recipientId: number, recipientPublicKeyB64: string, plaintextJson: string, files: File[], token: string): Promise<void> {
|
||||
const keys = getCurrentKeys();
|
||||
if (!keys) throw new Error("Keys not initialized");
|
||||
|
||||
const mk = randomBytes(32);
|
||||
const wkSalt = randomBytes(16);
|
||||
const shared = await ecdhSharedSecret(keys.privateKey, ub64(recipientPublicKeyB64));
|
||||
const wkRaw = await deriveWrappingKey(shared, wkSalt, new Uint8Array([1]));
|
||||
const wk = await importAesGcmKey(wkRaw);
|
||||
|
||||
const wrap = await aesGcmEncrypt(wk, mk);
|
||||
|
||||
const form = new FormData();
|
||||
const names: string[] = [];
|
||||
function sliceBuffer(u8: Uint8Array): ArrayBuffer {
|
||||
return (u8.buffer as ArrayBuffer).slice(u8.byteOffset, u8.byteOffset + u8.byteLength);
|
||||
}
|
||||
|
||||
for (const f of files) {
|
||||
// Encrypt file with same mk
|
||||
const data = new Uint8Array(await f.arrayBuffer());
|
||||
const enc = await aesGcmEncrypt(await importAesGcmKey(mk), data);
|
||||
const blob = new Blob([sliceBuffer(enc.iv), sliceBuffer(enc.ciphertext)], { type: "application/octet-stream" });
|
||||
const serverName = f.name; // server uses provided name
|
||||
names.push(serverName);
|
||||
form.append("files", new File([blob], serverName));
|
||||
}
|
||||
form.append("fileNames", JSON.stringify(names));
|
||||
|
||||
// Merge files metadata into plaintext JSON and encrypt
|
||||
let obj: DmEncryptedJSON;
|
||||
try {
|
||||
obj = JSON.parse(plaintextJson);
|
||||
} catch {
|
||||
obj = { type: "text", data: { content: String(plaintextJson) } };
|
||||
}
|
||||
|
||||
const encMsg = await aesGcmEncrypt(await importAesGcmKey(mk), new TextEncoder().encode(JSON.stringify(obj)));
|
||||
form.append("dm_payload", JSON.stringify({
|
||||
recipientId: recipientId,
|
||||
iv: b64(encMsg.iv),
|
||||
ciphertext: b64(encMsg.ciphertext),
|
||||
salt: b64(wkSalt),
|
||||
iv2: b64(wrap.iv),
|
||||
wrappedMk: b64(wrap.ciphertext)
|
||||
} satisfies BaseDmEnvelope));
|
||||
|
||||
await fetch(`${API_BASE_URL}/dm/send`, {
|
||||
method: "POST",
|
||||
headers: getAuthHeaders(token, false),
|
||||
body: form
|
||||
});
|
||||
}
|
||||
|
||||
export async function editDmEnvelope(id: number, recipientPublicKeyB64: string, newPlaintextJson: string, authToken: string): Promise<void> {
|
||||
const keys = getCurrentKeys();
|
||||
if (!keys) throw new Error("Keys not initialized");
|
||||
|
||||
// We cannot reuse the old mk safely without knowing it; generate a fresh mk and wrap
|
||||
const mk = randomBytes(32);
|
||||
const wkSalt = randomBytes(16);
|
||||
const shared = await ecdhSharedSecret(keys.privateKey, ub64(recipientPublicKeyB64));
|
||||
const wkRaw = await deriveWrappingKey(shared, wkSalt, new Uint8Array([1]));
|
||||
const wk = await importAesGcmKey(wkRaw);
|
||||
const encMsg = await aesGcmEncrypt(await importAesGcmKey(mk), new TextEncoder().encode(newPlaintextJson));
|
||||
const wrap = await aesGcmEncrypt(wk, mk);
|
||||
|
||||
await request({
|
||||
type: "dmEdit",
|
||||
credentials: { scheme: "Bearer", credentials: authToken },
|
||||
data: {
|
||||
id,
|
||||
iv: b64(encMsg.iv),
|
||||
ciphertext: b64(encMsg.ciphertext),
|
||||
iv2: b64(wrap.iv),
|
||||
wrappedMk: b64(wrap.ciphertext),
|
||||
salt: b64(wkSalt)
|
||||
}
|
||||
} as DMEditRequest);
|
||||
}
|
||||
|
||||
export async function deleteDmEnvelope(id: number, recipientId: number, authToken: string): Promise<void> {
|
||||
await request({
|
||||
type: "dmDelete",
|
||||
credentials: { scheme: "Bearer", credentials: authToken },
|
||||
data: { id, recipientId }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { getAuthHeaders } from "../auth/api";
|
||||
import { API_BASE_URL } from "../core/config";
|
||||
import type { UserProfile } from "../core/types";
|
||||
|
||||
export interface ProfileData {
|
||||
profile_picture?: string;
|
||||
nickname?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface UploadResponse {
|
||||
profile_picture_url: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads user profile data from the server
|
||||
*/
|
||||
export async function loadProfile(token: string): Promise<ProfileData | null> {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/user/profile`, {
|
||||
headers: getAuthHeaders(token)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
// Map backend fields to frontend fields
|
||||
return {
|
||||
profile_picture: data.profile_picture,
|
||||
nickname: data.username,
|
||||
description: data.bio
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Error loading profile:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads a profile picture to the server
|
||||
*/
|
||||
export async function uploadProfilePicture(token: string, file: Blob): Promise<UploadResponse | null> {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('profile_picture', file, 'profile_picture.jpg');
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/upload-profile-picture`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: getAuthHeaders(token, false)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Upload error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates user profile information
|
||||
*/
|
||||
export async function updateProfile(token: string, data: Partial<ProfileData>): Promise<boolean> {
|
||||
try {
|
||||
// Map frontend fields to backend fields
|
||||
const backendData = {
|
||||
nickname: data.nickname,
|
||||
description: data.description
|
||||
};
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/user/profile`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
...getAuthHeaders(token),
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(backendData)
|
||||
});
|
||||
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
console.error('Error updating profile:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates user bio
|
||||
*/
|
||||
export async function updateBio(token: string, bio: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/user/bio`, {
|
||||
method: 'PUT',
|
||||
headers: getAuthHeaders(token),
|
||||
body: JSON.stringify({ bio })
|
||||
});
|
||||
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
console.error('Error updating bio:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches user profile data by username
|
||||
*/
|
||||
export async function fetchUserProfile(token: string, username: string): Promise<UserProfile | null> {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/user/${username}`, {
|
||||
headers: getAuthHeaders(token)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Error fetching user profile:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Authentication system implementation
|
||||
* @description Handles user authentication, registration, and session management
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { loadMessages } from "./chat";
|
||||
import { initializeProfile } from "./profile";
|
||||
import type { Headers, ErrorResponse, User, LoginResponse, LoginRequest, RegisterRequest } from "./types";
|
||||
import { API_BASE_URL } from "./config";
|
||||
|
||||
/**
|
||||
* Current authenticated user information
|
||||
* @type {User | null}
|
||||
*/
|
||||
export let currentUser: User | null = null;
|
||||
|
||||
/**
|
||||
* JWT authentication token
|
||||
* @type {string | null}
|
||||
*/
|
||||
export let authToken: string | null = null;
|
||||
|
||||
/**
|
||||
* Generates authentication headers for API requests
|
||||
* @param {boolean} json - Whether to include JSON content type header
|
||||
* @returns {Headers} Headers object with authentication and content type
|
||||
* @function getAuthHeaders
|
||||
* @example
|
||||
* const headers = getAuthHeaders();
|
||||
* fetch('/api/endpoint', { headers });
|
||||
*/
|
||||
export function getAuthHeaders(json: boolean = true): Headers {
|
||||
const headers: Headers = {};
|
||||
|
||||
if (json) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
if (authToken) {
|
||||
headers['Authorization'] = `Bearer ${authToken}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the login form and hides other interfaces
|
||||
* @function showLogin
|
||||
* @example
|
||||
* showLogin();
|
||||
*/
|
||||
export function showLogin(): void {
|
||||
document.getElementById('login-form')!.style.display = 'flex';
|
||||
document.getElementById('register-form')!.style.display = 'none';
|
||||
document.getElementById('chat-interface')!.style.display = 'none';
|
||||
clearAlerts();
|
||||
document.getElementById("electron-title-bar")!.classList.add("color-surface");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the registration form and hides other interfaces
|
||||
* @function showRegister
|
||||
* @example
|
||||
* showRegister();
|
||||
*/
|
||||
export function showRegister(): void {
|
||||
document.getElementById('login-form')!.style.display = 'none';
|
||||
document.getElementById('register-form')!.style.display = 'flex';
|
||||
document.getElementById('chat-interface')!.style.display = 'none';
|
||||
clearAlerts();
|
||||
document.getElementById("electron-title-bar")!.classList.add("color-surface");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the chat interface and hides authentication forms
|
||||
* @function showChat
|
||||
* @example
|
||||
* showChat();
|
||||
*/
|
||||
export function showChat(): void {
|
||||
document.getElementById('login-form')!.style.display = 'none';
|
||||
document.getElementById('register-form')!.style.display = 'none';
|
||||
document.getElementById('chat-interface')!.style.display = 'block';
|
||||
loadMessages();
|
||||
document.getElementById("electron-title-bar")!.classList.remove("color-surface");
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all alert messages from authentication forms
|
||||
* @function clearAlerts
|
||||
* @private
|
||||
*/
|
||||
export function clearAlerts(): void {
|
||||
document.getElementById('login-alerts')!.innerHTML = '';
|
||||
document.getElementById('register-alerts')!.innerHTML = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows an alert message in the specified container
|
||||
* @param {string} containerId - ID of the container to show the alert in
|
||||
* @param {string} message - Alert message to display
|
||||
* @param {'success' | 'danger'} type - Type of alert (success or danger)
|
||||
* @function showAlert
|
||||
* @example
|
||||
* showAlert('login-alerts', 'Login successful!', 'success');
|
||||
*/
|
||||
export function showAlert(containerId: string, message: string, type: "success" | "danger" = 'danger'): void {
|
||||
const container = document.getElementById(containerId)!;
|
||||
const alertDiv = document.createElement('div');
|
||||
alertDiv.className = `alert alert-${type}`;
|
||||
alertDiv.textContent = message;
|
||||
container.appendChild(alertDiv);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles login form submission
|
||||
* @async
|
||||
* @function handleLogin
|
||||
* @param {Event} e - Form submission event
|
||||
* @private
|
||||
*/
|
||||
async function handleLogin(e: Event): Promise<void> {
|
||||
e.preventDefault();
|
||||
|
||||
const usernameElement = document.getElementById('login-username') as HTMLInputElement;
|
||||
const passwordElement = document.getElementById('login-password') as HTMLInputElement;
|
||||
|
||||
const username = usernameElement.value.trim();
|
||||
const password = passwordElement.value.trim();
|
||||
|
||||
if (!username || !password) {
|
||||
showAlert('login-alerts', 'Пожалуйста, заполните все поля', 'danger');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const request: LoginRequest = {
|
||||
username: username,
|
||||
password: password
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(request)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data: LoginResponse = await response.json();
|
||||
// Store the JWT token
|
||||
authToken = data.token;
|
||||
currentUser = data.user;
|
||||
showChat();
|
||||
loadMessages(); // Start loading messages
|
||||
initializeProfile(); // Initialize profile after login
|
||||
} else {
|
||||
const data: ErrorResponse = await response.json();
|
||||
showAlert('login-alerts', data.message || 'Неверное имя пользователя или пароль', 'danger');
|
||||
}
|
||||
} catch (error) {
|
||||
showAlert('login-alerts', 'Ошибка соединения с сервером', 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles registration form submission
|
||||
* @async
|
||||
* @function handleRegister
|
||||
* @param {Event} e - Form submission event
|
||||
* @private
|
||||
*/
|
||||
async function handleRegister(e: Event): Promise<void> {
|
||||
e.preventDefault();
|
||||
|
||||
const usernameElement = document.getElementById('register-username') as HTMLInputElement;
|
||||
const passwordElement = document.getElementById('register-password') as HTMLInputElement;
|
||||
const confirmPasswordElement = document.getElementById('register-confirm-password') as HTMLInputElement;
|
||||
|
||||
const username = usernameElement.value.trim();
|
||||
const password = passwordElement.value.trim();
|
||||
const confirmPassword = confirmPasswordElement.value.trim();
|
||||
|
||||
if (!username || !password || !confirmPassword) {
|
||||
showAlert('register-alerts', 'Пожалуйста, заполните все поля', 'danger');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
showAlert('register-alerts', 'Пароли не совпадают', 'danger');
|
||||
return;
|
||||
}
|
||||
|
||||
if (username.length < 3 || username.length > 20) {
|
||||
showAlert('register-alerts', 'Имя пользователя должно быть от 3 до 20 символов', 'danger');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password.length < 5 || password.length > 50) {
|
||||
showAlert('register-alerts', 'Пароль должен быть от 5 до 50 символов', 'danger');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const request: RegisterRequest = {
|
||||
username: username,
|
||||
password: password,
|
||||
confirm_password: confirmPassword
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/register`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(request)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
// Registration successful
|
||||
showAlert('register-alerts', 'Регистрация прошла успешно! Теперь вы можете войти.', 'success');
|
||||
setTimeout(() => {
|
||||
showLogin();
|
||||
}, 2000);
|
||||
} else {
|
||||
const data: ErrorResponse = await response.json();
|
||||
showAlert('register-alerts', data.message || 'Ошибка при регистрации', 'danger');
|
||||
}
|
||||
} catch (error) {
|
||||
showAlert('register-alerts', 'Ошибка соединения с сервером', 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs out the current user and clears session data
|
||||
* @async
|
||||
* @function logout
|
||||
* @example
|
||||
* await logout();
|
||||
*/
|
||||
export async function logout(): Promise<void> {
|
||||
try {
|
||||
await fetch(`${API_BASE_URL}/logout`, {
|
||||
method: 'GET',
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error);
|
||||
}
|
||||
|
||||
currentUser = null;
|
||||
authToken = null;
|
||||
showLogin();
|
||||
clearAlerts();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the chat interface and initializes messaging
|
||||
* @function loadChat
|
||||
* @example
|
||||
* loadChat();
|
||||
*/
|
||||
export function loadChat(): void {
|
||||
showChat();
|
||||
loadMessages();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks authentication status on page load
|
||||
* @async
|
||||
* @function checkAuthStatus
|
||||
* @example
|
||||
* await checkAuthStatus();
|
||||
*/
|
||||
export async function checkAuthStatus(): Promise<void> {
|
||||
// For JWT, we don't have a persistent token on page load
|
||||
// So we'll just show the login form
|
||||
showLogin();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up authentication form event listeners
|
||||
* @function setupAuthForms
|
||||
* @private
|
||||
*/
|
||||
function setupAuthForms(): void {
|
||||
document.getElementById('login-form-element')!.addEventListener('submit', handleLogin);
|
||||
document.getElementById('register-form-element')!.addEventListener('submit', handleRegister);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes links
|
||||
* @function setupLinks
|
||||
* @private
|
||||
*/
|
||||
function setupLinks(): void {
|
||||
document.getElementById("login-link")!.addEventListener("click", showLogin);
|
||||
document.getElementById("register-link")!.addEventListener("click", showRegister);
|
||||
}
|
||||
|
||||
// Initialize authentication forms
|
||||
setupAuthForms();
|
||||
setupLinks();
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Headers } from "../core/types";
|
||||
|
||||
/**
|
||||
* Generates authentication headers for API requests
|
||||
* @param {boolean} json - Whether to include JSON content type header
|
||||
* @returns {Headers} Headers object with authentication and content type
|
||||
*/
|
||||
export function getAuthHeaders(token: string | null, json: boolean = true): Headers {
|
||||
const headers: Headers = {};
|
||||
|
||||
if (json) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { API_BASE_URL } from "../core/config";
|
||||
import { getAuthHeaders } from "./api";
|
||||
import { generateX25519KeyPair } from "../utils/crypto/asymmetric";
|
||||
import { encryptBackupWithPassword, decryptBackupWithPassword, encodeBlob, decodeBlob } from "../utils/crypto/backup";
|
||||
import { b64, ub64 } from "../utils/utils";
|
||||
import type { BackupBlob, UploadPublicKeyRequest } from "../core/types";
|
||||
|
||||
let currentPublicKey: Uint8Array | null = null;
|
||||
let currentPrivateKey: Uint8Array | null = null;
|
||||
|
||||
async function fetchPublicKey(token: string): Promise<Uint8Array | null> {
|
||||
const headers = getAuthHeaders(token, true);
|
||||
const res = await fetch(`${API_BASE_URL}/crypto/public-key`, { method: "GET", headers });
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
if (!data?.publicKey) return null;
|
||||
return ub64(data.publicKey);
|
||||
}
|
||||
|
||||
async function uploadPublicKey(publicKey: Uint8Array, token: string): Promise<void> {
|
||||
const payload: UploadPublicKeyRequest = {
|
||||
publicKey: b64(publicKey)
|
||||
}
|
||||
|
||||
const headers = getAuthHeaders(token, true);
|
||||
await fetch(`${API_BASE_URL}/crypto/public-key`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchBackupBlob(token: string): Promise<string | null> {
|
||||
const headers = getAuthHeaders(token, true);
|
||||
const res = await fetch(`${API_BASE_URL}/crypto/backup`, {
|
||||
method: "GET",
|
||||
headers
|
||||
});
|
||||
if (res.ok) {
|
||||
const response: BackupBlob = await res.json();
|
||||
return response.blob;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadBackupBlob(blobJson: string, token: string): Promise<void> {
|
||||
const payload: BackupBlob = { blob: blobJson }
|
||||
|
||||
const headers = getAuthHeaders(token, true);
|
||||
await fetch(`${API_BASE_URL}/crypto/backup`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
|
||||
export interface UserKeyPairMemory {
|
||||
publicKey: Uint8Array;
|
||||
privateKey: Uint8Array;
|
||||
}
|
||||
|
||||
export function getCurrentKeys(): UserKeyPairMemory | null {
|
||||
if (currentPublicKey && currentPrivateKey) return { publicKey: currentPublicKey, privateKey: currentPrivateKey };
|
||||
return null;
|
||||
}
|
||||
|
||||
function saveKeys(
|
||||
publicKey: Uint8Array<ArrayBufferLike>,
|
||||
privateKey: Uint8Array<ArrayBufferLike>
|
||||
) {
|
||||
const encodedPublicKey = b64(publicKey);
|
||||
const encodedPrivateKey = b64(privateKey);
|
||||
|
||||
localStorage.setItem("publicKey", encodedPublicKey);
|
||||
localStorage.setItem("privateKey", encodedPrivateKey);
|
||||
}
|
||||
|
||||
export async function ensureKeysOnLogin(password: string, token: string): Promise<UserKeyPairMemory> {
|
||||
// Try to restore from backup
|
||||
const blobJson = await fetchBackupBlob(token);
|
||||
if (blobJson) {
|
||||
const blob = decodeBlob(blobJson);
|
||||
const bundle = await decryptBackupWithPassword(password, blob);
|
||||
currentPrivateKey = bundle.privateKey;
|
||||
// Ensure public key exists on server; if not, derive from private (not possible via libsafely), so keep previous
|
||||
// In our simple scheme, we rely on server having the public key or we reupload generated one on first setup
|
||||
const serverPub = await fetchPublicKey(token);
|
||||
if (serverPub) {
|
||||
currentPublicKey = serverPub;
|
||||
} else {
|
||||
// We don't have the corresponding public key from server; regenerate pair to resync
|
||||
const pair = generateX25519KeyPair();
|
||||
currentPublicKey = pair.publicKey;
|
||||
currentPrivateKey = pair.privateKey;
|
||||
await uploadPublicKey(currentPublicKey, token);
|
||||
const newBlob = await encryptBackupWithPassword(password, { version: 1, privateKey: currentPrivateKey });
|
||||
await uploadBackupBlob(encodeBlob(newBlob), token);
|
||||
}
|
||||
|
||||
saveKeys(currentPublicKey!, currentPrivateKey!);
|
||||
|
||||
return {
|
||||
publicKey: currentPublicKey!,
|
||||
privateKey: currentPrivateKey!
|
||||
};
|
||||
}
|
||||
|
||||
// First-time setup: generate keys and upload
|
||||
const pair = generateX25519KeyPair();
|
||||
currentPublicKey = pair.publicKey;
|
||||
currentPrivateKey = pair.privateKey;
|
||||
await uploadPublicKey(currentPublicKey, token);
|
||||
const encBlob = await encryptBackupWithPassword(password, { version: 1, privateKey: currentPrivateKey });
|
||||
await uploadBackupBlob(encodeBlob(encBlob), token);
|
||||
|
||||
saveKeys(pair.publicKey, pair.privateKey);
|
||||
|
||||
return pair;
|
||||
}
|
||||
|
||||
export function restoreKeys() {
|
||||
currentPublicKey = ub64(localStorage.getItem("publicKey")!);
|
||||
currentPrivateKey = ub64(localStorage.getItem("privateKey")!);
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Chat functionality and message management
|
||||
* @description Handles message display, loading, sending, and real-time updates
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { getAuthHeaders, currentUser, authToken } from "./auth";
|
||||
import { API_BASE_URL } from "./config";
|
||||
import { websocket } from "./websocket";
|
||||
import type { Message, Messages, WebSocketMessage } from "./types";
|
||||
import { formatTime } from "./utils/utils";
|
||||
import { show as showContextMenu } from "./message-context-menu";
|
||||
import { show as showUserProfileDialog } from "./user-profile-dialog";
|
||||
import defaultAvatar from "./images/default-avatar.png";
|
||||
|
||||
/**
|
||||
* Adds a new message to the chat interface
|
||||
* @param {Message} message - Message object to display
|
||||
* @param {boolean} isAuthor - Whether the current user is the message author
|
||||
* @function addMessage
|
||||
* @example
|
||||
* addMessage(messageData, messageData.username === currentUser.username);
|
||||
*/
|
||||
export function addMessage(message: Message, isAuthor: boolean): void {
|
||||
const messagesContainer = document.querySelector('.chat-messages') as HTMLElement;
|
||||
const messageDiv = document.createElement('div');
|
||||
messageDiv.classList.add("message");
|
||||
if (isAuthor) {
|
||||
messageDiv.classList.add("sent");
|
||||
} else {
|
||||
messageDiv.classList.add("received");
|
||||
}
|
||||
messageDiv.dataset.id = `${message.id}`;
|
||||
|
||||
const messageInner = document.createElement('div');
|
||||
messageInner.classList.add('message-inner');
|
||||
|
||||
// Add profile picture for received messages
|
||||
if (!isAuthor) {
|
||||
const profilePicDiv = document.createElement('div');
|
||||
profilePicDiv.classList.add('message-profile-pic');
|
||||
|
||||
const profileImg = document.createElement('img');
|
||||
profileImg.src = message.profile_picture || defaultAvatar;
|
||||
profileImg.alt = message.username;
|
||||
|
||||
let errorLock = false;
|
||||
|
||||
profileImg.addEventListener("error", () => {
|
||||
if (!errorLock) {
|
||||
profileImg.src = defaultAvatar;
|
||||
errorLock = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Add click handler to profile picture
|
||||
profileImg.style.cursor = 'pointer';
|
||||
profileImg.addEventListener('click', () => {
|
||||
showUserProfileDialog(message.username);
|
||||
});
|
||||
|
||||
profilePicDiv.appendChild(profileImg);
|
||||
messageDiv.appendChild(profilePicDiv);
|
||||
}
|
||||
|
||||
if (!isAuthor) {
|
||||
const usernameDiv = document.createElement('div');
|
||||
usernameDiv.classList.add('message-username');
|
||||
usernameDiv.textContent = message.username;
|
||||
|
||||
// Add click handler to username
|
||||
usernameDiv.style.cursor = 'pointer';
|
||||
usernameDiv.addEventListener('click', () => {
|
||||
showUserProfileDialog(message.username);
|
||||
});
|
||||
|
||||
messageInner.appendChild(usernameDiv);
|
||||
}
|
||||
|
||||
// Add reply preview if this is a reply
|
||||
if (message.reply_to) {
|
||||
const replyDiv = document.createElement('div');
|
||||
replyDiv.classList.add('message-reply');
|
||||
replyDiv.innerHTML = `
|
||||
<div class="reply-content">
|
||||
<span class="reply-username">${message.reply_to.username}</span>
|
||||
<span class="reply-text">${message.reply_to.content}</span>
|
||||
</div>
|
||||
`;
|
||||
messageInner.appendChild(replyDiv);
|
||||
}
|
||||
|
||||
const contentDiv = document.createElement('div');
|
||||
contentDiv.classList.add('message-content');
|
||||
contentDiv.textContent = message.content;
|
||||
messageInner.appendChild(contentDiv);
|
||||
|
||||
const timeDiv = document.createElement('div');
|
||||
timeDiv.classList.add('message-time');
|
||||
|
||||
let timeText = formatTime(message.timestamp);
|
||||
if (message.is_edited) {
|
||||
timeText += ' (edited)';
|
||||
}
|
||||
timeDiv.textContent = timeText;
|
||||
|
||||
if (isAuthor && message.is_read) {
|
||||
const checkIcon = document.createElement('span');
|
||||
checkIcon.classList.add("material-symbols", "outlined");
|
||||
timeDiv.appendChild(checkIcon);
|
||||
}
|
||||
|
||||
messageInner.appendChild(timeDiv);
|
||||
messageDiv.appendChild(messageInner);
|
||||
messagesContainer.appendChild(messageDiv);
|
||||
|
||||
// Add right-click context menu
|
||||
messageDiv.addEventListener('contextmenu', (e) => {
|
||||
e.preventDefault();
|
||||
showContextMenu(message, e.clientX, e.clientY);
|
||||
});
|
||||
|
||||
// Прокрутка к новому сообщению
|
||||
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads chat messages from the server
|
||||
* @function loadMessages
|
||||
* @example
|
||||
* loadMessages();
|
||||
*/
|
||||
export function loadMessages(): void {
|
||||
fetch(`${API_BASE_URL}/get_messages`, {
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then((data: Messages) => {
|
||||
if (data.messages && data.messages.length > 0) {
|
||||
const messagesContainer = document.querySelector('.chat-messages') as HTMLElement;
|
||||
|
||||
const lastMessage = messagesContainer.lastElementChild as HTMLElement
|
||||
let lastMessageId: number = 0
|
||||
if (lastMessage) {
|
||||
lastMessageId = Number(lastMessage.dataset.id)
|
||||
}
|
||||
|
||||
// Добавляем только новые сообщения
|
||||
data.messages.forEach(msg => {
|
||||
if (msg.id > lastMessageId) {
|
||||
addMessage(msg, msg.username == currentUser!.username);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message via WebSocket
|
||||
* @function sendMessage
|
||||
* @example
|
||||
* sendMessage();
|
||||
*/
|
||||
export function sendMessage(): void {
|
||||
const input = document.querySelector('.message-input') as HTMLInputElement;
|
||||
const message = input.value.trim();
|
||||
|
||||
if (message) {
|
||||
const payload: WebSocketMessage = {
|
||||
data: {
|
||||
content: message
|
||||
},
|
||||
credentials: {
|
||||
scheme: "Bearer",
|
||||
credentials: authToken!
|
||||
},
|
||||
type: "sendMessage"
|
||||
}
|
||||
|
||||
let callback: ((e: MessageEvent) => void) | null = null
|
||||
callback = (e) => {
|
||||
websocket.removeEventListener("message", callback!);
|
||||
const response: WebSocketMessage = JSON.parse(e.data)
|
||||
console.log(response)
|
||||
if (!response.error) {
|
||||
input.value = "";
|
||||
}
|
||||
}
|
||||
websocket.addEventListener("message", callback);
|
||||
|
||||
websocket.send(JSON.stringify(payload));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
document.getElementById('message-form')!.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
});
|
||||
|
||||
/**
|
||||
* Updates an existing message in the chat interface
|
||||
* @param {Message} message - Updated message object
|
||||
* @function updateMessage
|
||||
*/
|
||||
export function updateMessage(message: Message): void {
|
||||
const messageElement = document.querySelector(`[data-id="${message.id}"]`) as HTMLElement;
|
||||
if (!messageElement) return;
|
||||
|
||||
const contentDiv = messageElement.querySelector('.message-content') as HTMLElement;
|
||||
const timeDiv = messageElement.querySelector('.message-time') as HTMLElement;
|
||||
|
||||
if (contentDiv) {
|
||||
contentDiv.textContent = message.content;
|
||||
}
|
||||
|
||||
if (timeDiv) {
|
||||
let timeText = formatTime(message.timestamp);
|
||||
if (message.is_edited) {
|
||||
timeText += ' (edited)';
|
||||
}
|
||||
timeDiv.textContent = timeText;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a message from the chat interface
|
||||
* @param {number} messageId - ID of the message to remove
|
||||
* @function removeMessage
|
||||
*/
|
||||
export function removeMessage(messageId: number): void {
|
||||
const messageElement = document.querySelector(`[data-id="${messageId}"]`) as HTMLElement;
|
||||
if (messageElement) {
|
||||
messageElement.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles WebSocket message updates
|
||||
* @param {WebSocketMessage} response - WebSocket response
|
||||
* @function handleWebSocketMessage
|
||||
*/
|
||||
export function handleWebSocketMessage(response: WebSocketMessage): void {
|
||||
switch (response.type) {
|
||||
case 'messageEdited':
|
||||
if (response.data) {
|
||||
updateMessage(response.data);
|
||||
}
|
||||
break;
|
||||
case 'messageDeleted':
|
||||
if (response.data && response.data.message_id) {
|
||||
removeMessage(response.data.message_id);
|
||||
}
|
||||
break;
|
||||
case 'newMessage':
|
||||
if (response.data) {
|
||||
const isAuthor = response.data.username === currentUser?.username;
|
||||
addMessage(response.data, isAuthor);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -6,22 +6,27 @@
|
||||
*/
|
||||
|
||||
/**
|
||||
* Base API endpoint for all backend requests
|
||||
* @type {string}
|
||||
* Base domain name for all requests in production
|
||||
* @constant
|
||||
*/
|
||||
export const API_BASE_URL: string = '/api';
|
||||
export const BASE_DOMAIN = import.meta.env.VITE_API_BASE_URL ?? "fromchat.ru";
|
||||
|
||||
/**
|
||||
* Base API endpoint for all backend requests
|
||||
* @constant
|
||||
*/
|
||||
export const API_BASE_URL = `${location.host ? "" : `https://${BASE_DOMAIN}`}/api`;
|
||||
|
||||
/**
|
||||
* Full API URL including hostname and port for WebSocket connections
|
||||
* @type {string}
|
||||
* @constant
|
||||
*/
|
||||
export const API_FULL_BASE_URL: string = `${location.host}/api`;
|
||||
export const API_WS_BASE_URL = `${location.host || BASE_DOMAIN}/api`;
|
||||
|
||||
/**
|
||||
* Application name displayed in UI and document title
|
||||
* @type {string}
|
||||
* @constant
|
||||
*/
|
||||
export const PRODUCT_NAME: string = "FromChat";
|
||||
export const PRODUCT_NAME = "FromChat";
|
||||
|
||||
export const MINIMUM_WIDTH = 800;
|
||||
@@ -5,9 +5,8 @@
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { showLogin } from "./auth";
|
||||
import { PRODUCT_NAME } from "./config";
|
||||
import { enableMapSet } from "immer";
|
||||
|
||||
showLogin();
|
||||
document.getElementById("productname")!.textContent = PRODUCT_NAME;
|
||||
document.title = PRODUCT_NAME;
|
||||
document.title = PRODUCT_NAME;
|
||||
enableMapSet();
|
||||
+180
-2
@@ -5,6 +5,7 @@
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* HTTP headers object type
|
||||
* @typedef {Object.<string, string>} Headers
|
||||
@@ -31,6 +32,11 @@ export interface Size2D {
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface Rect extends Size2D {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// App types
|
||||
|
||||
/**
|
||||
@@ -54,6 +60,11 @@ export interface Message {
|
||||
timestamp: string;
|
||||
profile_picture?: string;
|
||||
reply_to?: Message;
|
||||
files?: Attachment[];
|
||||
|
||||
runtimeData?: {
|
||||
dmEnvelope?: DmEnvelope;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,6 +94,7 @@ export interface User {
|
||||
username: string;
|
||||
admin?: boolean;
|
||||
bio?: string;
|
||||
profile_picture: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -136,6 +148,20 @@ export interface RegisterRequest {
|
||||
confirm_password: string;
|
||||
}
|
||||
|
||||
export interface UploadPublicKeyRequest {
|
||||
publicKey: string;
|
||||
}
|
||||
|
||||
export interface SendDMRequest {
|
||||
recipientId: number;
|
||||
iv: string;
|
||||
ciphertext: string;
|
||||
salt: string;
|
||||
iv2: string;
|
||||
wrappedMk: string;
|
||||
replyToId?: number;
|
||||
}
|
||||
|
||||
// Responses
|
||||
|
||||
/**
|
||||
@@ -149,6 +175,58 @@ export interface LoginResponse {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface BackupBlob {
|
||||
blob: string;
|
||||
}
|
||||
|
||||
export interface BaseDmEnvelope {
|
||||
iv: string;
|
||||
ciphertext: string;
|
||||
salt: string;
|
||||
iv2: string;
|
||||
wrappedMk: string;
|
||||
recipientId: number;
|
||||
}
|
||||
|
||||
export interface DmEnvelope extends BaseDmEnvelope {
|
||||
id: number;
|
||||
senderId: number;
|
||||
files?: DmFile[];
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface DmFile {
|
||||
name: string;
|
||||
id: number;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface DmEditedPayload {
|
||||
id: number;
|
||||
iv: string;
|
||||
ciphertext: string;
|
||||
timestamp: string
|
||||
}
|
||||
|
||||
export interface DmDeletedPayload {
|
||||
id: number;
|
||||
senderId: number;
|
||||
recipientId: number
|
||||
}
|
||||
|
||||
export interface FetchDMResponse {
|
||||
messages: DmEnvelope[]
|
||||
}
|
||||
|
||||
export interface DmEncryptedJSON {
|
||||
type: "text",
|
||||
data: {
|
||||
content: string;
|
||||
reply_to_id?: number;
|
||||
files?: Attachment[];
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------
|
||||
// WebSocket types
|
||||
// ---------------
|
||||
@@ -161,10 +239,10 @@ export interface LoginResponse {
|
||||
* @property {any} [data] - Message payload data
|
||||
* @property {WebSocketError} [error] - Error information if applicable
|
||||
*/
|
||||
export interface WebSocketMessage {
|
||||
export interface WebSocketMessage<T> {
|
||||
type: string;
|
||||
credentials?: WebSocketCredentials;
|
||||
data?: any;
|
||||
data?: T;
|
||||
error?: WebSocketError;
|
||||
}
|
||||
|
||||
@@ -188,4 +266,104 @@ export interface WebSocketError {
|
||||
export interface WebSocketCredentials {
|
||||
scheme: string;
|
||||
credentials: string;
|
||||
}
|
||||
|
||||
export interface Attachment {
|
||||
path: string;
|
||||
encrypted: boolean;
|
||||
name: string;
|
||||
}
|
||||
|
||||
// -----------------------
|
||||
// WebSocket message types
|
||||
// -----------------------
|
||||
|
||||
// Utils
|
||||
export interface DMEditPayload {
|
||||
id: number;
|
||||
iv: string;
|
||||
ciphertext: string;
|
||||
iv2: string;
|
||||
wrappedMk: string;
|
||||
salt: string;
|
||||
}
|
||||
|
||||
// Requests
|
||||
export interface DMEditRequest extends WebSocketMessage {
|
||||
type: "dmEdit",
|
||||
credentials: WebSocketCredentials;
|
||||
data: DMEditPayload
|
||||
}
|
||||
|
||||
export interface SendMessageRequest extends WebSocketMessage {
|
||||
type: "sendMessage",
|
||||
credentials: WebSocketCredentials;
|
||||
data: {
|
||||
content: string;
|
||||
reply_to_id: number | null;
|
||||
}
|
||||
}
|
||||
|
||||
// Messages
|
||||
export interface DMNewWebSocketMessage extends WebSocketMessage {
|
||||
type: "dmNew",
|
||||
data: DmEnvelope
|
||||
}
|
||||
|
||||
export interface DMEditedWebSocketMessage extends WebSocketMessage {
|
||||
type: "dmEdited",
|
||||
data: DMEditPayload
|
||||
}
|
||||
|
||||
export interface DMDeletedWebSocketMessage extends WebSocketMessage {
|
||||
type: "dmDeleted",
|
||||
data: {
|
||||
id: number;
|
||||
}
|
||||
}
|
||||
|
||||
export interface MessageEditedWebSocketMessage extends WebSocketMessage {
|
||||
type: "messageEdited",
|
||||
data: Partial<Message> & { id: number }
|
||||
}
|
||||
|
||||
export interface MessageDeletedWebSocketMessage extends WebSocketMessage {
|
||||
type: "messageDeleted",
|
||||
data: {
|
||||
message_id: number;
|
||||
}
|
||||
}
|
||||
|
||||
export interface NewMessageWebSocketMessage extends WebSocketMessage {
|
||||
type: "newMessage",
|
||||
data: Message
|
||||
}
|
||||
|
||||
// Shared types
|
||||
export type DMWebSocketMessage = DMNewWebSocketMessage | DMEditedWebSocketMessage | DMDeletedWebSocketMessage
|
||||
export type ChatWebSocketMessage = MessageEditedWebSocketMessage | MessageDeletedWebSocketMessage | NewMessageWebSocketMessage
|
||||
|
||||
// -----------
|
||||
// Encrypted message JSON (plaintext structure before encryption)
|
||||
// -----------
|
||||
|
||||
export type ChatMessageKind = "text"; // Extendable for future kinds
|
||||
|
||||
export interface EncryptedTextMessageData {
|
||||
content: string;
|
||||
files?: Attachment[];
|
||||
reply_to_id?: number | null;
|
||||
}
|
||||
|
||||
export interface EncryptedMessageJson {
|
||||
type: ChatMessageKind;
|
||||
data: EncryptedTextMessageData;
|
||||
}
|
||||
|
||||
// -----------
|
||||
// React types
|
||||
// -----------
|
||||
export interface DialogProps {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (value: boolean) => void;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* @fileoverview WebSocket connection management for real-time chat
|
||||
* @description Handles WebSocket connections, message processing, and auto-reconnection
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { API_WS_BASE_URL } from "./config";
|
||||
import type { WebSocketMessage } from "./types";
|
||||
import { delay } from "../utils/utils";
|
||||
|
||||
/**
|
||||
* Creates a new WebSocket connection to the chat server
|
||||
* @returns {WebSocket} New WebSocket instance
|
||||
* @private
|
||||
*/
|
||||
function create(): WebSocket {
|
||||
let prefix = "ws://";
|
||||
if (location.protocol.includes("https")) {
|
||||
prefix = "wss://";
|
||||
}
|
||||
|
||||
return new WebSocket(`${prefix}${API_WS_BASE_URL}/chat/ws`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Global WebSocket instance
|
||||
* @type {WebSocket}
|
||||
*/
|
||||
export let websocket: WebSocket = create();
|
||||
|
||||
/**
|
||||
* Global WebSocket message handler reference
|
||||
* This will be set by the active panel to handle incoming messages
|
||||
*/
|
||||
let globalMessageHandler: ((response: WebSocketMessage<any>) => void) | null = null;
|
||||
|
||||
/**
|
||||
* Set the global WebSocket message handler
|
||||
* @param handler - Function to handle WebSocket messages
|
||||
*/
|
||||
export function setGlobalMessageHandler(handler: ((response: WebSocketMessage<any>) => void) | null): void {
|
||||
globalMessageHandler = handler;
|
||||
}
|
||||
|
||||
export function request<Request, Response = any>(payload: WebSocketMessage<Request>): Promise<WebSocketMessage<Response>> {
|
||||
console.log("WebSocket request:", payload);
|
||||
return new Promise((resolve, reject) => {
|
||||
function requestInner() {
|
||||
let listener: ((e: MessageEvent) => void) | null = null;
|
||||
listener = (e) => {
|
||||
resolve(JSON.parse(e.data));
|
||||
websocket.removeEventListener("message", listener!);
|
||||
}
|
||||
websocket.addEventListener("message", listener);
|
||||
websocket.send(JSON.stringify(payload))
|
||||
|
||||
setTimeout(() => reject("Request timed out"), 10000);
|
||||
}
|
||||
|
||||
if (websocket.readyState == 0) {
|
||||
websocket.addEventListener("open", requestInner);
|
||||
setTimeout(() => reject("Request timed out"), 10000);
|
||||
} else {
|
||||
requestInner();
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* This function will wait 3 seconds and them attempts to reconnect the WebSocket.
|
||||
* If it fails, tries again in an endless loop until the connection is established
|
||||
* again.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
async function onError() {
|
||||
console.warn("WebSocket disconnected, retrying in 3 seconds...");
|
||||
await delay(3000);
|
||||
websocket = create();
|
||||
|
||||
let listener: () => void | null;
|
||||
listener = () => {
|
||||
console.log("WebSocket successfully reconnected!");
|
||||
websocket.removeEventListener("open", listener);
|
||||
}
|
||||
|
||||
websocket.addEventListener("open", listener);
|
||||
websocket.addEventListener("error", onError);
|
||||
}
|
||||
|
||||
// --------------
|
||||
// Initialization
|
||||
// --------------
|
||||
|
||||
websocket.addEventListener("message", (e) => {
|
||||
try {
|
||||
const response: WebSocketMessage<any> = JSON.parse(e.data);
|
||||
|
||||
// Route message to global handler if set
|
||||
if (globalMessageHandler) {
|
||||
globalMessageHandler(response);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error parsing WebSocket message:", error);
|
||||
}
|
||||
});
|
||||
websocket.addEventListener("error", onError);
|
||||
@@ -1,342 +0,0 @@
|
||||
@use "common/colors" as *;
|
||||
@use "common/material" as *;
|
||||
|
||||
#chat-interface {
|
||||
height: 100%;
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
background-color: $color-dark-surface-container;
|
||||
color: white;
|
||||
padding: 16px 16px;
|
||||
justify-content: end;
|
||||
width: fit-content;
|
||||
z-index: 1000;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
|
||||
.header-content {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
|
||||
.logo {
|
||||
font-size: 1.8rem;
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#logouts {
|
||||
display: none;
|
||||
list-style: none;
|
||||
gap: 10px;
|
||||
|
||||
li {
|
||||
a {
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
transition: all 0.3s ease;
|
||||
padding: 10px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chat-container {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
|
||||
.chat-main {
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
|
||||
.chat-header {
|
||||
padding: 16px;
|
||||
background: $color-dark-surface-container;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
box-shadow: black 0 0 20px;
|
||||
|
||||
.chat-header-avatar {
|
||||
width: 45px;
|
||||
height: 45px;
|
||||
border-radius: 20%;
|
||||
object-fit: cover;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
|
||||
.chat-header-info {
|
||||
display: flex;
|
||||
|
||||
.info-chat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
h4 {
|
||||
font-size: 1.1rem;
|
||||
margin: 0 0 0.2rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
color: #718096;
|
||||
}
|
||||
}
|
||||
|
||||
.online-status {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background-color: $success;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
a {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
text-decoration: none;
|
||||
color: white;
|
||||
justify-content: end;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
position: absolute;
|
||||
right: 2%;
|
||||
top: 2%;
|
||||
|
||||
&:hover {
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
padding: 1rem;
|
||||
overflow-y: auto;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 7px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background-color: $color-dark-surface-container-high;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-bottom: 1rem;
|
||||
max-width: 70%;
|
||||
position: relative;
|
||||
width: fit-content;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 8px;
|
||||
|
||||
.message-profile-pic {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
flex-shrink: 0;
|
||||
margin-bottom: 4px;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.message-inner {
|
||||
padding: 0.8rem 1rem;
|
||||
border-radius: 12px;
|
||||
position: relative;
|
||||
word-wrap: break-word;
|
||||
|
||||
.message-content {
|
||||
word-wrap: break-word;
|
||||
margin-bottom: 0.3rem;
|
||||
}
|
||||
|
||||
.message-reply {
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
border-left: 3px solid $color-dark-primary;
|
||||
|
||||
.reply-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
|
||||
.reply-username {
|
||||
font-weight: 600;
|
||||
font-size: 0.8rem;
|
||||
color: $color-dark-primary;
|
||||
}
|
||||
|
||||
.reply-text {
|
||||
font-size: 0.85rem;
|
||||
color: $color-dark-on-surface-variant;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 200px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.message-time {
|
||||
font-size: 0.7rem;
|
||||
color: $color-dark-on-surface-variant;
|
||||
margin-top: 0.3rem;
|
||||
text-align: right;
|
||||
}
|
||||
}
|
||||
|
||||
&.received .message-inner {
|
||||
background-color: $color-dark-surface-container;
|
||||
border-top-left-radius: 5px;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
&.sent {
|
||||
margin-left: auto;
|
||||
flex-direction: row-reverse;
|
||||
|
||||
.message-inner {
|
||||
background-color: $color-dark-primary-container;
|
||||
color: $color-dark-on-primary-container;
|
||||
border-top-right-radius: 5px;
|
||||
}
|
||||
|
||||
.message-time {
|
||||
color: $color-dark-on-primary-container;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.message-username {
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.3rem;
|
||||
font-size: 0.9rem;
|
||||
transition: color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: $color-dark-primary;
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chat-input-wrapper {
|
||||
position: relative;
|
||||
|
||||
&::before {
|
||||
$height: 20px;
|
||||
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -$height;
|
||||
left: 0;
|
||||
right: 0;
|
||||
width: 100%;
|
||||
height: $height;
|
||||
background: linear-gradient(
|
||||
0deg,
|
||||
$color-dark-surface,
|
||||
rgba(255, 255, 255, 0),
|
||||
);
|
||||
}
|
||||
|
||||
.chat-input {
|
||||
margin: 0 20px 20px 20px;
|
||||
background-color: $color-dark-surface-container;
|
||||
border-radius: 40px;
|
||||
|
||||
.input-group {
|
||||
display: flex;
|
||||
|
||||
.message-input {
|
||||
flex: 1;
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 25px;
|
||||
font-size: 1rem;
|
||||
outline: none;
|
||||
background-color: inherit;
|
||||
caret-color: $color-dark-primary;
|
||||
color: $color-dark-on-surface;
|
||||
}
|
||||
|
||||
.send-btn {
|
||||
margin: 10px;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
background-color: $color-dark-primary;
|
||||
color: $color-dark-on-primary;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background-color 0.25s ease;
|
||||
|
||||
@include hoverStateLayer($background: $color-dark-primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reply preview styles
|
||||
.reply-preview {
|
||||
background-color: $color-dark-surface;
|
||||
border-radius: 8px;
|
||||
padding: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
border-left: 3px solid $color-dark-primary;
|
||||
|
||||
.reply-preview-content {
|
||||
color: $color-dark-on-surface-variant;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.4;
|
||||
|
||||
strong {
|
||||
color: $color-dark-primary;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.fade-in {
|
||||
animation: fadeIn 0.3s ease forwards;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import "../electron.d.ts";
|
||||
import { PRODUCT_NAME } from "./config";
|
||||
|
||||
if (window.electronInterface !== undefined) {
|
||||
console.log("Running in Electron");
|
||||
document.documentElement.classList.add("electron", `platform-${window.electronInterface.platform}`);
|
||||
document.getElementById("window-title")!.textContent = PRODUCT_NAME;
|
||||
} else {
|
||||
console.log("Running in normal browser");
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* @fileoverview Electron-specific code
|
||||
* @description This module initializes Electron-specific functionality.
|
||||
* @author denis0001-dev
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
export const isElectron = import.meta.env.VITE_ELECTRON && window.electronInterface != undefined;
|
||||
|
||||
if (isElectron) {
|
||||
console.log("Running in Electron");
|
||||
document.documentElement.classList.add("electron", `platform-${window.electronInterface.platform}`);
|
||||
} else {
|
||||
console.log("Running in normal browser");
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Left panel UI controls and interactions
|
||||
* @description Handles chat collapse/expand, chat switching, and profile dialog
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import type { Dialog } from "mdui/components/dialog";
|
||||
import { loadProfilePicture } from "./profile/upload";
|
||||
|
||||
// сварачивание и разворачивание чата
|
||||
const chatCollapseBtn = document.getElementById('hide-chat')!;
|
||||
const chat1 = document.getElementById('chat-list-chat-1')!;
|
||||
const chat2 = document.getElementById('chat-list-chat-2')!;
|
||||
const chatInner = document.getElementById('chat-inner')!;
|
||||
const chatName = document.getElementById('chat-name')!;
|
||||
const profileButton = document.getElementById('profile-open')!;
|
||||
const dialog = document.getElementById("profile-dialog") as Dialog;
|
||||
const dialogClose = document.getElementById("profile-dialog-close")!;
|
||||
|
||||
/**
|
||||
* Sets up chat collapse functionality
|
||||
* @function setupChatCollapse
|
||||
* @private
|
||||
*/
|
||||
function setupChatCollapse(): void {
|
||||
chatCollapseBtn.addEventListener('click', () => {
|
||||
chatCollapseBtn.style.display = 'none';
|
||||
chatInner.style.display = 'none';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up chat switching functionality
|
||||
* @function setupChatSwitching
|
||||
* @private
|
||||
*/
|
||||
function setupChatSwitching(): void {
|
||||
chat1.addEventListener('click', () => {
|
||||
chatCollapseBtn.style.display = 'flex';
|
||||
chatInner.style.display = 'flex';
|
||||
chatName.textContent = 'общий чат';
|
||||
});
|
||||
|
||||
chat2.addEventListener('click', () => {
|
||||
chatCollapseBtn.style.display = 'flex';
|
||||
chatInner.style.display = 'flex';
|
||||
chatName.textContent = 'общий чат 2';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up profile dialog functionality
|
||||
* @function setupProfileDialog
|
||||
* @private
|
||||
*/
|
||||
function setupProfileDialog(): void {
|
||||
profileButton.addEventListener('click', () => {
|
||||
dialog.open = true;
|
||||
loadProfilePicture();
|
||||
});
|
||||
|
||||
dialogClose.addEventListener("click", () => {
|
||||
dialog.open = false;
|
||||
});
|
||||
}
|
||||
|
||||
setupChatCollapse();
|
||||
setupChatSwitching();
|
||||
setupProfileDialog();
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Application entry point for FromChat frontend
|
||||
* @description Main module that initializes all required components and styles
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import './css/style.scss';
|
||||
import "mdui/mdui.css";
|
||||
|
||||
import "./utils/material";
|
||||
import "./chat";
|
||||
import "./settings";
|
||||
import "./leftpanel";
|
||||
import "./init";
|
||||
import "./profile";
|
||||
import "./message-context-menu";
|
||||
import "./user-profile-dialog";
|
||||
import "./electron";
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* @fileoverview Application entry point for FromChat frontend
|
||||
* @description Main module that initializes all required components and styles
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import './resources/css/style.scss';
|
||||
import "mdui/mdui.css";
|
||||
|
||||
import "./utils/material";
|
||||
import "./core/init";
|
||||
import "./electron/electron";
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import App from './ui/App';
|
||||
import { StrictMode } from 'react';
|
||||
|
||||
// Initialize React app
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
);
|
||||
@@ -1,338 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Message context menu functionality
|
||||
* @description Handles right-click context menu for message actions (edit, delete, reply)
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { currentUser, authToken } from "./auth";
|
||||
import { websocket } from "./websocket";
|
||||
import type { Message, WebSocketMessage } from "./types";
|
||||
import { showSuccess, showError } from "./utils/notification";
|
||||
import { delay } from "./utils/utils";
|
||||
import type { Dialog } from "mdui/components/dialog";
|
||||
import type { TextField } from "mdui/components/text-field";
|
||||
|
||||
|
||||
let menu = document.getElementById("message-context-menu")!;
|
||||
let editDialog = document.getElementById("edit-message-dialog") as Dialog;
|
||||
let replyDialog = document.getElementById("reply-message-dialog") as Dialog;
|
||||
let currentMessage: Message | null = null;
|
||||
|
||||
function init() {
|
||||
bindEvents();
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds event listeners
|
||||
* @private
|
||||
*/
|
||||
function bindEvents(): void {
|
||||
// Context menu events
|
||||
menu?.addEventListener('click', (e) => {
|
||||
const target = e.target as HTMLElement;
|
||||
const action = target.closest('.context-menu-item')?.getAttribute('data-action');
|
||||
|
||||
if (action && currentMessage) {
|
||||
handleAction(action, currentMessage);
|
||||
}
|
||||
});
|
||||
|
||||
// Close menu when clicking outside
|
||||
document.addEventListener('click', (e) => {
|
||||
if (!menu?.contains(e.target as Node)) {
|
||||
hide();
|
||||
}
|
||||
});
|
||||
|
||||
// Edit dialog events
|
||||
const editCancelBtn = editDialog?.querySelector('#edit-cancel');
|
||||
const editSaveBtn = editDialog?.querySelector('#edit-save');
|
||||
|
||||
editCancelBtn?.addEventListener('click', () => hideEditDialog());
|
||||
editSaveBtn?.addEventListener('click', () => saveEdit());
|
||||
|
||||
// Reply dialog events
|
||||
const replyCancelBtn = replyDialog?.querySelector('#reply-cancel');
|
||||
const replySendBtn = replyDialog?.querySelector('#reply-send');
|
||||
|
||||
replyCancelBtn?.addEventListener('click', () => hideReplyDialog());
|
||||
replySendBtn?.addEventListener('click', () => sendReply());
|
||||
|
||||
// Keyboard shortcuts
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
hide();
|
||||
hideEditDialog();
|
||||
hideReplyDialog();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the context menu at the specified position
|
||||
* @param {Message} message - The message to show menu for
|
||||
* @param {number} x - X coordinate
|
||||
* @param {number} y - Y coordinate
|
||||
*/
|
||||
export function show(message: Message, x: number, y: number): void {
|
||||
currentMessage = message;
|
||||
|
||||
// Show delete for own messages and for owner on any message
|
||||
const editItem = menu.querySelector('[data-action="edit"]') as HTMLElement;
|
||||
const deleteItem = menu.querySelector('[data-action="delete"]') as HTMLElement;
|
||||
|
||||
const isAuthor = message.username === currentUser?.username;
|
||||
const isOwner = !!currentUser?.admin;
|
||||
|
||||
editItem.style.display = isAuthor ? 'flex' : 'none';
|
||||
deleteItem.style.display = (isAuthor || isOwner) ? 'flex' : 'none';
|
||||
|
||||
// Position the menu properly
|
||||
menu.style.display = 'block';
|
||||
|
||||
let menuWidth = menu.offsetWidth;
|
||||
let menuHeight = menu.offsetHeight;
|
||||
|
||||
let adjustedX = x;
|
||||
let adjustedY = y;
|
||||
let vertical = "top";
|
||||
let horizontal = "right";
|
||||
|
||||
// Adjust horizontal position if menu would go off-screen
|
||||
if (x + menuWidth > window.innerWidth) {
|
||||
adjustedX = x - menuWidth;
|
||||
horizontal = "left";
|
||||
}
|
||||
|
||||
// Adjust vertical position if menu would go off-screen
|
||||
if (y + menuHeight > window.innerHeight) {
|
||||
adjustedY = y - menuHeight;
|
||||
vertical = "bottom";
|
||||
}
|
||||
|
||||
// Ensure menu doesn't go off the left or top edges
|
||||
adjustedX = Math.max(0, adjustedX);
|
||||
adjustedY = Math.max(0, adjustedY);
|
||||
|
||||
menu.style.left = `${adjustedX}px`;
|
||||
menu.style.top = `${adjustedY}px`;
|
||||
menu.classList.add(`pos-${vertical}-${horizontal}`, "open");
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides the context menu
|
||||
*/
|
||||
export function hide(): void {
|
||||
menu.style.display = 'none';
|
||||
menu.classList.forEach((name) => {
|
||||
if (name.match(/pos-\w+-\w+/)) {
|
||||
menu.classList.remove(name);
|
||||
}
|
||||
})
|
||||
currentMessage = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles context menu actions
|
||||
* @param {string} action - The action to perform
|
||||
* @param {Message} message - The message to act on
|
||||
* @private
|
||||
*/
|
||||
function handleAction(action: string, message: Message): void {
|
||||
hide();
|
||||
|
||||
switch (action) {
|
||||
case 'edit':
|
||||
showEditDialog(message);
|
||||
break;
|
||||
case 'delete':
|
||||
deleteMessage(message);
|
||||
break;
|
||||
case 'reply':
|
||||
showReplyDialog(message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the edit dialog
|
||||
* @param {Message} message - The message to edit
|
||||
* @private
|
||||
*/
|
||||
async function showEditDialog(message: Message): Promise<void> {
|
||||
const textField = editDialog.querySelector('#edit-message-input') as TextField;
|
||||
textField.value = message.content;
|
||||
|
||||
currentMessage = message;
|
||||
editDialog.open = true;
|
||||
|
||||
// Focus the text field
|
||||
await delay(100);
|
||||
textField?.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides the edit dialog
|
||||
* @private
|
||||
*/
|
||||
function hideEditDialog(): void {
|
||||
editDialog.open = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the edited message
|
||||
* @private
|
||||
*/
|
||||
function saveEdit(): void {
|
||||
if (!currentMessage) return;
|
||||
|
||||
const textField = editDialog.querySelector('#edit-message-input') as TextField;
|
||||
const newContent = textField?.value?.trim() || '';
|
||||
|
||||
if (!newContent) {
|
||||
showError('Message cannot be empty');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: WebSocketMessage = {
|
||||
type: "editMessage",
|
||||
data: {
|
||||
message_id: currentMessage.id,
|
||||
content: newContent
|
||||
},
|
||||
credentials: {
|
||||
scheme: "Bearer",
|
||||
credentials: authToken!
|
||||
}
|
||||
};
|
||||
|
||||
let callback: ((e: MessageEvent) => void) | null = null;
|
||||
callback = (e) => {
|
||||
websocket.removeEventListener("message", callback!);
|
||||
const response: WebSocketMessage = JSON.parse(e.data);
|
||||
|
||||
if (response.error) {
|
||||
showError(response.error.detail);
|
||||
} else {
|
||||
showSuccess('Message edited successfully');
|
||||
hideEditDialog();
|
||||
}
|
||||
};
|
||||
websocket.addEventListener("message", callback);
|
||||
websocket.send(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the reply dialog
|
||||
* @param {Message} message - The message to reply to
|
||||
* @private
|
||||
*/
|
||||
async function showReplyDialog(message: Message): Promise<void> {
|
||||
const preview = replyDialog.querySelector('#reply-preview') as HTMLElement;
|
||||
preview.innerHTML = `
|
||||
<div class="reply-preview-content">
|
||||
<strong>${message.username}</strong>: ${message.content}
|
||||
</div>
|
||||
`;
|
||||
|
||||
currentMessage = message;
|
||||
replyDialog.open = true;
|
||||
|
||||
// Focus the text field
|
||||
await delay(100);
|
||||
const textField = replyDialog?.querySelector('#reply-message-input') as TextField;
|
||||
textField?.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides the reply dialog
|
||||
* @private
|
||||
*/
|
||||
function hideReplyDialog(): void {
|
||||
replyDialog.open = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the reply message
|
||||
* @private
|
||||
*/
|
||||
function sendReply(): void {
|
||||
if (!currentMessage) return;
|
||||
|
||||
const textField = replyDialog.querySelector('#reply-message-input') as TextField;
|
||||
const content = textField?.value?.trim() || '';
|
||||
|
||||
if (!content) {
|
||||
showError('Reply cannot be empty');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: WebSocketMessage = {
|
||||
type: "replyMessage",
|
||||
data: {
|
||||
content: content,
|
||||
reply_to_id: currentMessage.id
|
||||
},
|
||||
credentials: {
|
||||
scheme: "Bearer",
|
||||
credentials: authToken!
|
||||
}
|
||||
};
|
||||
|
||||
let callback: ((e: MessageEvent) => void) | null = null;
|
||||
callback = (e) => {
|
||||
websocket.removeEventListener("message", callback!);
|
||||
const response: WebSocketMessage = JSON.parse(e.data);
|
||||
|
||||
if (response.error) {
|
||||
showError(response.error.detail);
|
||||
} else {
|
||||
showSuccess('Reply sent successfully');
|
||||
hideReplyDialog();
|
||||
if (textField) {
|
||||
textField.value = '';
|
||||
}
|
||||
}
|
||||
};
|
||||
websocket.addEventListener("message", callback);
|
||||
websocket.send(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a message
|
||||
* @param {Message} message - The message to delete
|
||||
* @private
|
||||
*/
|
||||
function deleteMessage(message: Message): void {
|
||||
if (!confirm('Are you sure you want to delete this message?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: WebSocketMessage = {
|
||||
type: "deleteMessage",
|
||||
data: {
|
||||
message_id: message.id
|
||||
},
|
||||
credentials: {
|
||||
scheme: "Bearer",
|
||||
credentials: authToken!
|
||||
}
|
||||
};
|
||||
|
||||
let callback: ((e: MessageEvent) => void) | null = null;
|
||||
callback = (e) => {
|
||||
websocket.removeEventListener("message", callback!);
|
||||
const response: WebSocketMessage = JSON.parse(e.data);
|
||||
|
||||
if (response.error) {
|
||||
showError(response.error.detail);
|
||||
} else {
|
||||
showSuccess('Message deleted successfully');
|
||||
}
|
||||
};
|
||||
websocket.addEventListener("message", callback);
|
||||
websocket.send(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
init();
|
||||
@@ -1,44 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Profile module entry point and initialization
|
||||
* @description Coordinates profile system initialization and form handling
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import type { Dialog } from "mdui/components/dialog";
|
||||
import { loadProfileData } from './profile/editor';
|
||||
import { loadProfilePicture, initializeProfileUpload } from "./profile/upload";
|
||||
import { initializeProfileEditor } from './profile/editor';
|
||||
|
||||
// Handle profile form submission
|
||||
const form = document.getElementById("profile-form")!;
|
||||
const dialog = document.getElementById("profile-dialog") as Dialog;
|
||||
|
||||
form.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
// TODO: Process form data if needed
|
||||
// For now, just close the dialog
|
||||
dialog.open = false;
|
||||
});
|
||||
|
||||
/**
|
||||
* Initializes profile functionality after user login
|
||||
* @function initializeProfile
|
||||
* @example
|
||||
* // Called after successful authentication
|
||||
* initializeProfile();
|
||||
*/
|
||||
export function initializeProfile(): void {
|
||||
// Initialize profile modules
|
||||
initializeProfileUpload();
|
||||
initializeProfileEditor();
|
||||
|
||||
// Load profile data
|
||||
Promise.all([
|
||||
loadProfilePicture(),
|
||||
loadProfileData()
|
||||
]).catch(error => {
|
||||
console.error('Error initializing profile:', error);
|
||||
});
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Profile-related API calls
|
||||
* @description Handles all profile-related HTTP requests to the backend
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { getAuthHeaders } from '../auth';
|
||||
import type { ProfileData, UploadResponse } from './types';
|
||||
|
||||
/**
|
||||
* Loads user profile data from the server
|
||||
* @async
|
||||
* @function loadProfile
|
||||
* @returns {Promise<ProfileData | null>} User profile data or null if failed
|
||||
* @example
|
||||
* const profile = await loadProfile();
|
||||
* if (profile) {
|
||||
* console.log('User nickname:', profile.nickname);
|
||||
* }
|
||||
*/
|
||||
export async function loadProfile(): Promise<ProfileData | null> {
|
||||
try {
|
||||
const response = await fetch('/api/user/profile', {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Error loading profile:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads a profile picture to the server
|
||||
* @async
|
||||
* @function uploadProfilePicture
|
||||
* @param {Blob} file - The image file to upload
|
||||
* @returns {Promise<UploadResponse | null>} Upload response with URL or null if failed
|
||||
* @example
|
||||
* const fileInput = document.getElementById('file-input');
|
||||
* const file = fileInput.files[0];
|
||||
* const result = await uploadProfilePicture(file);
|
||||
* if (result) {
|
||||
* console.log('Uploaded to:', result.profile_picture_url);
|
||||
* }
|
||||
*/
|
||||
export async function uploadProfilePicture(file: Blob): Promise<UploadResponse | null> {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('profile_picture', file, 'profile_picture.jpg');
|
||||
|
||||
const response = await fetch('/api/upload-profile-picture', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: getAuthHeaders(false)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Upload error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates user profile information
|
||||
* @async
|
||||
* @function updateProfile
|
||||
* @param {Partial<ProfileData>} data - Profile data to update
|
||||
* @returns {Promise<boolean>} True if update was successful, false otherwise
|
||||
* @example
|
||||
* const success = await updateProfile({
|
||||
* nickname: 'New Name',
|
||||
* description: 'Updated bio'
|
||||
* });
|
||||
* if (success) {
|
||||
* console.log('Profile updated successfully');
|
||||
* }
|
||||
*/
|
||||
export async function updateProfile(data: Partial<ProfileData>): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch('/api/user/profile', {
|
||||
method: 'PUT',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
console.error('Error updating profile:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates user bio
|
||||
* @async
|
||||
* @function updateBio
|
||||
* @param {string} bio - New bio text
|
||||
* @returns {Promise<boolean>} True if update was successful, false otherwise
|
||||
* @example
|
||||
* const success = await updateBio('My new bio text');
|
||||
* if (success) {
|
||||
* console.log('Bio updated successfully');
|
||||
* }
|
||||
*/
|
||||
export async function updateBio(bio: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch('/api/user/bio', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ bio })
|
||||
});
|
||||
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
console.error('Error updating bio:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Profile editing functionality
|
||||
* @description Handles profile form editing and MDUI text field integration
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { updateProfile } from './api';
|
||||
import { loadProfile } from './api';
|
||||
import { showSuccess, showError } from '../utils/notification';
|
||||
import type { TextField } from 'mdui/components/text-field';
|
||||
|
||||
let profileForm = document.getElementById('profile-form')!;
|
||||
let nicknameField = document.getElementById('username-field') as unknown as TextField;
|
||||
let descriptionField = document.getElementById('description-field') as unknown as TextField;
|
||||
|
||||
/**
|
||||
* Initialization state flag
|
||||
* @type {boolean}
|
||||
*/
|
||||
let isInitialized = false;
|
||||
|
||||
/**
|
||||
* Sets the username field value
|
||||
* @param {string} value - The username value to set
|
||||
* @function setUsernameValue
|
||||
* @example
|
||||
* setUsernameValue('John Doe');
|
||||
*/
|
||||
export function setUsernameValue(value: string): void {
|
||||
if (nicknameField && nicknameField.value !== undefined) {
|
||||
nicknameField.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the description field value
|
||||
* @param {string} value - The description value to set
|
||||
* @function setDescriptionValue
|
||||
* @example
|
||||
* setDescriptionValue('Software Developer');
|
||||
*/
|
||||
export function setDescriptionValue(value: string): void {
|
||||
if (descriptionField && descriptionField.value !== undefined) {
|
||||
descriptionField.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current username field value
|
||||
* @returns {string} The current username value
|
||||
* @function getUsernameValue
|
||||
* @example
|
||||
* const username = getUsernameValue();
|
||||
* console.log('Current username:', username);
|
||||
*/
|
||||
export function getUsernameValue(): string {
|
||||
if (nicknameField && nicknameField.value !== undefined) {
|
||||
return nicknameField.value;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current description field value
|
||||
* @returns {string} The current description value
|
||||
* @function getDescriptionValue
|
||||
* @example
|
||||
* const description = getDescriptionValue();
|
||||
* console.log('Current description:', description);
|
||||
*/
|
||||
export function getDescriptionValue(): string {
|
||||
if (descriptionField && descriptionField.value !== undefined) {
|
||||
return descriptionField.value;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads profile data from the server and populates the form fields
|
||||
* @async
|
||||
* @function loadProfileData
|
||||
* @example
|
||||
* await loadProfileData();
|
||||
*/
|
||||
export async function loadProfileData(): Promise<void> {
|
||||
const userData = await loadProfile();
|
||||
if (userData) {
|
||||
if (userData.nickname) {
|
||||
setUsernameValue(userData.nickname);
|
||||
}
|
||||
if (userData.description) {
|
||||
setDescriptionValue(userData.description);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles profile form submission
|
||||
* @async
|
||||
* @function handleFormSubmission
|
||||
* @param {Event} e - Form submission event
|
||||
* @private
|
||||
*/
|
||||
async function handleFormSubmission(e: Event): Promise<void> {
|
||||
e.preventDefault();
|
||||
|
||||
const nickname = getUsernameValue();
|
||||
const description = getDescriptionValue();
|
||||
|
||||
if (nickname || description) {
|
||||
const success = await updateProfile({
|
||||
nickname: nickname || undefined,
|
||||
description: description || undefined
|
||||
});
|
||||
|
||||
if (success) {
|
||||
showSuccess('Профиль обновлен!');
|
||||
} else {
|
||||
showError('Ошибка при обновлении профиля');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up form submission handler
|
||||
* @function setupFormHandler
|
||||
* @private
|
||||
*/
|
||||
function setupFormHandler(): void {
|
||||
if (isInitialized) return;
|
||||
|
||||
// Get DOM elements
|
||||
profileForm = document.getElementById('profile-form')!;
|
||||
nicknameField = document.getElementById('username-field') as any;
|
||||
descriptionField = document.getElementById('description-field') as any;
|
||||
|
||||
profileForm.addEventListener('submit', handleFormSubmission);
|
||||
|
||||
isInitialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes profile editor functionality
|
||||
* @function initializeProfileEditor
|
||||
* @example
|
||||
* initializeProfileEditor();
|
||||
*/
|
||||
export function initializeProfileEditor(): void {
|
||||
setupFormHandler();
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Canvas-based image cropping component
|
||||
* @description Provides circular image cropping functionality with drag support
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import type { Size2D } from "../types";
|
||||
|
||||
/**
|
||||
* Image cropper class for circular profile picture cropping
|
||||
* @class ImageCropper
|
||||
*/
|
||||
export class ImageCropper {
|
||||
private canvas: HTMLCanvasElement;
|
||||
private ctx: CanvasRenderingContext2D;
|
||||
|
||||
/**
|
||||
* Image element to be cropped
|
||||
* @type {HTMLImageElement}
|
||||
* @private
|
||||
*/
|
||||
private image!: HTMLImageElement;
|
||||
|
||||
/**
|
||||
* Size of the crop area (diameter)
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
private cropSize: number = 200;
|
||||
private isDragging: boolean = false;
|
||||
|
||||
/**
|
||||
* Starting position of the drag operation
|
||||
* @type {Size2D}
|
||||
* @private
|
||||
*/
|
||||
private dragStart: Size2D = { x: 0, y: 0 };
|
||||
|
||||
/**
|
||||
* Current position of the crop area
|
||||
* @type {Size2D}
|
||||
* @private
|
||||
*/
|
||||
private cropPosition: Size2D = { x: 0, y: 0 };
|
||||
|
||||
/**
|
||||
* Creates a new ImageCropper instance
|
||||
* @param {HTMLElement} container - Container element to append the canvas to
|
||||
* @constructor
|
||||
* @example
|
||||
* const cropper = new ImageCropper(document.getElementById('cropper-area'));
|
||||
*/
|
||||
constructor(container: HTMLElement) {
|
||||
this.canvas = document.createElement('canvas');
|
||||
this.canvas.width = this.cropSize;
|
||||
this.canvas.height = this.cropSize;
|
||||
this.ctx = this.canvas.getContext('2d')!;
|
||||
|
||||
container.appendChild(this.canvas);
|
||||
this.setupEventListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up mouse and touch event listeners
|
||||
* @function setupEventListeners
|
||||
* @private
|
||||
*/
|
||||
private setupEventListeners(): void {
|
||||
this.canvas.addEventListener('mousedown', this.onMouseDown.bind(this));
|
||||
this.canvas.addEventListener('mousemove', this.onMouseMove.bind(this));
|
||||
this.canvas.addEventListener('mouseup', this.onMouseUp.bind(this));
|
||||
this.canvas.addEventListener('touchstart', this.onTouchStart.bind(this));
|
||||
this.canvas.addEventListener('touchmove', this.onTouchMove.bind(this));
|
||||
this.canvas.addEventListener('touchend', this.onTouchEnd.bind(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles mouse down events
|
||||
* @param {MouseEvent} e - Mouse event
|
||||
* @function onMouseDown
|
||||
* @private
|
||||
*/
|
||||
private onMouseDown(e: MouseEvent): void {
|
||||
this.isDragging = true;
|
||||
this.dragStart = { x: e.clientX, y: e.clientY };
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles mouse move events during dragging
|
||||
* @param {MouseEvent} e - Mouse event
|
||||
* @function onMouseMove
|
||||
* @private
|
||||
*/
|
||||
private onMouseMove(e: MouseEvent): void {
|
||||
if (!this.isDragging) return;
|
||||
|
||||
const deltaX = e.clientX - this.dragStart.x;
|
||||
const deltaY = e.clientY - this.dragStart.y;
|
||||
|
||||
this.cropPosition.x += deltaX;
|
||||
this.cropPosition.y += deltaY;
|
||||
|
||||
this.dragStart = { x: e.clientX, y: e.clientY };
|
||||
this.render();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles mouse up events
|
||||
* @function onMouseUp
|
||||
* @private
|
||||
*/
|
||||
private onMouseUp(): void {
|
||||
this.isDragging = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles touch start events
|
||||
* @param {TouchEvent} e - Touch event
|
||||
* @function onTouchStart
|
||||
* @private
|
||||
*/
|
||||
private onTouchStart(e: TouchEvent): void {
|
||||
e.preventDefault();
|
||||
const touch = e.touches[0];
|
||||
this.isDragging = true;
|
||||
this.dragStart = { x: touch.clientX, y: touch.clientY };
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles touch move events during dragging
|
||||
* @param {TouchEvent} e - Touch event
|
||||
* @function onTouchMove
|
||||
* @private
|
||||
*/
|
||||
private onTouchMove(e: TouchEvent): void {
|
||||
e.preventDefault();
|
||||
if (!this.isDragging) return;
|
||||
|
||||
const touch = e.touches[0];
|
||||
const deltaX = touch.clientX - this.dragStart.x;
|
||||
const deltaY = touch.clientY - this.dragStart.y;
|
||||
|
||||
this.cropPosition.x += deltaX;
|
||||
this.cropPosition.y += deltaY;
|
||||
|
||||
this.dragStart = { x: touch.clientX, y: touch.clientY };
|
||||
this.render();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles touch end events
|
||||
* @function onTouchEnd
|
||||
* @private
|
||||
*/
|
||||
private onTouchEnd(): void {
|
||||
this.isDragging = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads an image file for cropping
|
||||
* @param {File} file - Image file to load
|
||||
* @returns {Promise<void>} Promise that resolves when image is loaded
|
||||
* @async
|
||||
* @example
|
||||
* await cropper.loadImage(fileInput.files[0]);
|
||||
*/
|
||||
loadImage(file: File): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
this.image = new Image();
|
||||
this.image.onload = () => {
|
||||
this.render();
|
||||
resolve();
|
||||
};
|
||||
this.image.src = URL.createObjectURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the image with circular crop overlay
|
||||
* @function render
|
||||
* @private
|
||||
*/
|
||||
private render(): void {
|
||||
if (!this.image) return;
|
||||
|
||||
// Clear canvas
|
||||
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||
|
||||
// Calculate crop area
|
||||
const scale = Math.max(this.cropSize / this.image.width, this.cropSize / this.image.height);
|
||||
const scaledWidth = this.image.width * scale;
|
||||
const scaledHeight = this.image.height * scale;
|
||||
|
||||
// Draw image
|
||||
this.ctx.save();
|
||||
this.ctx.globalCompositeOperation = 'source-over';
|
||||
this.ctx.drawImage(
|
||||
this.image,
|
||||
this.cropPosition.x,
|
||||
this.cropPosition.y,
|
||||
scaledWidth,
|
||||
scaledHeight
|
||||
);
|
||||
this.ctx.restore();
|
||||
|
||||
// Draw crop overlay
|
||||
this.ctx.save();
|
||||
this.ctx.globalCompositeOperation = 'destination-in';
|
||||
this.ctx.beginPath();
|
||||
this.ctx.arc(this.cropSize / 2, this.cropSize / 2, this.cropSize / 2, 0, 2 * Math.PI);
|
||||
this.ctx.fill();
|
||||
this.ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the cropped image as a data URL
|
||||
* @returns {string} Data URL of the cropped image
|
||||
* @example
|
||||
* const croppedImage = cropper.getCroppedImage();
|
||||
* // Use croppedImage as src for an img element
|
||||
*/
|
||||
getCroppedImage(): string {
|
||||
return this.canvas.toDataURL('image/jpeg', 0.8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys the cropper and removes the canvas from DOM
|
||||
* @function destroy
|
||||
* @example
|
||||
* cropper.destroy();
|
||||
*/
|
||||
destroy(): void {
|
||||
if (this.canvas.parentNode) {
|
||||
this.canvas.parentNode.removeChild(this.canvas);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Profile-specific type definitions
|
||||
* @description Contains type definitions for profile-related functionality
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* User profile data structure
|
||||
* @interface ProfileData
|
||||
* @property {string} [profile_picture] - URL to user's profile picture
|
||||
* @property {string} [nickname] - User's display name
|
||||
* @property {string} [description] - User's bio or description
|
||||
*/
|
||||
export interface ProfileData {
|
||||
profile_picture?: string;
|
||||
nickname?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Profile picture upload response structure
|
||||
* @interface UploadResponse
|
||||
* @property {string} profile_picture_url - URL to the uploaded profile picture
|
||||
*/
|
||||
export interface UploadResponse {
|
||||
profile_picture_url: string;
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Profile picture upload functionality
|
||||
* @description Handles file selection, image cropping, and profile picture upload
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import type { Dialog } from "mdui/components/dialog";
|
||||
import { ImageCropper } from './image-cropper';
|
||||
import { uploadProfilePicture } from './api';
|
||||
import { loadProfile } from './api';
|
||||
import { showSuccess, showError } from '../utils/notification';
|
||||
|
||||
/**
|
||||
* Global image cropper instance
|
||||
* @type {ImageCropper | null}
|
||||
*/
|
||||
let cropper: ImageCropper | null = null;
|
||||
|
||||
/**
|
||||
* Initialization state flag
|
||||
* @type {boolean}
|
||||
*/
|
||||
let isInitialized = false;
|
||||
|
||||
let cropperDialog = document.getElementById('cropper-dialog') as Dialog;
|
||||
let fileInput = document.getElementById('pfp-file-input') as HTMLInputElement;
|
||||
let uploadBtn = document.getElementById('upload-pfp-btn')!;
|
||||
let cropSaveBtn = document.getElementById('crop-save')!;
|
||||
let cropCancelBtn = document.getElementById('crop-cancel')!;
|
||||
let cropperCloseBtn = document.getElementById('cropper-close')!;
|
||||
let cropperArea = document.getElementById('cropper-area')!;
|
||||
|
||||
/**
|
||||
* Opens the image cropper with the selected file
|
||||
* @async
|
||||
* @function openCropper
|
||||
* @param {File} file - The image file to crop
|
||||
* @private
|
||||
*/
|
||||
async function openCropper(file: File): Promise<void> {
|
||||
// Clear previous cropper
|
||||
cropperArea.innerHTML = '';
|
||||
|
||||
// Create new cropper
|
||||
cropper = new ImageCropper(cropperArea);
|
||||
|
||||
// Load image
|
||||
await cropper.loadImage(file);
|
||||
|
||||
// Open dialog
|
||||
cropperDialog.open = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the image cropper and cleans up resources
|
||||
* @function closeCropper
|
||||
* @private
|
||||
*/
|
||||
function closeCropper(): void {
|
||||
cropperDialog.open = false;
|
||||
cropperArea.innerHTML = '';
|
||||
if (cropper) {
|
||||
cropper.destroy();
|
||||
cropper = null;
|
||||
}
|
||||
fileInput.value = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the cropped image and uploads it to the server
|
||||
* @async
|
||||
* @function saveCroppedImage
|
||||
* @private
|
||||
*/
|
||||
async function saveCroppedImage(): Promise<void> {
|
||||
if (!cropper) return;
|
||||
|
||||
const croppedImageData = cropper.getCroppedImage();
|
||||
|
||||
// Convert data URL to blob
|
||||
const response = await fetch(croppedImageData);
|
||||
const blob = await response.blob();
|
||||
|
||||
const result = await uploadProfilePicture(blob);
|
||||
|
||||
if (result) {
|
||||
// Update profile picture display
|
||||
const profilePicture = document.getElementById('profile-picture') as HTMLImageElement;
|
||||
profilePicture.src = result.profile_picture_url + '?t=' + Date.now(); // Cache bust
|
||||
|
||||
// Close cropper
|
||||
closeCropper();
|
||||
|
||||
// Show success message
|
||||
showSuccess('Фото профиля обновлено!');
|
||||
} else {
|
||||
showError('Ошибка при загрузке фото');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up event listeners for upload functionality
|
||||
* @function setupEventListeners
|
||||
* @private
|
||||
*/
|
||||
function setupEventListeners(): void {
|
||||
if (isInitialized) return;
|
||||
|
||||
uploadBtn.addEventListener('click', () => {
|
||||
fileInput.click();
|
||||
});
|
||||
|
||||
fileInput.addEventListener('change', (e) => {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (file) {
|
||||
openCropper(file);
|
||||
}
|
||||
});
|
||||
|
||||
cropSaveBtn.addEventListener('click', () => {
|
||||
saveCroppedImage();
|
||||
});
|
||||
|
||||
cropCancelBtn.addEventListener('click', () => {
|
||||
closeCropper();
|
||||
});
|
||||
|
||||
cropperCloseBtn.addEventListener('click', () => {
|
||||
closeCropper();
|
||||
});
|
||||
|
||||
isInitialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads and displays the user's profile picture
|
||||
* @async
|
||||
* @function loadProfilePicture
|
||||
* @example
|
||||
* await loadProfilePicture();
|
||||
*/
|
||||
export async function loadProfilePicture(): Promise<void> {
|
||||
const userData = await loadProfile();
|
||||
if (userData?.profile_picture) {
|
||||
const url = `${userData.profile_picture}?t=${Date.now()}`;
|
||||
|
||||
const profilePicture = document.getElementById('profile-picture') as HTMLImageElement;
|
||||
const profilePicture2 = document.getElementById("preview1") as HTMLImageElement;
|
||||
profilePicture.src = url;
|
||||
profilePicture2.src = url;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes profile upload functionality
|
||||
* @function initializeProfileUpload
|
||||
* @example
|
||||
* initializeProfileUpload();
|
||||
*/
|
||||
export function initializeProfileUpload(): void {
|
||||
setupEventListeners();
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
@use "common/colors" as *;
|
||||
@use "common/material" as *;
|
||||
|
||||
#chat-interface {
|
||||
height: 100%;
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
background-color: $color-dark-surface-container;
|
||||
color: white;
|
||||
padding: 16px 16px;
|
||||
justify-content: end;
|
||||
width: fit-content;
|
||||
z-index: 1000;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
|
||||
.header-content {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
|
||||
.logo {
|
||||
font-size: 1.8rem;
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#logouts {
|
||||
display: none;
|
||||
list-style: none;
|
||||
gap: 10px;
|
||||
|
||||
li {
|
||||
a {
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
transition: all 0.3s ease;
|
||||
padding: 10px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chat-container {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
|
||||
.chat-main {
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
|
||||
.chat-header {
|
||||
padding: 16px;
|
||||
background: $color-dark-surface-container;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
box-shadow: black 0 0 20px;
|
||||
|
||||
.chat-header-avatar {
|
||||
width: 45px;
|
||||
height: 45px;
|
||||
border-radius: 20%;
|
||||
object-fit: cover;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
|
||||
.chat-header-info {
|
||||
display: flex;
|
||||
|
||||
.info-chat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
h4 {
|
||||
font-size: 1.1rem;
|
||||
margin: 0 0 0.2rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
color: #718096;
|
||||
}
|
||||
}
|
||||
|
||||
.online-status {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background-color: $success;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
a {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
text-decoration: none;
|
||||
color: white;
|
||||
justify-content: end;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
position: absolute;
|
||||
right: 2%;
|
||||
top: 2%;
|
||||
|
||||
&:hover {
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.quote.contextual-content > .quote-inner {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
|
||||
.reply-username {
|
||||
font-weight: 600;
|
||||
color: $color-dark-on-surface;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.reply-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
padding: 1rem;
|
||||
overflow-y: auto;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 7px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background-color: $color-dark-surface-container-high;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-bottom: 1rem;
|
||||
max-width: 70%;
|
||||
position: relative;
|
||||
width: fit-content;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 8px;
|
||||
|
||||
.message-inner {
|
||||
border-radius: 12px;
|
||||
position: relative;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-word;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
display: inline-block;
|
||||
|
||||
.message-profile-pic {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
flex-shrink: 0;
|
||||
margin-bottom: 4px;
|
||||
margin: 8px;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.message-username {
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.3rem;
|
||||
font-size: 0.9rem;
|
||||
transition: color 0.2s ease;
|
||||
margin: 8px;
|
||||
|
||||
&:hover {
|
||||
color: $color-dark-primary;
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
.message-content {
|
||||
word-wrap: break-word;
|
||||
margin: 10px 10px 0 10px;
|
||||
white-space: pre-wrap;
|
||||
|
||||
> p:first-child {
|
||||
margin-block-start: 0;
|
||||
}
|
||||
|
||||
> p:last-child {
|
||||
margin-block-end: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.quote.reply-preview {
|
||||
user-select: none;
|
||||
margin: 10px;
|
||||
}
|
||||
|
||||
.message-attachments {
|
||||
padding: 5px 0 0 0;
|
||||
overflow: hidden;
|
||||
|
||||
.attachment {
|
||||
a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.attachement-image {
|
||||
max-width: 200px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
margin-left: 3px;
|
||||
margin-right: 3px;
|
||||
margin-bottom: 3px;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
&.loading {
|
||||
filter: blur(10px);
|
||||
transition: filter 200ms ease;
|
||||
}
|
||||
}
|
||||
|
||||
.attachement-image.placeholder {
|
||||
background: $color-dark-surface-container-highest;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.image-wrapper {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.loading-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.08);
|
||||
backdrop-filter: blur(6px);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.preload-image {
|
||||
position: absolute;
|
||||
width: 0;
|
||||
height: 0;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.with-icon-gap {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.message-time {
|
||||
font-size: 0.7rem;
|
||||
color: $color-dark-on-surface-variant;
|
||||
margin-top: 0.3rem;
|
||||
text-align: right;
|
||||
user-select: none;
|
||||
margin: 4px 8px 8px 8px;
|
||||
}
|
||||
}
|
||||
|
||||
&.received .message-inner {
|
||||
background-color: $color-dark-surface-container;
|
||||
border-top-left-radius: 5px;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
&.sent {
|
||||
margin-left: auto;
|
||||
flex-direction: row-reverse;
|
||||
|
||||
.message-inner {
|
||||
background-color: $color-dark-primary-container;
|
||||
color: $color-dark-on-primary-container;
|
||||
border-top-right-radius: 5px;
|
||||
}
|
||||
|
||||
.message-time {
|
||||
color: $color-dark-on-primary-container;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.file-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
|
||||
z-index: 100;
|
||||
|
||||
backdrop-filter: blur(20px);
|
||||
|
||||
.file-overlay-wrapper {
|
||||
border-radius: 30px;
|
||||
outline: 3px dashed $color-dark-primary;
|
||||
outline-offset: -20px;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
.file-overlay-inner {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
background: rgba(18, 18, 18, 0.8);
|
||||
border: 1px solid $color-dark-surface-container-high;
|
||||
border-radius: 12px;
|
||||
color: $color-dark-on-surface;
|
||||
|
||||
mdui-icon {
|
||||
color: $color-dark-primary;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.chat-input-wrapper {
|
||||
position: relative;
|
||||
margin: 0 20px 20px 20px;
|
||||
|
||||
&::before {
|
||||
$height: 20px;
|
||||
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -$height;
|
||||
left: 0;
|
||||
right: 0;
|
||||
width: 100%;
|
||||
height: $height;
|
||||
background: linear-gradient(
|
||||
0deg,
|
||||
$color-dark-surface,
|
||||
rgba(255, 255, 255, 0),
|
||||
);
|
||||
}
|
||||
|
||||
.input-group {
|
||||
display: flex;
|
||||
background-color: $color-dark-surface-container;
|
||||
border-radius: 30px;
|
||||
flex-direction: column;
|
||||
|
||||
.contextual-preview {
|
||||
padding: 12px 16px 0 16px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
|
||||
mdui-icon {
|
||||
align-self: center;
|
||||
box-sizing: content-box;
|
||||
}
|
||||
|
||||
.reply-cancel {
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.attachments-preview {
|
||||
align-items: center;
|
||||
|
||||
.attachments-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-input {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
.message-input {
|
||||
flex: 1;
|
||||
padding: 20px 20px;
|
||||
padding-right: 0;
|
||||
border: none;
|
||||
border-radius: 25px;
|
||||
font-size: 1rem;
|
||||
outline: none;
|
||||
caret-color: $color-dark-primary;
|
||||
color: $color-dark-on-surface;
|
||||
resize: none;
|
||||
font: inherit;
|
||||
font-size: 13pt;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.buttons {
|
||||
align-self: flex-end;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
|
||||
.send-btn {
|
||||
margin: 10px;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: 50%;
|
||||
background-color: $color-dark-primary;
|
||||
color: $color-dark-on-primary;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background-color 0.25s ease;
|
||||
align-self: flex-end;
|
||||
|
||||
@include hoverStateLayer($background: $color-dark-primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.message-profile-pic {
|
||||
img {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
border: 2px solid $color-dark-outline;
|
||||
|
||||
&.loading {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.message-username {
|
||||
&.loading {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
|
||||
.context-menu {
|
||||
position: fixed;
|
||||
background: $color-dark-surface;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
padding: 0.5rem 0;
|
||||
min-width: 160px;
|
||||
z-index: 1000;
|
||||
|
||||
&.entering {
|
||||
animation: fadeInDown 0.2s ease forwards;
|
||||
}
|
||||
|
||||
&.entering-left {
|
||||
animation: fadeInLeft 0.2s ease forwards;
|
||||
}
|
||||
|
||||
&.entering-up {
|
||||
animation: fadeInUp 0.2s ease forwards;
|
||||
}
|
||||
|
||||
&.entering-up-left {
|
||||
animation: fadeInUpLeft 0.2s ease forwards;
|
||||
}
|
||||
|
||||
&.closing {
|
||||
animation: fadeOutUp 0.2s ease forwards;
|
||||
}
|
||||
|
||||
&.closing-left {
|
||||
animation: fadeOutRight 0.2s ease forwards;
|
||||
}
|
||||
|
||||
&.closing-up {
|
||||
animation: fadeOutDown 0.2s ease forwards;
|
||||
}
|
||||
|
||||
&.closing-up-left {
|
||||
animation: fadeOutDownRight 0.2s ease forwards;
|
||||
}
|
||||
|
||||
.context-menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem 1rem;
|
||||
cursor: pointer;
|
||||
color: $color-dark-on-surface;
|
||||
font-size: 0.9rem;
|
||||
transition: background-color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: $color-dark-surface-container;
|
||||
}
|
||||
|
||||
.material-symbols {
|
||||
font-size: 1.1rem;
|
||||
color: $color-dark-on-surface-variant;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fullscreen Image Viewer
|
||||
.fullscreen-image-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
backdrop-filter: blur(20px);
|
||||
z-index: 9999;
|
||||
opacity: 1;
|
||||
transition: opacity 0.3s ease;
|
||||
|
||||
&.closing {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.fullscreen-animated-image {
|
||||
position: absolute;
|
||||
object-fit: contain;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
|
||||
transition: left 0.3s ease, top 0.3s ease, width 0.3s ease, height 0.3s ease;
|
||||
}
|
||||
|
||||
.fullscreen-controls {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
|
||||
&.top-right {
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.progress-wrapper {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
.download-app-screen {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-width: 100vw;
|
||||
min-height: 100vh;
|
||||
padding: 32px;
|
||||
}
|
||||
@@ -9,13 +9,14 @@ html.electron {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 8px;
|
||||
height: 40px;
|
||||
min-height: 40px;
|
||||
background-color: $color-dark-surface-container;
|
||||
width: 100%;
|
||||
-webkit-app-region: drag;
|
||||
user-select: none;
|
||||
z-index: 10;
|
||||
transition: background-color 0.5s ease;
|
||||
flex-shrink: 0;
|
||||
|
||||
&.color-surface {
|
||||
background-color: $color-dark-surface;
|
||||
@@ -29,15 +30,12 @@ html.electron {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
&.platform-darwin .macos-padding {
|
||||
width: 70px;
|
||||
#main-wrapper {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
// .window-controls {
|
||||
// -webkit-app-region: no-drag;
|
||||
|
||||
// .hidden {
|
||||
// display: none;
|
||||
// }
|
||||
// }
|
||||
&.platform-darwin .macos-padding {
|
||||
width: 80px;
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@
|
||||
background-color: $color-dark-surface-container;
|
||||
height: 100%;
|
||||
z-index: 1000;
|
||||
min-height: 0; // allow children to manage their own scrolling
|
||||
|
||||
.chat-header-left {
|
||||
display: flex;
|
||||
@@ -64,7 +65,7 @@
|
||||
padding: 16px;
|
||||
overflow: hidden;
|
||||
|
||||
#productname {
|
||||
.product-name {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
@@ -100,6 +101,10 @@
|
||||
.chat-tabs {
|
||||
margin-top: 5px;
|
||||
width: 100%;
|
||||
height: calc(100% - 80px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0; // prevent flex collapse when inner overflows
|
||||
--mdui-color-surface: $color-dark-surface-container;
|
||||
--mdui-color-surface-variant: transparent;
|
||||
|
||||
@@ -110,6 +115,29 @@
|
||||
object-fit: cover;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
|
||||
mdui-tabs {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0; // enable inner panel to scroll
|
||||
}
|
||||
|
||||
mdui-tab-panel[active] {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0; // critical to avoid collapsing
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
mdui-list {
|
||||
flex: 1;
|
||||
min-height: 0; // allow scroll area to size correctly
|
||||
overflow-y: auto;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
mdui-bottom-app-bar {
|
||||
@@ -187,6 +187,16 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.profile-actions {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-top: 0.5rem;
|
||||
|
||||
mdui-button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.fade-in {
|
||||
animation: fadeIn 0.3s ease forwards;
|
||||
}
|
||||
|
||||
@keyframes fadeOutUp {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeInDown {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeInLeft {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeInUp {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeInUpLeft {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translate(10px, 10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translate(0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeOutRight {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateX(10px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeOutDown {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeOutDownRight {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translate(0, 0);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translate(10px, 10px);
|
||||
}
|
||||
}
|
||||
|
||||
.chat-switch-out {
|
||||
animation: fadeOutUp 0.2s ease forwards;
|
||||
}
|
||||
|
||||
.chat-switch-in {
|
||||
animation: fadeInDown 0.2s ease forwards;
|
||||
}
|
||||
+40
-2
@@ -1,4 +1,5 @@
|
||||
@use "material" as *;
|
||||
@use "sass:color";
|
||||
|
||||
.text-center {
|
||||
text-align: center;
|
||||
@@ -101,12 +102,49 @@ button, input {
|
||||
margin: 0 0 1rem 0;
|
||||
color: $color-dark-on-surface;
|
||||
font-size: 1.2rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
|
||||
mdui-text-field {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.dialog-actions {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
justify-content: flex-end;
|
||||
margin-top: 1.5rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.rich-text-area {
|
||||
width: 100%;
|
||||
resize: none;
|
||||
transition: height 0.2s ease;
|
||||
overflow-y: hidden;
|
||||
background-color: transparent;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.quote {
|
||||
background-color: $color-dark-surface-primary-container-lightened;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
|
||||
color: $color-dark-on-surface-variant;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.4;
|
||||
|
||||
&.bg-surfaceContainer {
|
||||
background-color: $color-dark-secondary-container;
|
||||
|
||||
.quote-inner {
|
||||
border-left: 3px solid $color-dark-secondary;
|
||||
}
|
||||
}
|
||||
|
||||
.quote-inner {
|
||||
border-left: 3px solid $color-dark-primary;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
}
|
||||
+3
@@ -50,6 +50,9 @@ $color-dark-surface-container-low: rgb(24 28 31);
|
||||
$color-dark-surface-container: rgb(28 32 36);
|
||||
$color-dark-surface-container-high: rgb(38 43 46);
|
||||
$color-dark-surface-container-highest: rgb(49 53 57);
|
||||
$color-dark-surface-primary-container-lightened: color.adjust($color-dark-primary-container, $lightness: 5%);
|
||||
$color-dark-surface-container-lightened: color.adjust($color-dark-surface-container, $lightness: 5%);
|
||||
|
||||
// custom colors
|
||||
$color-1: rgb(82, 109, 246);
|
||||
$color-2: rgb(65, 11, 113);
|
||||
@@ -0,0 +1,31 @@
|
||||
@use "../common/material" as *;
|
||||
|
||||
.reply-dialog .dialog-content {
|
||||
width: 300px;
|
||||
overflow-x:hidden;
|
||||
|
||||
.reply-preview-dialog {
|
||||
margin-bottom: 1rem;
|
||||
padding: 16px;
|
||||
background-color: $color-dark-surface-container;
|
||||
border-radius: 16px;
|
||||
|
||||
.reply-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
|
||||
.reply-username {
|
||||
font-weight: 600;
|
||||
color: $color-dark-on-surface;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.reply-text {
|
||||
color: $color-dark-on-surface-variant;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@
|
||||
@use "common/colors" as *;
|
||||
@use "common/material" as *;
|
||||
@use "electron";
|
||||
@use "dialogs/reply";
|
||||
@use "download-app";
|
||||
|
||||
@use "lib/fonts/montserrat";
|
||||
@use "lib/fonts/material-symbols";
|
||||
@@ -22,17 +24,20 @@ body {
|
||||
background-color: $color-dark-surface;
|
||||
color: $color-dark-on-surface;
|
||||
line-height: 1.6;
|
||||
|
||||
#main-wrapper {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
min-height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
body, #root {
|
||||
height: 100vh;
|
||||
position: relative;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
#main-wrapper {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
height: 100vh;
|
||||
}
|
||||
}
|
||||
|
||||
mdui-dialog {
|
||||
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,89 @@
|
||||
/// <reference lib="webworker" />
|
||||
|
||||
declare const self: ServiceWorkerGlobalScope;
|
||||
|
||||
interface NotificationPayload {
|
||||
title: string;
|
||||
body: string;
|
||||
icon?: string;
|
||||
image?: string;
|
||||
tag?: string;
|
||||
data?: any;
|
||||
}
|
||||
|
||||
interface NotificationAction {
|
||||
action: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
interface NotificationOptions {
|
||||
body: string;
|
||||
icon: string;
|
||||
badge: string;
|
||||
image?: string;
|
||||
tag: string;
|
||||
data?: any;
|
||||
actions: NotificationAction[];
|
||||
requireInteraction: boolean;
|
||||
silent: boolean;
|
||||
}
|
||||
|
||||
// Service Worker for Push Notifications
|
||||
self.addEventListener("push", function(event: ExtendableEvent) {
|
||||
const pushEvent = event as PushEvent;
|
||||
if (pushEvent.data) {
|
||||
const data: NotificationPayload = pushEvent.data.json();
|
||||
|
||||
const options: NotificationOptions = {
|
||||
body: data.body,
|
||||
icon: data.icon || "/logo.png",
|
||||
badge: "/logo.png",
|
||||
image: data.image,
|
||||
tag: data.tag || "message",
|
||||
data: data.data,
|
||||
actions: [
|
||||
{
|
||||
action: "open",
|
||||
title: "Open Chat"
|
||||
},
|
||||
{
|
||||
action: "close",
|
||||
title: "Close"
|
||||
}
|
||||
],
|
||||
requireInteraction: true,
|
||||
silent: false
|
||||
};
|
||||
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(data.title, options)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
self.addEventListener("notificationclick", function(event: ExtendableEvent) {
|
||||
const notificationEvent = event as NotificationEvent;
|
||||
notificationEvent.notification.close();
|
||||
|
||||
if (notificationEvent.action === "open" || !notificationEvent.action) {
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: "window" }).then(function(clientList: readonly WindowClient[]) {
|
||||
// If there's already a window open, focus it
|
||||
for (let i = 0; i < clientList.length; i++) {
|
||||
const client = clientList[i];
|
||||
if (client.url === self.location.origin && "focus" in client) {
|
||||
return client.focus();
|
||||
}
|
||||
}
|
||||
// Otherwise, open a new window
|
||||
if (self.clients.openWindow) {
|
||||
return self.clients.openWindow(self.location.origin);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
self.addEventListener("notificationclose", function(_event: ExtendableEvent) {
|
||||
// Handle notification close if needed
|
||||
});
|
||||
@@ -1,104 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Settings dialog management and panel navigation
|
||||
* @description Handles settings dialog functionality and dynamic panel switching
|
||||
* @author Cursor
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import type { Dialog } from "mdui/components/dialog";
|
||||
|
||||
const dialog = document.getElementById('settings-dialog') as Dialog;
|
||||
const openButton = document.getElementById('settings-open')!;
|
||||
const closeButton = document.getElementById('settings-close')!;
|
||||
|
||||
// Settings panel management
|
||||
const settingsList = document.querySelector('#settings-menu mdui-list')!;
|
||||
const settingsPanels = document.querySelectorAll('.settings-panel');
|
||||
|
||||
/**
|
||||
* Mapping between list item text and their corresponding panel IDs
|
||||
* @type {Object.<string, string>}
|
||||
*/
|
||||
const panelMapping = {
|
||||
'Уведомления': 'notifications-settings',
|
||||
'Внешний вид': 'appearance-settings',
|
||||
'Безопасность': 'security-settings',
|
||||
'Язык': 'language-settings',
|
||||
'Хранилище': 'storage-settings',
|
||||
'Помощь': 'help-settings',
|
||||
'О приложении': 'about-settings'
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles click events on settings list items
|
||||
* @param {Element} item - The clicked list item element
|
||||
* @function handleListItemClick
|
||||
* @private
|
||||
*/
|
||||
function handleListItemClick(item: Element): void {
|
||||
// Remove active class from all items and panels
|
||||
const listItems = settingsList.querySelectorAll('mdui-list-item');
|
||||
listItems.forEach(li => li.removeAttribute('active'));
|
||||
settingsPanels.forEach(panel => panel.classList.remove('active'));
|
||||
|
||||
// Add active class to clicked item
|
||||
item.setAttribute('active', '');
|
||||
|
||||
// Show corresponding panel using the mapping
|
||||
const itemText = item.textContent?.trim();
|
||||
const panelId = panelMapping[itemText as keyof typeof panelMapping];
|
||||
|
||||
if (panelId) {
|
||||
const targetPanel = document.getElementById(panelId);
|
||||
if (targetPanel) {
|
||||
targetPanel.classList.add('active');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up click listeners for all settings list items
|
||||
* @function setupSettingsNavigation
|
||||
* @private
|
||||
*/
|
||||
function setupSettingsNavigation(): void {
|
||||
const listItems = settingsList.querySelectorAll('mdui-list-item');
|
||||
listItems.forEach((item) => {
|
||||
item.addEventListener('click', () => handleListItemClick(item));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets settings dialog to show the first panel
|
||||
* @function resetToFirstPanel
|
||||
* @private
|
||||
*/
|
||||
function resetToFirstPanel(): void {
|
||||
const firstItem = settingsList.querySelector('mdui-list-item');
|
||||
const firstPanel = document.querySelector('.settings-panel');
|
||||
if (firstItem && firstPanel) {
|
||||
settingsList.querySelectorAll('mdui-list-item').forEach(li => li.removeAttribute('active'));
|
||||
settingsPanels.forEach(panel => panel.classList.remove('active'));
|
||||
firstItem.setAttribute('active', '');
|
||||
firstPanel.classList.add('active');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up dialog event listeners
|
||||
* @function setupDialogListeners
|
||||
* @private
|
||||
*/
|
||||
function setupDialogListeners(): void {
|
||||
openButton.addEventListener('click', () => {
|
||||
dialog.open = true;
|
||||
resetToFirstPanel();
|
||||
});
|
||||
|
||||
closeButton.addEventListener('click', () => {
|
||||
dialog.open = false;
|
||||
});
|
||||
}
|
||||
|
||||
setupSettingsNavigation();
|
||||
setupDialogListeners();
|
||||
@@ -0,0 +1,50 @@
|
||||
import { MINIMUM_WIDTH } from "../core/config";
|
||||
import { isElectron } from "../electron/electron";
|
||||
import { ElectronTitleBar } from "./components/Electron";
|
||||
import useWindowSize from "./hooks/useWindowSize";
|
||||
import ChatScreen from "./screen/ChatScreen";
|
||||
import DownloadAppScreen from "./screen/DownloadAppScreen";
|
||||
import LoginScreen from "./screen/LoginScreen";
|
||||
import RegisterScreen from "./screen/RegisterScreen";
|
||||
import { useAppState } from "./state";
|
||||
import { useEffect } from "react";
|
||||
|
||||
export default function App() {
|
||||
const { currentPage, restoreUserFromStorage } = useAppState();
|
||||
const { width } = useWindowSize();
|
||||
|
||||
// Restore user from localStorage on app initialization
|
||||
useEffect(() => {
|
||||
restoreUserFromStorage();
|
||||
}, [restoreUserFromStorage]);
|
||||
|
||||
if (!isElectron && width < MINIMUM_WIDTH) {
|
||||
return <DownloadAppScreen />
|
||||
}
|
||||
|
||||
let page = <LoginScreen />;
|
||||
|
||||
switch (currentPage) {
|
||||
case "login": {
|
||||
page = <LoginScreen />
|
||||
break;
|
||||
}
|
||||
case "register": {
|
||||
page = <RegisterScreen />
|
||||
break;
|
||||
}
|
||||
case "chat": {
|
||||
page = <ChatScreen />
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ElectronTitleBar />
|
||||
<div id="main-wrapper">
|
||||
{page}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export type AlertType = "success" | "danger"
|
||||
|
||||
export interface Alert {
|
||||
type: AlertType;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export function AlertsContainer({ alerts }: { alerts: Alert[]}) {
|
||||
return (
|
||||
<div>
|
||||
{alerts.slice(-3).map((alert, i) => {
|
||||
return <div className={`alert alert-${alert.type}`} key={i}>{alert.message}</div>
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type React from "react";
|
||||
|
||||
export function AuthContainer({ children }: { children?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="auth-container">
|
||||
<div className="auth-card fade-in">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export type IconType = "filled" | "outlined";
|
||||
|
||||
export interface AuthHeaderIcon {
|
||||
name: string;
|
||||
type: IconType
|
||||
}
|
||||
|
||||
export interface AuthHeaderProps {
|
||||
title: string;
|
||||
icon: string | AuthHeaderIcon;
|
||||
subtitle: string;
|
||||
}
|
||||
|
||||
export function AuthHeader({ title, icon, subtitle }: AuthHeaderProps) {
|
||||
const iconType = typeof icon == "string" ? "filled" : icon.type;
|
||||
const iconName = typeof icon == "string" ? icon : icon.name;
|
||||
|
||||
return (
|
||||
<div className="auth-header">
|
||||
<h2>
|
||||
<span className={`material-symbols ${iconType} large`}>{iconName}</span>
|
||||
{title}
|
||||
</h2>
|
||||
<p>{subtitle}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { PRODUCT_NAME } from "../../core/config";
|
||||
import { isElectron } from "../../electron/electron";
|
||||
|
||||
export function ElectronTitleBar() {
|
||||
return isElectron && (
|
||||
<div id="electron-title-bar">
|
||||
{window.electronInterface.platform == "darwin" && <div className="macos-padding"></div>}
|
||||
<div id="window-title">{PRODUCT_NAME}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { PRODUCT_NAME } from "../../../core/config";
|
||||
import { useProfile } from "../../hooks/useProfile";
|
||||
import defaultAvatar from "../../../resources/images/default-avatar.png";
|
||||
import { useState } from "react";
|
||||
import { ProfileDialog } from "../profile/ProfileDialog";
|
||||
|
||||
export function ChatHeader() {
|
||||
const { profileData } = useProfile();
|
||||
const [isProfileOpen, setIsProfileOpen] = useState(false);
|
||||
|
||||
const handleProfileClick = () => {
|
||||
setIsProfileOpen(true);
|
||||
};
|
||||
|
||||
const profilePictureUrl = profileData?.profile_picture || defaultAvatar;
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="chat-header-left">
|
||||
<div className="product-name">{PRODUCT_NAME}</div>
|
||||
<div className="profile">
|
||||
<a href="#" id="profile-open" onClick={handleProfileClick}>
|
||||
<img
|
||||
src={profilePictureUrl}
|
||||
alt=""
|
||||
id="preview1"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.src = defaultAvatar;
|
||||
}}
|
||||
/>
|
||||
</a>
|
||||
</div>
|
||||
</header>
|
||||
<ProfileDialog isOpen={isProfileOpen} onOpenChange={setIsProfileOpen} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { MaterialDialog } from "../core/Dialog";
|
||||
import { RichTextArea } from "../core/RichTextArea";
|
||||
import type { Message } from "../../../core/types";
|
||||
import Quote from "../core/Quote";
|
||||
import AnimatedHeight from "../core/animations/AnimatedHeight";
|
||||
import { useImmer } from "use-immer";
|
||||
|
||||
interface ChatInputWrapperProps {
|
||||
onSendMessage: (message: string, files: File[]) => void;
|
||||
onSaveEdit?: (content: string) => void;
|
||||
replyTo?: Message | null;
|
||||
replyToVisible: boolean;
|
||||
onClearReply?: () => void;
|
||||
onCloseReply?: () => void;
|
||||
editingMessage?: Message | null;
|
||||
editVisible?: boolean;
|
||||
onClearEdit?: () => void;
|
||||
onCloseEdit?: () => void;
|
||||
onProvideFileAdder?: (adder: (files: File[]) => void) => void;
|
||||
}
|
||||
|
||||
export function ChatInputWrapper(
|
||||
{
|
||||
onSendMessage,
|
||||
onSaveEdit,
|
||||
replyTo,
|
||||
replyToVisible,
|
||||
onClearReply,
|
||||
onCloseReply,
|
||||
editingMessage,
|
||||
editVisible = false,
|
||||
onClearEdit,
|
||||
onCloseEdit,
|
||||
onProvideFileAdder
|
||||
}: ChatInputWrapperProps
|
||||
) {
|
||||
const [message, setMessage] = useState("");
|
||||
const [selectedFiles, setSelectedFiles] = useImmer<File[]>([]);
|
||||
const [attachmentsVisible, setAttachmentsVisible] = useState(false);
|
||||
const [errorOpen, setErrorOpen] = useState(false);
|
||||
|
||||
// Expose a way for parent to programmatically add files
|
||||
useEffect(() => {
|
||||
if (onProvideFileAdder) {
|
||||
const addFiles = (files: File[]) => {
|
||||
if (!files || files.length === 0) return;
|
||||
setSelectedFiles(draft => { draft.push(...files) });
|
||||
};
|
||||
onProvideFileAdder(addFiles);
|
||||
}
|
||||
}, [onProvideFileAdder]);
|
||||
|
||||
// When entering edit mode, preload the message content
|
||||
useEffect(() => {
|
||||
setMessage(editingMessage ? editingMessage.content || "" : "");
|
||||
}, [editingMessage]);
|
||||
|
||||
useEffect(() => {
|
||||
setAttachmentsVisible(selectedFiles.length > 0);
|
||||
}, [selectedFiles]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent | Event) => {
|
||||
e.preventDefault();
|
||||
const hasText = Boolean(message.trim());
|
||||
const hasFiles = selectedFiles.length > 0;
|
||||
if (hasText || hasFiles) {
|
||||
const totalSize = selectedFiles.reduce((acc, f) => acc + f.size, 0);
|
||||
const limit = 4 * 1024 * 1024 * 1024; // 4GB
|
||||
if (totalSize > limit) {
|
||||
setErrorOpen(true);
|
||||
return;
|
||||
}
|
||||
if (editingMessage && onSaveEdit) {
|
||||
onSaveEdit(message);
|
||||
setMessage("");
|
||||
if (onClearEdit) onClearEdit();
|
||||
} else {
|
||||
onSendMessage(message, selectedFiles);
|
||||
setMessage("");
|
||||
setAttachmentsVisible(false);
|
||||
if (onClearReply) onClearReply();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function handleAttachClick() {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.multiple = true;
|
||||
input.addEventListener("change", () => {
|
||||
setSelectedFiles(draft => { draft.push(...Array.from(input.files || [])) });
|
||||
});
|
||||
input.click();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="chat-input-wrapper">
|
||||
<form className="input-group" id="message-form" onSubmit={handleSubmit}>
|
||||
<AnimatedHeight visible={editVisible} onFinish={onCloseEdit}>
|
||||
{editingMessage && (
|
||||
<div className="reply-preview contextual-preview">
|
||||
<mdui-icon name="edit" />
|
||||
<Quote className="reply-content contextual-content" background="surfaceContainer">
|
||||
<span className="reply-username">{editingMessage!.username}</span>
|
||||
<span className="reply-text">{editingMessage!.content}</span>
|
||||
</Quote>
|
||||
<mdui-button-icon icon="close" className="reply-cancel" onClick={onClearEdit}></mdui-button-icon>
|
||||
</div>
|
||||
)}
|
||||
</AnimatedHeight>
|
||||
<AnimatedHeight visible={replyToVisible} onFinish={onCloseReply}>
|
||||
{replyTo && (
|
||||
<div className="reply-preview contextual-preview">
|
||||
<mdui-icon name="reply" />
|
||||
<Quote className="reply-content contextual-content" background="surfaceContainer">
|
||||
<span className="reply-username">{replyTo!.username}</span>
|
||||
<span className="reply-text">{replyTo!.content}</span>
|
||||
</Quote>
|
||||
<mdui-button-icon icon="close" className="reply-cancel" onClick={onClearReply}></mdui-button-icon>
|
||||
</div>
|
||||
)}
|
||||
</AnimatedHeight>
|
||||
<AnimatedHeight visible={attachmentsVisible} onFinish={() => setSelectedFiles([])}>
|
||||
{selectedFiles.length > 0 && (
|
||||
<div className="attachments-preview contextual-preview">
|
||||
<mdui-icon name="attach_file" />
|
||||
<div className="attachments-chips">
|
||||
{selectedFiles.map((file, i) => (
|
||||
<mdui-chip
|
||||
key={i}
|
||||
variant="input"
|
||||
end-icon="close"
|
||||
title={`${file.name} (${Math.round(file.size/1024/1024)} MB)`}
|
||||
onClick={() => {
|
||||
if (selectedFiles.length == 1) {
|
||||
setAttachmentsVisible(false);
|
||||
} else {
|
||||
setSelectedFiles(draft => { draft.splice(i) })
|
||||
}
|
||||
}}
|
||||
>
|
||||
<mdui-icon slot="icon" name="attach_file"></mdui-icon>
|
||||
<span className="name">{file.name}</span>
|
||||
</mdui-chip>
|
||||
))}
|
||||
</div>
|
||||
<mdui-button-icon icon="close" className="reply-cancel" onClick={() => setAttachmentsVisible(false)}></mdui-button-icon>
|
||||
</div>
|
||||
)}
|
||||
</AnimatedHeight>
|
||||
<div className="chat-input">
|
||||
<RichTextArea
|
||||
className="message-input"
|
||||
id="message-input"
|
||||
placeholder="Напишите сообщение..."
|
||||
autoComplete="off"
|
||||
text={message}
|
||||
rows={1}
|
||||
onTextChange={(value) => setMessage(value)}
|
||||
onEnter={handleSubmit} />
|
||||
<div className="buttons">
|
||||
<mdui-button-icon icon="attach_file" onClick={handleAttachClick} className="attach-btn"></mdui-button-icon>
|
||||
<button type="submit" className="send-btn">
|
||||
<span className="material-symbols filled">{editingMessage ? "check" : "send"}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<MaterialDialog open={errorOpen} onOpenChange={setErrorOpen} close-on-overlay-click close-on-esc>
|
||||
<div slot="headline">Ошибка</div>
|
||||
<div>Общий размер вложений превышает 4 ГБ.</div>
|
||||
<mdui-button slot="action" onClick={() => setErrorOpen(false)}>Закрыть</mdui-button>
|
||||
</MaterialDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useChat } from "../../hooks/useChat";
|
||||
import defaultAvatar from "../../../resources/images/default-avatar.png";
|
||||
|
||||
export function ChatMainHeader() {
|
||||
const { currentChat } = useChat();
|
||||
|
||||
return (
|
||||
<div className="chat-header">
|
||||
<img src={defaultAvatar} alt="Avatar" className="chat-header-avatar" />
|
||||
<div className="chat-header-info">
|
||||
<div className="info-chat">
|
||||
<h4 id="chat-name">{currentChat}</h4>
|
||||
<p>
|
||||
<span className="online-status"></span>
|
||||
Онлайн
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import { useChat } from "../../hooks/useChat";
|
||||
import { Message } from "./Message";
|
||||
import { useAppState } from "../../state";
|
||||
import type { Message as MessageType } from "../../../core/types";
|
||||
import type { UserProfile } from "../../../core/types";
|
||||
import { UserProfileDialog } from "./UserProfileDialog";
|
||||
import { MessageContextMenu, type ContextMenuState } from "./MessageContextMenu";
|
||||
import { fetchUserProfile } from "../../../api/profileApi";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { delay } from "../../../utils/utils";
|
||||
import { MaterialDialog } from "../core/Dialog";
|
||||
|
||||
interface ChatMessagesProps {
|
||||
messages?: MessageType[];
|
||||
isDm?: boolean;
|
||||
children?: ReactNode;
|
||||
onReplySelect?: (message: MessageType) => void;
|
||||
onEditSelect?: (message: MessageType) => void;
|
||||
onDelete?: (id: number) => void;
|
||||
dmRecipientPublicKey?: string;
|
||||
}
|
||||
|
||||
export function ChatMessages({ messages: propMessages, children, isDm = false, onReplySelect, onEditSelect, onDelete, dmRecipientPublicKey }: ChatMessagesProps) {
|
||||
const { messages: hookMessages } = useChat();
|
||||
const { user } = useAppState();
|
||||
|
||||
// Use prop messages if provided, otherwise use hook messages
|
||||
const messages = propMessages || hookMessages;
|
||||
const [profileDialogOpen, setProfileDialogOpen] = useState(false);
|
||||
const [selectedUserProfile, setSelectedUserProfile] = useState<UserProfile | null>(null);
|
||||
const [isLoadingProfile, setIsLoadingProfile] = useState(false);
|
||||
|
||||
// Context menu state
|
||||
const [contextMenu, setContextMenu] = useState<ContextMenuState>({
|
||||
isOpen: false,
|
||||
message: null,
|
||||
position: { x: 0, y: 0 }
|
||||
});
|
||||
|
||||
// Delete dialog
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [toBeDeleted, setToBeDeleted] = useState<{ id: number; isDm: boolean } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!deleteDialogOpen) {
|
||||
setToBeDeleted(null);
|
||||
}
|
||||
}, [deleteDialogOpen]);
|
||||
|
||||
async function handleProfileClick(username: string) {
|
||||
if (!user.authToken) return;
|
||||
|
||||
setIsLoadingProfile(true);
|
||||
try {
|
||||
const profile = await fetchUserProfile(user.authToken, username);
|
||||
if (profile) {
|
||||
setSelectedUserProfile(profile);
|
||||
setProfileDialogOpen(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch user profile:", error);
|
||||
} finally {
|
||||
setIsLoadingProfile(false);
|
||||
}
|
||||
};
|
||||
|
||||
function handleContextMenu(e: React.MouseEvent, message: MessageType) {
|
||||
e.preventDefault();
|
||||
setContextMenu({
|
||||
isOpen: true,
|
||||
message,
|
||||
position: { x: e.clientX, y: e.clientY }
|
||||
});
|
||||
};
|
||||
|
||||
function handleContextMenuOpenChange(isOpen: boolean) {
|
||||
setContextMenu(prev => ({
|
||||
...prev,
|
||||
isOpen
|
||||
}));
|
||||
};
|
||||
|
||||
function handleEdit(message: MessageType) {
|
||||
if (onEditSelect) onEditSelect(message);
|
||||
};
|
||||
|
||||
function handleReply(message: MessageType) {
|
||||
if (onReplySelect) onReplySelect(message);
|
||||
};
|
||||
|
||||
async function confirmDelete() {
|
||||
if (!toBeDeleted || !user.authToken) return;
|
||||
try {
|
||||
onDelete?.(toBeDeleted.id);
|
||||
// if (toBeDeleted.isDm) {
|
||||
// // For DM, send dmDelete
|
||||
// await request({
|
||||
// type: "dmDelete",
|
||||
// data: { id: toBeDeleted.id },
|
||||
// credentials: { scheme: "Bearer", credentials: user.authToken }
|
||||
// });
|
||||
// } else {
|
||||
// await request({
|
||||
// type: "deleteMessage",
|
||||
// data: { message_id: toBeDeleted.id },
|
||||
// credentials: { scheme: "Bearer", credentials: user.authToken }
|
||||
// });
|
||||
// }
|
||||
} catch (error) {
|
||||
console.error("Failed to delete message:", error);
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
}
|
||||
|
||||
async function handleDelete(message: MessageType) {
|
||||
setToBeDeleted({ id: message.id, isDm });
|
||||
setDeleteDialogOpen(true);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="chat-messages" id="chat-messages">
|
||||
{messages.map((message) => (
|
||||
<Message
|
||||
key={message.id}
|
||||
message={message}
|
||||
isAuthor={message.username === user.currentUser?.username}
|
||||
onProfileClick={handleProfileClick}
|
||||
onContextMenu={handleContextMenu}
|
||||
isLoadingProfile={isLoadingProfile}
|
||||
isDm={isDm}
|
||||
dmRecipientPublicKey={dmRecipientPublicKey} />
|
||||
))}
|
||||
{children}
|
||||
</div>
|
||||
|
||||
<UserProfileDialog
|
||||
isOpen={profileDialogOpen}
|
||||
onOpenChange={async (value) => {
|
||||
setProfileDialogOpen(value);
|
||||
if (!value) {
|
||||
await delay(1000);
|
||||
setSelectedUserProfile(null);
|
||||
}
|
||||
}}
|
||||
userProfile={selectedUserProfile}
|
||||
/>
|
||||
|
||||
<MaterialDialog
|
||||
headline="Удалить сообщение?"
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={setDeleteDialogOpen}>
|
||||
<mdui-button slot="action" variant="tonal" onClick={() => setDeleteDialogOpen(false)}>Отменить</mdui-button>
|
||||
<mdui-button slot="action" variant="filled" onClick={confirmDelete}>Удалить</mdui-button>
|
||||
</MaterialDialog>
|
||||
|
||||
{/* Context Menu */}
|
||||
{contextMenu.message && (
|
||||
<MessageContextMenu
|
||||
message={contextMenu.message}
|
||||
isAuthor={contextMenu.message.username === user.currentUser?.username}
|
||||
onEdit={handleEdit}
|
||||
onReply={handleReply}
|
||||
onDelete={handleDelete}
|
||||
position={contextMenu.position}
|
||||
isOpen={contextMenu.isOpen}
|
||||
onOpenChange={handleContextMenuOpenChange}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useChat } from "../../hooks/useChat";
|
||||
|
||||
export function ChatTabs() {
|
||||
const { activeTab, setActiveTab, setCurrentChat } = useChat();
|
||||
|
||||
const handleChatClick = (chatName: string) => {
|
||||
setCurrentChat(chatName);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="chat-tabs">
|
||||
<mdui-tabs value={activeTab} full-width onChange={(e: any) => setActiveTab(e.detail.value)}>
|
||||
<mdui-tab value="chats">
|
||||
Чаты
|
||||
</mdui-tab>
|
||||
<mdui-tab value="channels">
|
||||
Каналы
|
||||
</mdui-tab>
|
||||
<mdui-tab value="contacts">
|
||||
Контакты
|
||||
</mdui-tab>
|
||||
<mdui-tab value="dms">
|
||||
ЛС
|
||||
</mdui-tab>
|
||||
|
||||
<mdui-tab-panel slot="panel" value="chats">
|
||||
<mdui-list>
|
||||
<mdui-list-item
|
||||
headline="Общий чат"
|
||||
description="Вы: Последнее сообщение"
|
||||
id="chat-list-chat-1"
|
||||
onClick={() => handleChatClick("Общий чат")}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<img src="./src/resources/images/default-avatar.png" alt="" slot="icon" />
|
||||
</mdui-list-item>
|
||||
<mdui-list-item
|
||||
headline="Общий чат 2"
|
||||
description="Вы: Последнее сообщение"
|
||||
id="chat-list-chat-2"
|
||||
onClick={() => handleChatClick("Общий чат 2")}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<img src="./src/resources/images/default-avatar.png" alt="" slot="icon" />
|
||||
</mdui-list-item>
|
||||
</mdui-list>
|
||||
</mdui-tab-panel>
|
||||
<mdui-tab-panel slot="panel" value="channels">Скоро будет...</mdui-tab-panel>
|
||||
<mdui-tab-panel slot="panel" value="contacts">Скоро будет...</mdui-tab-panel>
|
||||
<mdui-tab-panel slot="panel" value="dms">
|
||||
<mdui-list id="dm-users"></mdui-list>
|
||||
</mdui-tab-panel>
|
||||
</mdui-tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { useEffect } from "react";
|
||||
import { useDM } from "../../hooks/useDM";
|
||||
import { useAppState } from "../../state";
|
||||
import { fetchUserPublicKey } from "../../../api/dmApi";
|
||||
import defaultAvatar from "../../../resources/images/default-avatar.png";
|
||||
|
||||
export function DMUsersList() {
|
||||
const { dmUsers, isLoadingUsers, loadUsers } = useDM();
|
||||
const { chat, switchToDM } = useAppState();
|
||||
|
||||
useEffect(() => {
|
||||
if (chat.activeTab === "dms") {
|
||||
loadUsers();
|
||||
}
|
||||
}, [chat.activeTab, loadUsers]);
|
||||
|
||||
if (isLoadingUsers) {
|
||||
return (
|
||||
<mdui-list>
|
||||
<mdui-list-item headline="Загрузка..." description="Получение списка пользователей...">
|
||||
<img src={defaultAvatar} alt="" slot="icon" />
|
||||
</mdui-list-item>
|
||||
</mdui-list>
|
||||
);
|
||||
}
|
||||
|
||||
if (dmUsers.length === 0) {
|
||||
return (
|
||||
<mdui-list>
|
||||
<mdui-list-item headline="Нет пользователей" description="Пользователи не найдены">
|
||||
<img src={defaultAvatar} alt="" slot="icon" />
|
||||
</mdui-list-item>
|
||||
</mdui-list>
|
||||
);
|
||||
}
|
||||
|
||||
const handleUserClick = async (user: any) => {
|
||||
if (!user.publicKey) {
|
||||
// Get public key if not already loaded
|
||||
const authToken = useAppState.getState().user.authToken;
|
||||
if (!authToken) return;
|
||||
|
||||
const publicKey = await fetchUserPublicKey(user.id, authToken);
|
||||
if (publicKey) {
|
||||
user.publicKey = publicKey;
|
||||
} else {
|
||||
console.error("Failed to get public key for user:", user.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await switchToDM({
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
publicKey: user.publicKey,
|
||||
profilePicture: user.profile_picture,
|
||||
online: user.online || false
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<mdui-list>
|
||||
{dmUsers.map((user) => (
|
||||
<mdui-list-item
|
||||
key={user.id}
|
||||
headline={user.username}
|
||||
description={user.lastMessage || "Нет сообщений"}
|
||||
onClick={() => handleUserClick(user)}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<img
|
||||
src={user.profile_picture || defaultAvatar}
|
||||
alt={user.username}
|
||||
slot="icon"
|
||||
style={{
|
||||
width: "40px",
|
||||
height: "40px",
|
||||
borderRadius: "50%",
|
||||
objectFit: "cover"
|
||||
}}
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).src = defaultAvatar;
|
||||
}}
|
||||
/>
|
||||
{user.unreadCount > 0 && (
|
||||
<mdui-badge slot="end-icon">
|
||||
{user.unreadCount}
|
||||
</mdui-badge>
|
||||
)}
|
||||
</mdui-list-item>
|
||||
))}
|
||||
</mdui-list>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { PRODUCT_NAME } from "../../../core/config";
|
||||
import { useAppState } from "../../state";
|
||||
import defaultAvatar from "../../../resources/images/default-avatar.png";
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { ProfileDialog } from "../profile/ProfileDialog";
|
||||
import { SettingsDialog } from "../settings/SettingsDialog";
|
||||
import { DMUsersList } from "./DMUsersList";
|
||||
import type { Tabs } from "mdui";
|
||||
import type { ChatTabs } from "../../state";
|
||||
|
||||
function BottomAppBar() {
|
||||
const [settingsOpen, onSettingsOpenChange] = useState(false);
|
||||
const { logout } = useAppState();
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<mdui-bottom-app-bar>
|
||||
<mdui-button-icon icon="settings--filled" id="settings-open" onClick={() => onSettingsOpenChange(true)}></mdui-button-icon>
|
||||
<mdui-button-icon icon="group_add--filled"></mdui-button-icon>
|
||||
<div style={{ flexGrow: 1 }}></div>
|
||||
<mdui-button-icon
|
||||
icon="logout--filled"
|
||||
id="logout-btn"
|
||||
onClick={handleLogout}
|
||||
title="Выйти"
|
||||
></mdui-button-icon>
|
||||
<mdui-fab icon="edit--filled"></mdui-fab>
|
||||
</mdui-bottom-app-bar>
|
||||
<SettingsDialog isOpen={settingsOpen} onOpenChange={onSettingsOpenChange} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function ChatTabs() {
|
||||
const { chat, switchToTab, switchToPublicChat } = useAppState();
|
||||
const { activeTab } = chat;
|
||||
|
||||
const handleChatClick = async (chatName: string) => {
|
||||
await switchToPublicChat(chatName);
|
||||
};
|
||||
|
||||
const handleTabChange = async (e: FormEvent<Tabs>) => {
|
||||
const tab = (e.target as Tabs).value as ChatTabs;
|
||||
await switchToTab(tab);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="chat-tabs">
|
||||
<mdui-tabs value={activeTab} full-width onChange={handleTabChange}>
|
||||
<mdui-tab value="chats">Чаты</mdui-tab>
|
||||
<mdui-tab value="channels">Каналы</mdui-tab>
|
||||
<mdui-tab value="contacts">Контакты</mdui-tab>
|
||||
<mdui-tab value="dms">ЛС</mdui-tab>
|
||||
|
||||
<mdui-tab-panel slot="panel" value="chats">
|
||||
<mdui-list>
|
||||
<mdui-list-item
|
||||
headline="Общий чат"
|
||||
description="Вы: Последнее сообщение"
|
||||
id="chat-list-chat-1"
|
||||
onClick={() => handleChatClick("Общий чат")}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<img src={defaultAvatar} alt="" slot="icon" />
|
||||
</mdui-list-item>
|
||||
<mdui-list-item
|
||||
headline="Общий чат 2"
|
||||
description="Вы: Последнее сообщение"
|
||||
id="chat-list-chat-2"
|
||||
onClick={() => handleChatClick("Общий чат 2")}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<img src={defaultAvatar} alt="" slot="icon" />
|
||||
</mdui-list-item>
|
||||
</mdui-list>
|
||||
</mdui-tab-panel>
|
||||
<mdui-tab-panel slot="panel" value="channels">Скоро будет...</mdui-tab-panel>
|
||||
<mdui-tab-panel slot="panel" value="contacts">Скоро будет...</mdui-tab-panel>
|
||||
<mdui-tab-panel slot="panel" value="dms">
|
||||
<DMUsersList />
|
||||
</mdui-tab-panel>
|
||||
</mdui-tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function ChatHeader() {
|
||||
const [isProfileOpen, setProfileOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<header className="chat-header-left">
|
||||
<div className="product-name">{PRODUCT_NAME}</div>
|
||||
<div className="profile">
|
||||
<a href="#" id="profile-open" onClick={() => setProfileOpen(true)}>
|
||||
<img src={defaultAvatar} alt="" id="preview1" />
|
||||
</a>
|
||||
</div>
|
||||
<ProfileDialog isOpen={isProfileOpen} onOpenChange={setProfileOpen} />
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export function LeftPanel() {
|
||||
return (
|
||||
<div className="chat-list" id="chat-list">
|
||||
<ChatHeader />
|
||||
<ChatTabs />
|
||||
<BottomAppBar />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
import { formatTime } from "../../../utils/utils";
|
||||
import type { Attachment, Message as MessageType } from "../../../core/types";
|
||||
import defaultAvatar from "../../../resources/images/default-avatar.png";
|
||||
import Quote from "../core/Quote";
|
||||
import { parse } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { getCurrentKeys } from "../../../auth/crypto";
|
||||
import { ecdhSharedSecret, deriveWrappingKey } from "../../../utils/crypto/asymmetric";
|
||||
import { importAesGcmKey, aesGcmDecrypt } from "../../../utils/crypto/symmetric";
|
||||
import { getAuthHeaders } from "../../../auth/api";
|
||||
import { useAppState } from "../../state";
|
||||
import { ub64 } from "../../../utils/utils";
|
||||
import { useImmer } from "use-immer";
|
||||
|
||||
interface MessageProps {
|
||||
message: MessageType;
|
||||
isAuthor: boolean;
|
||||
onProfileClick: (username: string) => void;
|
||||
onContextMenu: (e: React.MouseEvent, message: MessageType) => void;
|
||||
isLoadingProfile?: boolean;
|
||||
isDm?: boolean;
|
||||
dmRecipientPublicKey?: string;
|
||||
}
|
||||
|
||||
interface Rect {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number
|
||||
}
|
||||
|
||||
export function Message({ message, isAuthor, onProfileClick, onContextMenu, isLoadingProfile = false, isDm = false, dmRecipientPublicKey }: MessageProps) {
|
||||
const [formattedMessage, setFormattedMessage] = useState({ __html: "" });
|
||||
const [decryptedFiles, updateDecryptedFiles] = useImmer<Map<string, string>>(new Map());
|
||||
const [loadedImages, updateLoadedImages] = useImmer<Set<string>>(new Set());
|
||||
const [downloadingPaths, updateDownloadingPaths] = useImmer<Set<string>>(new Set());
|
||||
const [isDownloadingFullscreen, setIsDownloadingFullscreen] = useState(false);
|
||||
const [fullscreenImage, setFullscreenImage] = useState<{
|
||||
src: string;
|
||||
name: string;
|
||||
element: HTMLImageElement;
|
||||
startRect: Rect;
|
||||
endRect: Rect;
|
||||
} | null>(null);
|
||||
const [isAnimatingOpen, setIsAnimatingOpen] = useState(false);
|
||||
const { user } = useAppState();
|
||||
const imageRefs = useRef<Map<string, HTMLImageElement>>(new Map());
|
||||
const dmEnvelope = message.runtimeData?.dmEnvelope;
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
setFormattedMessage({
|
||||
__html: DOMPurify.sanitize(
|
||||
await parse(message.content)
|
||||
).trim()
|
||||
});
|
||||
})();
|
||||
}, [message]);
|
||||
|
||||
// Auto-decrypt images in DMs
|
||||
useEffect(() => {
|
||||
if (isDm && message.files) {
|
||||
message.files.forEach(async (file) => {
|
||||
console.log(file);
|
||||
const isImage = /\.(png|jpg|jpeg|gif|webp)$/i.test(file.name || "");
|
||||
if (isImage && file.encrypted && !decryptedFiles.has(file.path)) {
|
||||
console.log("Decrypting...");
|
||||
const decryptedUrl = await decryptFile(file);
|
||||
console.log(decryptedUrl);
|
||||
if (decryptedUrl) {
|
||||
updateDecryptedFiles(draft => {
|
||||
draft.set(file.path, decryptedUrl);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [message.files, isDm, decryptedFiles]);
|
||||
|
||||
const decryptFile = async (file: Attachment): Promise<string | null> => {
|
||||
if (!file.encrypted || !isDm || !user.authToken || !dmRecipientPublicKey || !dmEnvelope) {
|
||||
debugger;
|
||||
console.warn("Conditions not met")
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if already decrypted
|
||||
if (decryptedFiles.has(file.path)) {
|
||||
return decryptedFiles.get(file.path) || null;
|
||||
}
|
||||
|
||||
try {
|
||||
// no-op decrypt indicator removed from UI
|
||||
// Fetch encrypted file
|
||||
const response = await fetch(file.path, {
|
||||
headers: getAuthHeaders(user.authToken!)
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to fetch file");
|
||||
|
||||
const encryptedData = await response.arrayBuffer();
|
||||
|
||||
// Get current user's keys
|
||||
const keys = getCurrentKeys();
|
||||
if (!keys) throw new Error("Keys not initialized");
|
||||
|
||||
// Derive shared secret with the recipient's public key
|
||||
const shared = await ecdhSharedSecret(keys.privateKey, ub64(dmRecipientPublicKey));
|
||||
|
||||
// Derive wrapping key using the salt from the DM envelope
|
||||
const wkRaw = await deriveWrappingKey(shared, ub64(dmEnvelope.salt), new Uint8Array([1]));
|
||||
const wk = await importAesGcmKey(wkRaw);
|
||||
|
||||
// Unwrap the message key
|
||||
const mk = await aesGcmDecrypt(wk, ub64(dmEnvelope.iv2), ub64(dmEnvelope.wrappedMk));
|
||||
|
||||
// Decrypt the file using the message key
|
||||
const iv = new Uint8Array(encryptedData, 0, 12);
|
||||
const ciphertext = new Uint8Array(encryptedData, 12);
|
||||
const decrypted = await aesGcmDecrypt(await importAesGcmKey(mk), iv, ciphertext);
|
||||
|
||||
// Create blob URL for download
|
||||
const blob = new Blob([decrypted.buffer as ArrayBuffer]);
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
updateDecryptedFiles(draft => {
|
||||
draft.set(file.path, url);
|
||||
});
|
||||
return url;
|
||||
} catch (error) {
|
||||
console.error("Failed to decrypt file:", error);
|
||||
return null;
|
||||
} finally {
|
||||
// no-op decrypt indicator removed from UI
|
||||
}
|
||||
};
|
||||
|
||||
const handleImageClick = async (file: Attachment, imageElement: HTMLImageElement) => {
|
||||
// Use decrypted URL if available, otherwise decrypt first
|
||||
const decryptedUrl = decryptedFiles.get(file.path);
|
||||
if (decryptedUrl) {
|
||||
openFullscreenFromThumb(imageElement, decryptedUrl, file.name || "image");
|
||||
} else if (file.encrypted && isDm) {
|
||||
const newDecryptedUrl = await decryptFile(file);
|
||||
if (newDecryptedUrl) {
|
||||
openFullscreenFromThumb(imageElement, newDecryptedUrl, file.name || "image");
|
||||
}
|
||||
} else {
|
||||
openFullscreenFromThumb(imageElement, file.path, file.name || "image");
|
||||
}
|
||||
};
|
||||
|
||||
const computeEndRect = (naturalWidth: number, naturalHeight: number): Rect => {
|
||||
const viewportWidth = window.innerWidth;
|
||||
const viewportHeight = window.innerHeight;
|
||||
const maxWidth = Math.floor(viewportWidth * 0.9);
|
||||
const maxHeight = Math.floor(viewportHeight * 0.9);
|
||||
const widthRatio = maxWidth / naturalWidth;
|
||||
const heightRatio = maxHeight / naturalHeight;
|
||||
const scale = Math.min(widthRatio, heightRatio, 1);
|
||||
const width = Math.round(naturalWidth * scale);
|
||||
const height = Math.round(naturalHeight * scale);
|
||||
const left = Math.round((viewportWidth - width) / 2);
|
||||
const top = Math.round((viewportHeight - height) / 2);
|
||||
return { left, top, width, height };
|
||||
};
|
||||
|
||||
const openFullscreenFromThumb = (imgEl: HTMLImageElement, src: string, name: string) => {
|
||||
const rect = imgEl.getBoundingClientRect();
|
||||
const startRect = { left: rect.left, top: rect.top, width: rect.width, height: rect.height };
|
||||
const tempImg = new Image();
|
||||
tempImg.src = src;
|
||||
// Hide original while animating
|
||||
imgEl.style.visibility = "hidden";
|
||||
tempImg.onload = () => {
|
||||
const endRect = computeEndRect(tempImg.naturalWidth, tempImg.naturalHeight);
|
||||
setFullscreenImage({
|
||||
src,
|
||||
name,
|
||||
element: imgEl,
|
||||
startRect,
|
||||
endRect
|
||||
});
|
||||
// Start animation on next frame to ensure DOM has overlay mounted
|
||||
requestAnimationFrame(() => setIsAnimatingOpen(true));
|
||||
};
|
||||
};
|
||||
|
||||
const closeFullscreen = () => {
|
||||
// Reverse animation
|
||||
setIsAnimatingOpen(false);
|
||||
// Wait for transition to finish
|
||||
setTimeout(() => {
|
||||
if (fullscreenImage?.element) {
|
||||
fullscreenImage.element.style.visibility = "visible";
|
||||
}
|
||||
setFullscreenImage(null);
|
||||
}, 300);
|
||||
};
|
||||
|
||||
const downloadImage = async () => {
|
||||
if (!fullscreenImage) return;
|
||||
const { src, name } = fullscreenImage;
|
||||
try {
|
||||
setIsDownloadingFullscreen(true);
|
||||
if (src.startsWith("blob:")) {
|
||||
const link = document.createElement("a");
|
||||
link.href = src;
|
||||
link.download = name;
|
||||
link.click();
|
||||
setIsDownloadingFullscreen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch with credentials/headers when not a blob URL
|
||||
const response = await fetch(src, {
|
||||
headers: user.authToken ? getAuthHeaders(user.authToken) : undefined,
|
||||
credentials: "include"
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to download image");
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = name;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
} finally {
|
||||
setIsDownloadingFullscreen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const downloadFile = async (file: Attachment) => {
|
||||
try {
|
||||
updateDownloadingPaths(draft => {
|
||||
draft.add(file.path);
|
||||
});
|
||||
// Prefer decrypted URL if present (DM encrypted case)
|
||||
const decrypted = decryptedFiles.get(file.path);
|
||||
if (decrypted) {
|
||||
const link = document.createElement("a");
|
||||
link.href = decrypted;
|
||||
link.download = file.name || "file";
|
||||
link.click();
|
||||
updateDownloadingPaths(draft => {
|
||||
draft.delete(file.path);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// If not decrypted or public file, fetch with credentials/headers
|
||||
const response = await fetch(file.path, {
|
||||
headers: user.authToken ? getAuthHeaders(user.authToken) : undefined,
|
||||
credentials: "include"
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to download file");
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = file.name || "file";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
} finally {
|
||||
updateDownloadingPaths(draft => {
|
||||
draft.delete(file.path);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
function handleContextMenu(e: React.MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onContextMenu(e, message);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`message ${isAuthor ? "sent" : "received"}`}
|
||||
data-id={message.id}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
<div className="message-inner">
|
||||
{/* Add profile picture for received messages */}
|
||||
{!isAuthor && !isDm && (
|
||||
<div className="message-profile-pic">
|
||||
<img
|
||||
src={message.profile_picture || defaultAvatar}
|
||||
alt={message.username}
|
||||
onClick={() => !isLoadingProfile && onProfileClick(message.username)}
|
||||
style={{ cursor: isLoadingProfile ? "default" : "pointer" }}
|
||||
className={isLoadingProfile ? "loading" : ""}
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.src = defaultAvatar;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isAuthor && !isDm && (
|
||||
<div
|
||||
className={`message-username ${isLoadingProfile ? "loading" : ""}`}
|
||||
onClick={() => !isLoadingProfile && onProfileClick(message.username)}
|
||||
style={{ cursor: isLoadingProfile ? "default" : "pointer" }}>
|
||||
{message.username}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add reply preview if this is a reply */}
|
||||
{message.reply_to && (
|
||||
<Quote className="reply-preview contextual-content" background={isAuthor ? "primaryContainer" : "surfaceContainer"}>
|
||||
<span className="reply-username">{message.reply_to.username}</span>
|
||||
<span className="reply-text">{message.reply_to.content}</span>
|
||||
</Quote>
|
||||
)}
|
||||
|
||||
<div className="message-content" dangerouslySetInnerHTML={formattedMessage} />
|
||||
|
||||
{message.files && message.files.length > 0 && (
|
||||
<mdui-list className="message-attachments">
|
||||
{message.files.map((file, idx) => {
|
||||
const isImage = /\.(png|jpg|jpeg|gif|webp)$/i.test(file.name || "");
|
||||
const isEncryptedDm = Boolean(isDm && file.encrypted);
|
||||
const decryptedUrl = decryptedFiles.get(file.path);
|
||||
const imageSrc = isImage ? (isEncryptedDm ? decryptedUrl : file.path) : undefined;
|
||||
const isDownloading = downloadingPaths.has(file.path);
|
||||
|
||||
return (
|
||||
<div className="attachment" key={idx}>
|
||||
{isImage ? (
|
||||
<div className="image-wrapper">
|
||||
<img
|
||||
ref={(el) => {
|
||||
if (el) imageRefs.current.set(file.path, el);
|
||||
}}
|
||||
src={imageSrc}
|
||||
alt={file.name || "image"}
|
||||
onClick={(e) => handleImageClick(file, e.currentTarget)}
|
||||
onLoad={() => updateLoadedImages(draft => { draft.add(file.path); })}
|
||||
className={`attachement-image ${loadedImages.has(file.path) ? "" : "loading"}`}
|
||||
/>
|
||||
{!loadedImages.has(file.path) && (
|
||||
<div className="loading-overlay">
|
||||
<mdui-circular-progress />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<a
|
||||
href="#"
|
||||
onClick={async (e) => {
|
||||
e.preventDefault();
|
||||
await downloadFile(file);
|
||||
}}
|
||||
>
|
||||
<mdui-list-item>
|
||||
<span className="with-icon-gap">
|
||||
{isDownloading ? <mdui-circular-progress /> : null}
|
||||
{(file.name || file.path.split("/").pop() || "Имя файла неизвестно").replace(/\d+_\d+_/, "")}
|
||||
</span>
|
||||
</mdui-list-item>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</mdui-list>
|
||||
)}
|
||||
|
||||
<div className="message-time">
|
||||
{formatTime(message.timestamp)}
|
||||
{message.is_edited ? " (edited)" : undefined}
|
||||
|
||||
{isAuthor && message.is_read && (
|
||||
<span className="material-symbols outlined"></span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Fullscreen Image Viewer with shared-element like transition */}
|
||||
{fullscreenImage && (
|
||||
<div
|
||||
className={`fullscreen-image-overlay ${isAnimatingOpen ? "open" : "closing"}`}
|
||||
onClick={closeFullscreen}>
|
||||
<img
|
||||
src={fullscreenImage.src}
|
||||
alt={fullscreenImage.name}
|
||||
className={`fullscreen-animated-image ${isAnimatingOpen ? "to-end" : "to-start"}`}
|
||||
style={{
|
||||
left: `${isAnimatingOpen ? fullscreenImage.endRect.left : fullscreenImage.startRect.left}px`,
|
||||
top: `${isAnimatingOpen ? fullscreenImage.endRect.top : fullscreenImage.startRect.top}px`,
|
||||
width: `${isAnimatingOpen ? fullscreenImage.endRect.width : fullscreenImage.startRect.width}px`,
|
||||
height: `${isAnimatingOpen ? fullscreenImage.endRect.height : fullscreenImage.startRect.height}px`
|
||||
}}
|
||||
onClick={e => e.stopPropagation()}
|
||||
/>
|
||||
<div className="fullscreen-controls top-right" onClick={e => e.stopPropagation()}>
|
||||
<mdui-button-icon icon="close" onClick={closeFullscreen} />
|
||||
{isDownloadingFullscreen ? (
|
||||
<div className="progress-wrapper">
|
||||
<mdui-circular-progress />
|
||||
</div>
|
||||
) : (
|
||||
<mdui-button-icon icon="download" onClick={downloadImage} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import type { Message, Size2D } from "../../../core/types";
|
||||
|
||||
interface MessageContextMenuProps {
|
||||
message: Message;
|
||||
isAuthor: boolean;
|
||||
onEdit: (message: Message) => void;
|
||||
onReply: (message: Message) => void;
|
||||
onDelete: (message: Message) => void;
|
||||
position: Size2D;
|
||||
isOpen: boolean;
|
||||
onOpenChange: (isOpen: boolean) => void;
|
||||
}
|
||||
|
||||
export interface ContextMenuState {
|
||||
isOpen: boolean;
|
||||
message: Message | null;
|
||||
position: Size2D;
|
||||
}
|
||||
|
||||
export function MessageContextMenu({
|
||||
message,
|
||||
isAuthor,
|
||||
onEdit,
|
||||
onReply,
|
||||
onDelete,
|
||||
position,
|
||||
isOpen,
|
||||
onOpenChange
|
||||
}: MessageContextMenuProps) {
|
||||
// Internal state for closing animation
|
||||
const [isClosing, setIsClosing] = useState(false);
|
||||
const [calculatedPosition, setCalculatedPosition] = useState(position);
|
||||
const [animationClass, setAnimationClass] = useState('entering');
|
||||
|
||||
// Calculate smart positioning when component opens
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
const menuWidth = 160; // min-width from CSS
|
||||
const menuHeight = isAuthor ? 120 : 60; // Approximate height based on items
|
||||
const padding = 10; // Padding from viewport edges
|
||||
|
||||
const viewportWidth = window.innerWidth;
|
||||
const viewportHeight = window.innerHeight;
|
||||
|
||||
let x = position.x;
|
||||
let y = position.y;
|
||||
let animation = 'entering';
|
||||
|
||||
// Check if menu would overflow right edge
|
||||
if (x + menuWidth + padding > viewportWidth) {
|
||||
x = viewportWidth - menuWidth - padding;
|
||||
animation = 'entering-left'; // Animation from left side
|
||||
}
|
||||
|
||||
// Check if menu would overflow bottom edge
|
||||
if (y + menuHeight + padding > viewportHeight) {
|
||||
y = viewportHeight - menuHeight - padding;
|
||||
animation = 'entering-up'; // Animation from bottom
|
||||
}
|
||||
|
||||
// If both edges would overflow, use top-left positioning
|
||||
if (x + menuWidth + padding > viewportWidth && y + menuHeight + padding > viewportHeight) {
|
||||
x = Math.max(padding, position.x - menuWidth);
|
||||
y = Math.max(padding, position.y - menuHeight);
|
||||
animation = 'entering-up-left';
|
||||
}
|
||||
|
||||
setCalculatedPosition({ x, y });
|
||||
setAnimationClass(animation);
|
||||
}
|
||||
}, [isOpen, position, isAuthor]);
|
||||
|
||||
// Effect to handle clicks outside the context menu
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (isOpen && !isClosing) {
|
||||
// Check if the click is on a context menu element
|
||||
const target = event.target as Element;
|
||||
if (!target.closest('.context-menu')) {
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && isOpen && !isClosing) {
|
||||
handleClose();
|
||||
}
|
||||
};
|
||||
|
||||
const handleWindowBlur = () => {
|
||||
// Close context menu when browser window loses focus
|
||||
if (isOpen && !isClosing) {
|
||||
handleClose();
|
||||
}
|
||||
};
|
||||
|
||||
// Add event listeners
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
window.addEventListener('blur', handleWindowBlur);
|
||||
|
||||
// Cleanup
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
window.removeEventListener('blur', handleWindowBlur);
|
||||
};
|
||||
}, [isOpen, isClosing]);
|
||||
|
||||
const handleAction = (action: string) => {
|
||||
switch (action) {
|
||||
case "reply":
|
||||
onReply(message);
|
||||
handleClose();
|
||||
break;
|
||||
case "edit":
|
||||
if (isAuthor) onEdit(message);
|
||||
break;
|
||||
case "delete":
|
||||
if (isAuthor) {
|
||||
onDelete(message);
|
||||
handleClose();
|
||||
}
|
||||
break;
|
||||
}
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setIsClosing(true);
|
||||
// Set appropriate closing animation based on opening animation
|
||||
const closingAnimation = animationClass.replace('entering', 'closing');
|
||||
setAnimationClass(closingAnimation);
|
||||
|
||||
// Wait for animation to complete before calling onOpenChange
|
||||
setTimeout(() => {
|
||||
onOpenChange(false);
|
||||
setIsClosing(false);
|
||||
setAnimationClass('entering'); // Reset for next opening
|
||||
}, 200); // Match the animation duration from _animations.scss
|
||||
};
|
||||
|
||||
return isOpen && (
|
||||
<div
|
||||
className={`context-menu ${animationClass}`}
|
||||
style={{
|
||||
position: "fixed",
|
||||
display: "block",
|
||||
top: calculatedPosition.y,
|
||||
left: calculatedPosition.x,
|
||||
zIndex: 1000
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}>
|
||||
<div className="context-menu-item" onClick={() => handleAction("reply")}>
|
||||
<span className="material-symbols">reply</span>
|
||||
Ответить
|
||||
</div>
|
||||
{isAuthor && (
|
||||
<>
|
||||
<div className="context-menu-item" onClick={() => handleAction("edit")}>
|
||||
<span className="material-symbols">edit</span>
|
||||
Редактировать
|
||||
</div>
|
||||
<div className="context-menu-item" onClick={() => handleAction("delete")}>
|
||||
<span className="material-symbols">delete</span>
|
||||
Удалить
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { MessagePanel, type MessagePanelState } from "../../panels/MessagePanel";
|
||||
import { ChatMessages } from "./ChatMessages";
|
||||
import { ChatInputWrapper } from "./ChatInputWrapper";
|
||||
import { setGlobalMessageHandler } from "../../../core/websocket";
|
||||
import type { Message } from "../../../core/types";
|
||||
import defaultAvatar from "../../../resources/images/default-avatar.png";
|
||||
import AnimatedOpacity from "../core/animations/AnimatedOpacity";
|
||||
import type { DMPanel } from "../../panels/DMPanel";
|
||||
|
||||
interface MessagePanelRendererProps {
|
||||
panel: MessagePanel | null;
|
||||
isChatSwitching: boolean;
|
||||
}
|
||||
|
||||
export function MessagePanelRenderer({ panel, isChatSwitching }: MessagePanelRendererProps) {
|
||||
const [panelState, setPanelState] = useState<MessagePanelState | null>(null);
|
||||
const [switchIn, setSwitchIn] = useState(false);
|
||||
const [switchOut, setSwitchOut] = useState(false);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const [replyTo, setReplyTo] = useState<Message | null>(null);
|
||||
const [replyToVisible, setReplyToVisible] = useState(Boolean(replyTo));
|
||||
const [editMessage, setEditMessage] = useState<Message | null>(null);
|
||||
const [editVisible, setEditVisible] = useState(Boolean(editMessage));
|
||||
const [pendingAction, setPendingAction] = useState<null | { type: "reply" | "edit"; message: Message }>(null);
|
||||
|
||||
// Drag & drop
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const dragCounterRef = useRef(0);
|
||||
const addFilesRef = useRef<null | ((files: File[]) => void)>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!panel || !panelState) return;
|
||||
|
||||
return () => {
|
||||
dragCounterRef.current = 0;
|
||||
setIsDragging(false);
|
||||
};
|
||||
}, [panel, panelState]);
|
||||
|
||||
useEffect(() => {
|
||||
if (replyTo) {
|
||||
setReplyToVisible(true);
|
||||
}
|
||||
}, [replyTo]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editMessage) {
|
||||
setEditVisible(true);
|
||||
}
|
||||
}, [editMessage]);
|
||||
|
||||
// Handle panel state changes
|
||||
useEffect(() => {
|
||||
if (panel) {
|
||||
setPanelState(panel.getState());
|
||||
|
||||
// Set up state change listener
|
||||
const handleStateChange = (newState: MessagePanelState) => {
|
||||
setPanelState(newState);
|
||||
};
|
||||
|
||||
// Store the handler for cleanup
|
||||
panel.onStateChange = handleStateChange;
|
||||
|
||||
// Set up WebSocket message handler for this panel
|
||||
if (panel.handleWebSocketMessage) {
|
||||
setGlobalMessageHandler(panel.handleWebSocketMessage);
|
||||
}
|
||||
} else {
|
||||
setPanelState(null);
|
||||
// Clear global message handler when no panel is active
|
||||
setGlobalMessageHandler(null);
|
||||
}
|
||||
|
||||
// Cleanup function
|
||||
return () => {
|
||||
if (panel && panel.onStateChange) {
|
||||
panel.onStateChange = null;
|
||||
}
|
||||
};
|
||||
}, [panel]);
|
||||
|
||||
// Handle chat switching animation
|
||||
useEffect(() => {
|
||||
if (isChatSwitching) {
|
||||
setSwitchOut(true);
|
||||
setTimeout(() => {
|
||||
setSwitchOut(false);
|
||||
setSwitchIn(true);
|
||||
setTimeout(() => setSwitchIn(false), 200);
|
||||
}, 250);
|
||||
}
|
||||
}, [isChatSwitching]);
|
||||
|
||||
// Scroll to bottom when messages change
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [panelState?.messages]);
|
||||
|
||||
if (!panel || !panelState) {
|
||||
return (
|
||||
<div className="chat-container">
|
||||
<div className="chat-main" id="chat-inner">
|
||||
<div className="chat-header">
|
||||
<img src={defaultAvatar} alt="Avatar" className="chat-header-avatar" />
|
||||
<div className="chat-header-info">
|
||||
<div className="info-chat">
|
||||
<h4 id="chat-name">Выбор чата</h4>
|
||||
<p>
|
||||
<span className="online-status"></span>
|
||||
Выберите чат, чтобы начать переписку
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="chat-messages" id="chat-messages">
|
||||
<div style={{
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
color: "var(--mdui-color-on-surface-variant)"
|
||||
}}>
|
||||
Выберите чат на боковой панели, чтобы начать переписку
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`chat-container ${switchIn ? "chat-switch-in" : ""} ${switchOut ? "chat-switch-out" : ""}`}>
|
||||
<div
|
||||
className="chat-main"
|
||||
id="chat-inner"
|
||||
onDragEnter={(e) => {
|
||||
if (!e.dataTransfer) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
dragCounterRef.current += 1;
|
||||
// Only show overlay when actual files are dragged
|
||||
const hasFiles = Array.from(e.dataTransfer.types || []).includes("Files");
|
||||
if (hasFiles) setIsDragging(true);
|
||||
}}
|
||||
onDragOver={(e) => {
|
||||
if (!e.dataTransfer) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.dataTransfer.dropEffect = "copy";
|
||||
}}
|
||||
onDragLeave={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
dragCounterRef.current = Math.max(0, dragCounterRef.current - 1);
|
||||
if (dragCounterRef.current === 0) setIsDragging(false);
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
if (!e.dataTransfer) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const files = Array.from(e.dataTransfer.files || []);
|
||||
if (files.length > 0 && addFilesRef.current) {
|
||||
addFilesRef.current(files);
|
||||
}
|
||||
setIsDragging(false);
|
||||
dragCounterRef.current = 0;
|
||||
}}>
|
||||
<div className="chat-header">
|
||||
<img
|
||||
src={panelState.profilePicture || defaultAvatar}
|
||||
alt="Avatar"
|
||||
className="chat-header-avatar"
|
||||
onClick={panel.handleProfileClick}
|
||||
style={{ cursor: "pointer" }}
|
||||
/>
|
||||
<div className="chat-header-info">
|
||||
<div className="info-chat">
|
||||
<h4 id="chat-name">{panelState.title}</h4>
|
||||
<p>
|
||||
<span className={`online-status ${panelState.online ? "online" : "offline"}`}></span>
|
||||
{panelState.online ? "Online" : "Offline"}
|
||||
{panelState.isTyping && " • Typing..."}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{panelState.isLoading ? (
|
||||
<div className="chat-messages" id="chat-messages">
|
||||
<div style={{
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
color: "var(--mdui-color-on-surface-variant)"
|
||||
}}>
|
||||
Загрузка сообщений...
|
||||
</div>
|
||||
</div>
|
||||
): (
|
||||
<ChatMessages
|
||||
messages={panelState.messages}
|
||||
isDm={panel.isDm()}
|
||||
dmRecipientPublicKey={(panel as DMPanel).dmData?.publicKey}
|
||||
onReplySelect={(message) => {
|
||||
if (editMessage || editVisible) {
|
||||
setPendingAction({ type: "reply", message: message });
|
||||
setEditVisible(false); // onCloseEdit will apply pending
|
||||
} else {
|
||||
setReplyTo(message);
|
||||
}
|
||||
}}
|
||||
onEditSelect={(message) => {
|
||||
if (replyTo || replyToVisible) {
|
||||
setPendingAction({ type: "edit", message: message });
|
||||
setReplyToVisible(false); // onCloseReply will apply pending
|
||||
} else {
|
||||
setEditMessage(message);
|
||||
}
|
||||
}}
|
||||
onDelete={(id) => panel.handleDeleteMessage(id)}
|
||||
>
|
||||
<div ref={messagesEndRef} />
|
||||
</ChatMessages>
|
||||
)}
|
||||
|
||||
<AnimatedOpacity
|
||||
visible={isDragging}
|
||||
className="file-overlay"
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => e.preventDefault()}>
|
||||
<div className="file-overlay-wrapper">
|
||||
<div className="file-overlay-inner">
|
||||
<mdui-icon name="upload_file" />
|
||||
<span>Отпустите файл(ы) для добавления</span>
|
||||
</div>
|
||||
</div>
|
||||
</AnimatedOpacity>
|
||||
|
||||
<ChatInputWrapper
|
||||
onSendMessage={(text, files) => {
|
||||
panel.handleSendMessage(text, replyTo?.id, files);
|
||||
setReplyTo(null);
|
||||
}}
|
||||
onSaveEdit={(content) => {
|
||||
if (editMessage) {
|
||||
panel.handleEditMessage(editMessage.id, content);
|
||||
setEditMessage(null);
|
||||
}
|
||||
}}
|
||||
replyTo={replyTo}
|
||||
replyToVisible={replyToVisible}
|
||||
onClearReply={() => {
|
||||
setPendingAction(null);
|
||||
setReplyToVisible(false);
|
||||
}}
|
||||
onCloseReply={() => {
|
||||
setReplyTo(null);
|
||||
if (pendingAction && pendingAction.type === "edit") {
|
||||
setEditMessage(pendingAction.message);
|
||||
setPendingAction(null);
|
||||
}
|
||||
}}
|
||||
editingMessage={editMessage}
|
||||
editVisible={editVisible}
|
||||
onClearEdit={() => {
|
||||
setPendingAction(null);
|
||||
setEditVisible(false);
|
||||
}}
|
||||
onCloseEdit={() => {
|
||||
setEditMessage(null);
|
||||
if (pendingAction && pendingAction.type === "reply") {
|
||||
setReplyTo(pendingAction.message);
|
||||
setPendingAction(null);
|
||||
}
|
||||
}}
|
||||
onProvideFileAdder={(adder) => { addFilesRef.current = adder; }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import type { Message } from "../../../core/types";
|
||||
import { MaterialDialog } from "../core/Dialog";
|
||||
import { MaterialTextField } from "../core/TextField";
|
||||
|
||||
interface ReplyMessageDialogProps {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (value: boolean) => void;
|
||||
replyToMessage: Message | null;
|
||||
onSendReply: (content: string, replyToId: number) => void;
|
||||
}
|
||||
|
||||
export function ReplyMessageDialog({ isOpen, onOpenChange, replyToMessage, onSendReply }: ReplyMessageDialogProps) {
|
||||
const [replyContent, setReplyContent] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (replyToMessage) {
|
||||
setReplyContent("");
|
||||
}
|
||||
}, [replyToMessage]);
|
||||
|
||||
const handleSendReply = () => {
|
||||
if (replyToMessage && replyContent.trim()) {
|
||||
onSendReply(replyContent.trim(), replyToMessage.id);
|
||||
onOpenChange(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
setReplyContent("");
|
||||
};
|
||||
|
||||
if (!replyToMessage) return null;
|
||||
|
||||
return (
|
||||
<MaterialDialog open={isOpen} onOpenChange={onOpenChange} close-on-overlay-click close-on-esc className="reply-dialog">
|
||||
<div className="dialog-content">
|
||||
<h3>Ответить на сообщение</h3>
|
||||
<div className="reply-preview-dialog">
|
||||
<div className="reply-content">
|
||||
<span className="reply-username">{replyToMessage.username}</span>
|
||||
<span className="reply-text">{replyToMessage.content}</span>
|
||||
</div>
|
||||
</div>
|
||||
<MaterialTextField
|
||||
value={replyContent}
|
||||
onInput={(e) => setReplyContent((e.target as HTMLInputElement).value)}
|
||||
label="Reply"
|
||||
variant="outlined"
|
||||
placeholder="Type your reply..."
|
||||
maxlength={1000} />
|
||||
<div className="dialog-actions">
|
||||
<mdui-button onClick={handleCancel} variant="outlined">Cancel</mdui-button>
|
||||
<mdui-button onClick={handleSendReply}>Send Reply</mdui-button>
|
||||
</div>
|
||||
</div>
|
||||
</MaterialDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useAppState } from "../../state";
|
||||
import { MessagePanelRenderer } from "./MessagePanelRenderer";
|
||||
|
||||
export function RightPanel() {
|
||||
const { chat } = useAppState();
|
||||
|
||||
return (
|
||||
<MessagePanelRenderer
|
||||
panel={chat.activePanel}
|
||||
isChatSwitching={chat.isChatSwitching}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { DialogProps } from "../../../core/types";
|
||||
import type { UserProfile } from "../../../core/types";
|
||||
import { MaterialDialog } from "../core/Dialog";
|
||||
import { formatTime } from "../../../utils/utils";
|
||||
import defaultAvatar from "../../../resources/images/default-avatar.png";
|
||||
|
||||
interface UserProfileDialogProps extends DialogProps {
|
||||
userProfile: UserProfile | null;
|
||||
}
|
||||
|
||||
export function UserProfileDialog({ isOpen, onOpenChange, userProfile }: UserProfileDialogProps) {
|
||||
const content = userProfile ? (
|
||||
<div className="content">
|
||||
<div className="profile-picture-section">
|
||||
<img
|
||||
className="profile-picture"
|
||||
alt="Profile Picture"
|
||||
src={userProfile.profile_picture || defaultAvatar}
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.src = defaultAvatar;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="profile-info">
|
||||
<div className="username-section">
|
||||
<h4 className="username">{userProfile.username}</h4>
|
||||
<div className={`online-status ${userProfile.online ? "online" : "offline"}`}>
|
||||
{userProfile.online ? (
|
||||
<>
|
||||
<span className="online-indicator"></span> Онлайн
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="offline-indicator"></span> Последний заход {formatTime(userProfile.last_seen)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bio-section">
|
||||
<label>О себе:</label>
|
||||
<div className="bio-display">
|
||||
{userProfile.bio || "No bio available."}
|
||||
</div>
|
||||
</div>
|
||||
<div className="profile-stats">
|
||||
<div className="stat">
|
||||
<span className="stat-label">Зарегистрирован:</span>
|
||||
<span className="stat-value member-since">{formatTime(userProfile.created_at)}</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<span className="stat-label">Last seen:</span>
|
||||
<span className="stat-value last-seen">{formatTime(userProfile.last_seen)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="profile-actions">
|
||||
<mdui-button id="dm-button" variant="filled">
|
||||
<mdui-icon slot="icon" name="chat--filled"></mdui-icon>
|
||||
Send Message
|
||||
</mdui-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null
|
||||
|
||||
return (
|
||||
<MaterialDialog open={isOpen} onOpenChange={onOpenChange} close-on-overlay-click close-on-esc id="user-profile-dialog">
|
||||
{content}
|
||||
</MaterialDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Dialog as MduiDialog } from "mdui/components/dialog";
|
||||
import { useEffect, type Ref } from "react"
|
||||
import { createPortal } from "react-dom";
|
||||
import { id } from "../../../utils/utils";
|
||||
import useCombinedRefs from "../../hooks/useCombinedRefs";
|
||||
|
||||
export interface BaseDialogProps {
|
||||
onOpenChange: (value: boolean) => void;
|
||||
ref?: Ref<MduiDialog & HTMLElement>
|
||||
}
|
||||
|
||||
export type FullDialogProps = React.ComponentPropsWithoutRef<"mdui-dialog"> & BaseDialogProps;
|
||||
|
||||
export function MaterialDialog(props: FullDialogProps) {
|
||||
const [setDialogRef, dialogRef] = useCombinedRefs(props.ref);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
mutations.forEach((mutation) => {
|
||||
if (mutation.type === "attributes" && mutation.attributeName === "open") {
|
||||
const isOpen = dialog.hasAttribute("open");
|
||||
if (isOpen !== props.open) {
|
||||
props.onOpenChange(isOpen);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Start observing the dialog element for attribute changes
|
||||
observer.observe(dialog, {
|
||||
attributes: true,
|
||||
attributeFilter: ["open"]
|
||||
});
|
||||
|
||||
// Cleanup observer
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [dialogRef.current, props.open, props.onOpenChange]);
|
||||
|
||||
return createPortal(<mdui-dialog {...props} ref={setDialogRef} />, id("root"));
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export interface QuoteProps {
|
||||
className?: string;
|
||||
children?: ReactNode;
|
||||
background?: "surfaceContainer" | "primaryContainer"
|
||||
}
|
||||
|
||||
export default function Quote({ className, children, background = "primaryContainer" }: QuoteProps) {
|
||||
return (
|
||||
<div className={`quote bg-${background} ${className}`}>
|
||||
<div className="quote-inner">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user