diff --git "a/app.py" "b/app.py" deleted file mode 100644--- "a/app.py" +++ /dev/null @@ -1,5704 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -Adusis — flagship single-file Flask application (v2) -==================================================== - -Однофайловое приложение, которое включает: - -1. Очередь запросов к JSON-базе (JsonDatabase). - Раньше каждый запрос заново скачивал data_adusis.json с Hugging Face, - и параллельные запросы «накладывались» друг на друга — история - (сообщения, лайки, просмотры) терялась, а HF возвращал ошибки. - Теперь: - * в памяти процесса живёт ЕДИНЫЙ экземпляр данных под RLock; - * все чтения работают с памятью (без скачивания на каждый запрос); - * все мутации проходят через `with db.write():` и попадают в - ОДНОПОТОЧНУЮ очередь записи (write queue) — файл пишется - атомарно (temp + os.replace); - * загрузка в Hugging Face вынесена в отдельную очередь с - COALESCE (слиянием) и retry/backoff — коммиты в HF никогда - не выполняются параллельно; - * фоновый sync подтягивает изменения с HF, только когда - локальных правок нет; - * присутствие (last_seen) пишется с дебаунсом, а не на каждый запрос. - Формат базы остался прежним — обычный JSON. - -2. PWA: manifest.json, service worker (офлайн-режим), иконки - (генерируются чистым Python, без внешних библиотек), кнопка - «Установить приложение» + детальная инструкция для iPhone. - -3. Push-уведомления по Web Push (VAPID + aes128gcm) на базе - библиотеки `cryptography`: подписка из установленного приложения, - уведомления о новых сообщениях и новых видео. - -4. Улучшенная авторизация: хеширование паролей (pbkdf2), вход - «запомнить меня» на 30 дней через server-side remember-токены, - стабильный secret key между перезапусками, защита от брутфорса. - -5. SEO: robots.txt, sitemap.xml (со всеми страницами и видео), - уникальные title/description/canonical, Open Graph, JSON-LD - (VideoObject / ImageObject / Person / ItemList). - -6. Новый «флагманский» интерфейс: адаптив под телефон и компьютер, - нижняя навигация на мобильных, стеклянные карточки, тосты, - тёмная тема, safe-area для iPhone. - -Запуск: python3 adusis_app.py (порт по умолчанию 7860) -""" - -import base64 -import hashlib -import hmac -import html -import io -import json -import logging -import os -import queue -import random -import re -import struct -import threading -import time -import uuid -import zlib -from contextlib import contextmanager -from datetime import datetime, timedelta -from functools import wraps - -from flask import (Flask, Response, flash, g, jsonify, redirect, - render_template_string, request, session, url_for) -from werkzeug.security import check_password_hash, generate_password_hash -from werkzeug.utils import secure_filename - -# ---------------------------------------------------------------- optional deps -try: - from huggingface_hub import HfApi, hf_hub_download - HF_AVAILABLE = True -except Exception: # pragma: no cover - HF_AVAILABLE = False - HfApi = None - hf_hub_download = None - -try: - from cryptography.hazmat.primitives import hashes, serialization - from cryptography.hazmat.primitives.asymmetric import ec - from cryptography.hazmat.primitives.ciphers.aead import AESGCM - from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand - from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature - CRYPTO_AVAILABLE = True -except Exception: # pragma: no cover - CRYPTO_AVAILABLE = False - -# ---------------------------------------------------------------------- config -BASE_DIR = os.path.dirname(os.path.abspath(__file__)) - -def _env(name, default=None): - v = os.getenv(name) - return v if v not in (None, "") else default - -def _env_int(name, default): - try: - return int(os.getenv(name, default)) - except (TypeError, ValueError): - return default - -def _env_bool(name, default=False): - return os.getenv(name, "").strip().lower() in ("1", "true", "yes", "on") if os.getenv(name) else default - -DATA_FILE = _env("DATA_FILE", os.path.join(BASE_DIR, "data_adusis.json")) -REPO_ID = _env("HF_REPO_ID", "Eluza133/A12d12s12") -HF_TOKEN_WRITE = _env("HF_TOKEN") -HF_TOKEN_READ = _env("HF_TOKEN_READ") or HF_TOKEN_WRITE -HF_DISABLED = _env_bool("HF_DISABLED", not HF_AVAILABLE) - -UPLOAD_FOLDER = _env("UPLOAD_FOLDER", os.path.join(BASE_DIR, "uploads")) -VAPID_FILE = _env("VAPID_FILE", os.path.join(BASE_DIR, "vapid_keys.json")) -SECRET_FILE = os.path.join(BASE_DIR, ".flask_secret_key") - -PORT = _env_int("PORT", 7860) -SESSION_DAYS = _env_int("SESSION_DAYS", 30) -MIN_PASSWORD_LEN = _env_int("MIN_PASSWORD_LENGTH", 6) -DB_SYNC_INTERVAL = _env_int("DB_SYNC_INTERVAL", 300) # сек между sync с HF -UPLOAD_RETRIES = _env_int("HF_UPLOAD_RETRIES", 4) -UPLOAD_MIN_INTERVAL = _env_int("HF_UPLOAD_MIN_INTERVAL", 10) # мин. пауза между коммитами в HF -VAPID_CONTACT = _env("VAPID_CONTACT", "mailto:admin@adusis.app") -MAX_UPLOAD_BYTES = _env_int("MAX_UPLOAD_MB", 100) * 1024 * 1024 -SITE_NAME = _env("SITE_NAME", "Adusis") -SITE_URL = (_env("SITE_URL", "") or "").rstrip("/") # напр. https://xxx.hf.space - -os.makedirs(UPLOAD_FOLDER, exist_ok=True) - -# ------------------------------------------------------------------ economics -USER_ROLES = ["white girl", "white boy", "couple", "BBC alpha bull"] -REFERRAL_REWARDS = { - "white girl": 100, - "couple": 100, - "BBC alpha bull": 100, - "white boy": 50, -} -DEFAULT_REWARD = 0 -UPLOAD_REWARD = 10 -VIEW_REWARD_AMOUNT = 50 -VIEW_REWARD_THRESHOLD = 200 -PROMOTE_COST = 50 -PROMOTE_DURATION_DAYS = 7 -LOGO_URL = "https://cdn-avatars.huggingface.co/v1/production/uploads/673b00f35373479538ac373c/W_dumUND8K6IlMxVmpUgS.jpeg" - -ALLOWED_MEDIA_EXT = {"png", "jpg", "jpeg", "gif", "mp4", "mov", "avi", "webm"} -ALLOWED_IMAGE_EXT = {"png", "jpg", "jpeg", "gif"} - -logging.basicConfig( - level=getattr(logging, _env("LOG_LEVEL", "INFO").upper(), logging.INFO), - format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", -) -log = logging.getLogger("adusis") - -TS_FMT = "%Y-%m-%d %H:%M:%S" - - -def now_str(): - return datetime.now().strftime(TS_FMT) - - -def allowed_file(filename, allowed_extensions): - return "." in filename and filename.rsplit(".", 1)[1].lower() in allowed_extensions - - -def media_url(filename, mtype): - """Публичный URL медиа в Hugging Face dataset. - Абсолютные и локальные (/...) пути возвращаются как есть.""" - if not filename: - return "" - if str(filename).startswith(("http://", "https://", "/")): - return filename - return "https://huggingface.co/datasets/%s/resolve/main/%ss/%s" % (REPO_ID, mtype, filename) - - -# =============================================================== PWA icon maker -def _png_bytes(width, height, rows): - """Минимальный PNG-энкодер на stdlib (zlib + struct). rows — список bytearray RGBA.""" - - def chunk(ctype, data): - return (struct.pack(">I", len(data)) + ctype + data + - struct.pack(">I", zlib.crc32(ctype + data) & 0xFFFFFFFF)) - - raw = b"".join(b"\x00" + bytes(r) for r in rows) - ihdr = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0) - return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + - chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")) - - -def _lerp(a, b, t): - return a + (b - a) * t - - -def _make_icon(size, maskable=False, with_heart=True): - """Генерирует иконку: градиент + белое сердце (неявная функция сердца).""" - pad = 0.16 if maskable else 0.0 # safe-zone для maskable - span = 1.0 - 2 * pad - heart_scale = 0.30 if maskable else 0.34 - radius = 0.24 if not maskable else 0.0 - rows = [] - for y in range(size): - row = bytearray() - ny = (y / (size - 1.0)) * 2 - 1 - for x in range(size): - nx = (x / (size - 1.0)) * 2 - 1 - # фон: диагональный градиент розовый -> фиолетовый -> синий - t = (nx * 0.5 + 0.5) * 0.65 + (ny * 0.5 + 0.5) * 0.35 - t = min(1.0, max(0.0, t)) - if t < 0.5: - k = t / 0.5 - r, g_, b = _lerp(255, 139, k), _lerp(79, 92, k), _lerp(216, 246, k) - else: - k = (t - 0.5) / 0.5 - r, g_, b = _lerp(139, 92, k), _lerp(92, 200, k), _lerp(246, 255, k) - a = 255 - # скругление углов (кроме maskable) - if radius > 0: - cx, cy = min(max(nx, -1 + radius), 1 - radius), min(max(ny, -1 + radius), 1 - radius) - dx, dy = nx - cx, ny - cy - if dx * dx + dy * dy > radius * radius: - a = 0 - # сердце: (x^2+y^2-1)^3 - x^2*y^3 <= 0 - if with_heart and a: - hx, hy = nx / heart_scale, ny / heart_scale + 0.28 - v = (hx * hx + hy * hy - 1) ** 3 - hx * hx * hy ** 3 - if v <= 0: - # мягкое свечение по краям - edge = min(1.0, max(0.0, -v * 2.2)) - glow = 1.0 - min(1.0, edge * 1.6) - r = _lerp(255, r, glow * 0.55) - g_ = _lerp(255, g_, glow * 0.55) - b = _lerp(255, b, glow * 0.55) - elif v < 0.06: - halo = 1.0 - min(1.0, v / 0.06) - r = _lerp(r, 255, halo * 0.30) - g_ = _lerp(g_, 255, halo * 0.30) - b = _lerp(b, 255, halo * 0.30) - row += bytes((int(r), int(g_), int(b), int(a))) - rows.append(row) - return _png_bytes(size, size, rows) - - - -def _hsl_to_rgb(h, s, l): - """h в [0,360), s,l в [0,1] -> (r,g,b) 0..255.""" - c = (1 - abs(2 * l - 1)) * s - hp = (h % 360) / 60.0 - x = c * (1 - abs(hp % 2 - 1)) - if hp < 1: r, g, b = c, x, 0 - elif hp < 2: r, g, b = x, c, 0 - elif hp < 3: r, g, b = 0, c, x - elif hp < 4: r, g, b = 0, x, c - elif hp < 5: r, g, b = x, 0, c - else: r, g, b = c, 0, x - mm = l - c / 2 - return (int((r + mm) * 255), int((g + mm) * 255), int((b + mm) * 255)) - - -def _heart_alpha(nx, ny, scale, dy=0.28): - hx, hy = nx / scale, ny / scale + dy - v = (hx * hx + hy * hy - 1) ** 3 - hx * hx * hy ** 3 - return v - - -def _make_avatar_png(seed, size=220): - """Градиентный аватар с «сердечным» знаком; цвет зависит от seed. - Используется как демо-аватар и как fallback для пользователей без фото.""" - rnd = random.Random(hash(seed) & 0xFFFFFF) - h1 = rnd.uniform(0, 360) - h2 = (h1 + rnd.uniform(40, 110)) % 360 - c1 = _hsl_to_rgb(h1, 0.85, 0.60) - c2 = _hsl_to_rgb(h2, 0.85, 0.52) - c3 = _hsl_to_rgb((h2 + 40) % 360, 0.9, 0.66) - rows = [] - radius = 0.30 - for y in range(size): - row = bytearray() - ny = (y / (size - 1.0)) * 2 - 1 - for x in range(size): - nx = (x / (size - 1.0)) * 2 - 1 - t = min(1.0, max(0.0, (nx * 0.5 + 0.5) * 0.6 + (ny * 0.5 + 0.5) * 0.4)) - if t < 0.5: - k = t / 0.5 - r, g, b = _lerp(c1[0], c2[0], k), _lerp(c1[1], c2[1], k), _lerp(c1[2], c2[2], k) - else: - k = (t - 0.5) / 0.5 - r, g, b = _lerp(c2[0], c3[0], k), _lerp(c2[1], c3[1], k), _lerp(c2[2], c3[2], k) - a = 255 - cx, cy = min(max(nx, -1 + radius), 1 - radius), min(max(ny, -1 + radius), 1 - radius) - if (nx - cx) ** 2 + (ny - cy) ** 2 > radius * radius: - a = 0 - v = _heart_alpha(nx, ny, 0.34) - if v <= 0: - glow = min(1.0, max(0.0, -v * 2.0)) - mix = 1.0 - min(1.0, glow * 1.7) - r = _lerp(255, r, mix * 0.5) - g = _lerp(255, g, mix * 0.5) - b = _lerp(255, b, mix * 0.5) - row += bytes((int(r), int(g), int(b), int(a))) - rows.append(row) - return _png_bytes(size, size, rows) - - -def _make_demo_media_png(seed, w=800, h=1000): - """Абстрактное «превью» для демо-историй: mesh-градиент с мягкими пятнами.""" - rnd = random.Random(seed) - base_h = rnd.uniform(0, 360) - c1 = _hsl_to_rgb(base_h, 0.75, 0.16) - c2 = _hsl_to_rgb((base_h + 60) % 360, 0.8, 0.30) - blobs = [] - for _ in range(7): - blobs.append(( - rnd.uniform(-0.3, 1.3), rnd.uniform(-0.3, 1.3), rnd.uniform(0.12, 0.45), - _hsl_to_rgb(rnd.uniform(0, 360), 0.9, 0.55), - )) - rows = [] - for y in range(h): - row = bytearray() - ny = y / (h - 1.0) - for x in range(w): - nx = x / (w - 1.0) - t = min(1.0, max(0.0, nx * 0.55 + ny * 0.45)) - r, g, b = _lerp(c1[0], c2[0], t), _lerp(c1[1], c2[1], t), _lerp(c1[2], c2[2], t) - for bx, by, br, col in blobs: - dx, dy = (nx - bx) * (w / h), (ny - by) - d2 = dx * dx + dy * dy - if d2 < br * br: - k = (1 - (d2 / (br * br)) ** 0.5) * 0.55 - r = _lerp(r, col[0], k) - g = _lerp(g, col[1], k) - b = _lerp(b, col[2], k) - row += bytes((int(r), int(g), int(b), 255)) - rows.append(row) - return _png_bytes(w, h, rows) - -def _make_badge(size=96): - """Монохромный badge для строки состояния Android.""" - rows = [] - for y in range(size): - row = bytearray() - ny = (y / (size - 1.0)) * 2 - 1 - for x in range(size): - nx = (x / (size - 1.0)) * 2 - 1 - hx, hy = nx / 0.34, ny / 0.34 + 0.28 - v = (hx * hx + hy * hy - 1) ** 3 - hx * hx * hy ** 3 - on = v <= 0 - row += bytes((255, 255, 255, 255 if on else 0)) - rows.append(row) - return _png_bytes(size, size, rows) - - -_ICON_CACHE = {} - - -def get_icon(kind, size): - key = (kind, size) - if key not in _ICON_CACHE: - if kind == "badge": - _ICON_CACHE[key] = _make_badge(size) - else: - _ICON_CACHE[key] = _make_icon(size, maskable=(kind == "maskable")) - return _ICON_CACHE[key] - - -# ============================================================ JSON «database» -# Единый экземпляр данных в памяти + одноThreadовая очередь записи + -# отдельная очередь загрузки в Hugging Face с coalesce и retry. -# Формат остаётся прежним — обычный JSON-файл в HF dataset. - -def initialize_data_structure(data): - if not isinstance(data, dict): - log.warning("Data is not a dict, initializing empty database") - data = {"posts": [], "users": {}, "transactions": [], "direct_messages": {}} - - data.setdefault("posts", []) - data.setdefault("users", {}) - data.setdefault("transactions", []) - data.setdefault("direct_messages", {}) - data.setdefault("push_subscriptions", {}) - - if not isinstance(data["posts"], list): - data["posts"] = [] - if not isinstance(data["users"], dict): - data["users"] = {} - if not isinstance(data["transactions"], list): - data["transactions"] = [] - if not isinstance(data["direct_messages"], dict): - data["direct_messages"] = {} - if not isinstance(data["push_subscriptions"], dict): - data["push_subscriptions"] = {} - - now = now_str() - for post in data["posts"]: - if not isinstance(post, dict): - continue - post.setdefault("likes", []) - post.setdefault("views", 0) - post.setdefault("comments", []) - post.setdefault("jerked_off_count", 0) - post.setdefault("views_reward_milestone", 0) - post.setdefault("promoted_until", None) - post.setdefault("upload_date", "1970-01-01 00:00:00") - post.setdefault("uploader", "unknown") - post.setdefault("title", "Untitled") - post.setdefault("description", "") - post.setdefault("type", "photo") - post.setdefault("filename", "") - if "id" not in post: - post["id"] = str(random.randint(100000, 999999)) - if not isinstance(post.get("likes"), list): - post["likes"] = [] - if not isinstance(post.get("comments"), list): - post["comments"] = [] - - all_codes = {u.get("referral_code") for u in data["users"].values() - if isinstance(u, dict) and u.get("referral_code")} - - for username, user_data in data["users"].items(): - if not isinstance(user_data, dict): - continue - user_data.setdefault("last_seen", "1970-01-01 00:00:00") - user_data.setdefault("bio", "") - user_data.setdefault("link", "") - user_data.setdefault("avatar", None) - user_data.setdefault("aducoin", 0) - user_data.setdefault("role", None) - user_data.setdefault("referred_by", None) - user_data.setdefault("notify_messages", True) - user_data.setdefault("notify_videos", True) - user_data.setdefault("remember_tokens", []) - if not user_data.get("referral_code") or user_data["referral_code"] in all_codes: - new_code = generate_unique_referral_code(data) - user_data["referral_code"] = new_code - all_codes.add(new_code) - - for conv_key, messages in list(data["direct_messages"].items()): - if not isinstance(messages, list): - log.warning("Conversation %r is not a list, resetting.", conv_key) - data["direct_messages"][conv_key] = [] - continue - for msg in messages: - if not isinstance(msg, dict): - continue - msg.setdefault("sender", "unknown") - msg.setdefault("timestamp", now) - msg.setdefault("text", "") - msg.setdefault("message_id", str(uuid.uuid4())) - msg.setdefault("read", False) - data["direct_messages"][conv_key] = [m for m in messages if isinstance(m, dict)] - - return data - - -def generate_unique_referral_code(data): - while True: - code = str(uuid.uuid4())[:8] - if not any(isinstance(u, dict) and u.get("referral_code") == code - for u in data.get("users", {}).values()): - return code - - -def log_transaction(data, user, type_, amount, description, related_user=None, related_story_id=None): - if user not in data.get("users", {}): - log.warning("Attempted to log transaction for non-existent user: %s", user) - return - balance_after = data["users"][user].get("aducoin", 0) - transaction = { - "id": str(uuid.uuid4()), - "user": user, - "timestamp": now_str(), - "type": type_, - "amount": amount, - "description": description, - "related_user": related_user, - "related_story_id": related_story_id, - "balance_after": balance_after, - } - data.setdefault("transactions", []).append(transaction) - log.info("Transaction logged: %s", transaction) - - -class _WriteJob: - __slots__ = ("done", "ok", "error") - - def __init__(self): - self.done = threading.Event() - self.ok = False - self.error = None - - -# Глобальный замок на ЛЮБУЮ операцию с Hugging Face — коммиты никогда -# не выполняются параллельно (именно это раньше ломало базу). -HF_LOCK = threading.RLock() - - -class JsonDatabase: - """ - Очередь к JSON-базе. - - with db.read() as data: # чтение (из памяти, без HF) - ... - with db.write() as data: # мутация + постановка в очередь записи - data["users"][u]["aducoin"] += 1 - db.mutate(fn, wait=True) # то же + дождаться записи на диск - - Коммиты в HF дополнительно ограничены по частоте (UPLOAD_MIN_INTERVAL): - частые presence-обновления не превращаются в сотни коммитов, - при этом в HF всегда уходит ПОСЛЕДНИЙ снапшот (coalesce). - """ - - def __init__(self, path, repo_id=None, token_write=None, token_read=None, - sync_interval=DB_SYNC_INTERVAL, upload_retries=UPLOAD_RETRIES, - upload_min_interval=UPLOAD_MIN_INTERVAL): - self.path = path - self.repo_id = repo_id - self.token_write = token_write - self.token_read = token_read - self.sync_interval = max(30, sync_interval) - self.upload_retries = max(1, upload_retries) - self.upload_min_interval = max(0, upload_min_interval) - - self._lock = threading.RLock() - self._data = None - self._dirty = False # память отличается от файла - self._pending_upload = False # HF отстаёт от памяти - self._write_queue = queue.Queue() # задания записи файла - self._upload_queue = queue.Queue() # снапшоты на загрузку в HF - self._last_write_ts = 0.0 - self._last_upload_ts = 0.0 - self._last_sync_ts = 0.0 - self._stop = threading.Event() - self.stats = {"writes": 0, "uploads": 0, "upload_failures": 0, - "downloads": 0, "queued": 0} - - self._initial_load() - - self._threads = [ - threading.Thread(target=self._writer_loop, name="db-writer", daemon=True), - threading.Thread(target=self._uploader_loop, name="db-uploader", daemon=True), - threading.Thread(target=self._sync_loop, name="db-syncer", daemon=True), - ] - for t in self._threads: - t.start() - - # ------------------------------------------------------------- загрузка - def _read_local(self): - try: - if os.path.exists(self.path) and os.path.getsize(self.path) > 0: - with open(self.path, "r", encoding="utf-8") as f: - return json.load(f) - except json.JSONDecodeError: - log.error("JSON decode error in %s — starting from empty structure", self.path) - except Exception as e: - log.error("Error reading %s: %s", self.path, e) - return None - - def _download_from_hf(self): - if HF_DISABLED or not HF_AVAILABLE or not self.token_read: - return None - with HF_LOCK: - try: - hf_hub_download( - repo_id=self.repo_id, filename=os.path.basename(self.path), - repo_type="dataset", token=self.token_read, - local_dir=os.path.dirname(self.path) or ".", - force_download=True, - ) - data = self._read_local() - if data is not None: - self.stats["downloads"] += 1 - self._last_sync_ts = time.time() - log.info("Database downloaded from Hugging Face") - return data - except Exception as e: - log.warning("HF download failed (%s) — using local copy if any", e) - return None - - def _initial_load(self): - data = None - if os.path.exists(self.path): - local = self._read_local() - if local is not None: - data = local - remote = self._download_from_hf() # на старте берём самое свежее - if remote is not None: - data = remote - if data is None: - data = {} - log.info("No existing database found — creating empty structure") - data = initialize_data_structure(data) - with self._lock: - self._data = data - self._dirty = False - self._pending_upload = False - # гарантируем наличие файла на диске - try: - if not os.path.exists(self.path): - self._flush_to_disk(json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8")) - self._pending_upload = True - except Exception as e: - log.error("Could not create initial data file: %s", e) - - # ------------------------------------------------------------- доступ - @contextmanager - def read(self): - """Доступ на чтение. Мутировать данные внутри — нельзя.""" - with self._lock: - yield self._data - - @contextmanager - def write(self, wait=False, timeout=30.0): - """ - Мутация данных. При успешном выходе из блока изменение - ставится в очередь записи (диск) и далее в очередь HF. - При исключении изменение НЕ коммитится. - - ВАЖНО: замок освобождается ДО ожидания записи (иначе deadlock — - writer-поток не смог бы сериализовать данные). - """ - job = _WriteJob() - committed = False - self._lock.acquire() - try: - yield self._data - self._dirty = True - self._pending_upload = True - self._last_write_ts = time.time() - self.stats["queued"] += 1 - self._write_queue.put(job) - committed = True - finally: - self._lock.release() - if committed and wait: - job.done.wait(timeout) - if not job.ok: - log.error("Write job failed: %s", job.error) - - def mutate(self, fn=None, wait=False, timeout=30.0): - """Функциональная мутация: db.mutate(lambda d: d['x'] += 1, wait=True)""" - with self.write(wait=wait, timeout=timeout): - if fn is not None: - fn(self._data) - - # ------------------------------------------------------------- writer - def _flush_to_disk(self, payload): - tmp = self.path + ".tmp" - with open(tmp, "wb") as f: - f.write(payload) - f.flush() - os.fsync(f.fileno()) - os.replace(tmp, self.path) - - def _writer_loop(self): - while not self._stop.is_set(): - job = self._write_queue.get() - if job is None: - break - try: - with self._lock: - if not self._dirty: - job.ok = True - job.done.set() - continue - payload = json.dumps(self._data, ensure_ascii=False, indent=2).encode("utf-8") - self._dirty = False - self._flush_to_disk(payload) - self.stats["writes"] += 1 - job.ok = True - self._upload_queue.put(payload) - except Exception as e: - log.error("Disk write failed: %s", e, exc_info=True) - job.ok = False - job.error = e - with self._lock: - self._dirty = True - threading.Timer(2.0, self._requeue_write, args=(job,)).start() - finally: - job.done.set() - - def _requeue_write(self, job): - if not job.done.is_set() or not job.ok: - self._write_queue.put(_WriteJob()) - - # ------------------------------------------------------------- uploader - def _upload_to_hf(self, payload): - if HF_DISABLED or not HF_AVAILABLE or not self.token_write: - return True - with HF_LOCK: - api = HfApi() - api.upload_file( - path_or_fileobj=io.BytesIO(payload), - path_in_repo=os.path.basename(self.path), - repo_id=self.repo_id, - repo_type="dataset", - token=self.token_write, - commit_message="Backup %s" % now_str(), - ) - return True - - def _uploader_loop(self): - while not self._stop.is_set(): - payload = self._upload_queue.get() - if payload is None: - break - # COALESCE: если в очереди ещё снапшоты — оставляем только последний - # (каждый снапшот — полное состояние базы, промежуточные не нужны) - drained = 0 - while True: - try: - nxt = self._upload_queue.get_nowait() - except queue.Empty: - break - if nxt is None: - return - payload = nxt - drained += 1 - if drained: - log.info("Coalesced %d pending upload snapshots into one", drained) - - # троттлинг коммитов: не чаще upload_min_interval (данные не теряются — - # уходит всегда последний снапшот, а диск уже актуален) - if self.upload_min_interval: - elapsed = time.time() - self._last_upload_ts - if 0 < elapsed < self.upload_min_interval: - time.sleep(min(self.upload_min_interval - elapsed, self.upload_min_interval)) - - ok = False - for attempt in range(self.upload_retries): - if self._stop.is_set(): - break - try: - self._upload_to_hf(payload) - ok = True - break - except Exception as e: - wait_s = min(60, 3 * (2 ** attempt)) - log.warning("HF upload failed (attempt %d/%d): %s — retry in %ds", - attempt + 1, self.upload_retries, e, wait_s) - time.sleep(wait_s) - if ok: - self.stats["uploads"] += 1 - with self._lock: - self._pending_upload = False - self._last_upload_ts = time.time() - else: - self.stats["upload_failures"] += 1 - log.error("HF upload giving up for now, will retry later") - self._upload_queue.put(payload) - time.sleep(60) - - # ------------------------------------------------------------- syncer - def _sync_loop(self): - while not self._stop.is_set(): - self._stop.wait(self.sync_interval) - if self._stop.is_set(): - break - try: - self.sync_from_remote() - except Exception as e: - log.warning("Background sync failed: %s", e) - - def sync_from_remote(self): - """Подтянуть изменения с HF, но ТОЛЬКО когда локальных правок нет.""" - with self._lock: - if self._dirty or self._pending_upload: - return False - if not self._upload_queue.empty(): - return False - if time.time() - self._last_write_ts < self.sync_interval: - return False - remote = self._download_from_hf() - if remote is None: - return False - remote = initialize_data_structure(remote) - with self._lock: - current = json.dumps(self._data, sort_keys=True, ensure_ascii=False) - incoming = json.dumps(remote, sort_keys=True, ensure_ascii=False) - if current != incoming: - log.info("Remote database changed — adopting remote version") - self._data = remote - return True - return False - - # ------------------------------------------------------------- прочее - def stop(self): - self._stop.set() - self._write_queue.put(None) - self._upload_queue.put(None) - - def health(self): - with self._lock: - return { - "writes": self.stats["writes"], - "uploads": self.stats["uploads"], - "upload_failures": self.stats["upload_failures"], - "downloads": self.stats["downloads"], - "pending_upload": self._pending_upload, - "dirty": self._dirty, - "queued_jobs": self._write_queue.qsize(), - "upload_queue": self._upload_queue.qsize(), - "seconds_since_write": round(time.time() - self._last_write_ts, 1) if self._last_write_ts else None, - } - - -DB = JsonDatabase(DATA_FILE, repo_id=REPO_ID, - token_write=None if HF_DISABLED else HF_TOKEN_WRITE, - token_read=None if HF_DISABLED else HF_TOKEN_READ) - - -# ===================================================== Web Push (VAPID + AESGCM) -# Реализация протокола Web Push «с нуля» на библиотеке cryptography: -# * VAPID: ключевая пара EC P-256, JWT (ES256) для авторизации; -# * шифрование payload: ECDH(P-256) + HKDF-SHA256 + AES-128-GCM -# (content-encoding: aes128gcm, RFC 8291 / draft-ietf-webpush-encryption). - -def b64url_encode(raw): - return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii") - - -def b64url_decode(s): - if isinstance(s, str): - s = s.encode("ascii") - s += b"=" * (-len(s) % 4) - return base64.urlsafe_b64decode(s) - - -class VapidKeys: - """Пара ключей VAPID. Хранится в vapid_keys.json (или в env).""" - - def __init__(self, private_key): - self.private_key = private_key - - @property - def public_raw(self): - return self.private_key.public_key().public_bytes( - serialization.Encoding.X962, - serialization.PublicFormat.UncompressedPoint) # 65 bytes - - @property - def public_b64(self): - return b64url_encode(self.public_raw) - - @property - def private_b64(self): - d = self.private_key.private_numbers().private_value - return b64url_encode(d.to_bytes(32, "big")) - - def save(self, path): - try: - with open(path, "w", encoding="utf-8") as f: - json.dump({"private_key": self.private_b64, - "public_key": self.public_b64}, f) - except Exception as e: - log.warning("Could not persist VAPID keys: %s", e) - - @classmethod - def load_or_create(cls, path): - env_priv, env_pub = os.getenv("VAPID_PRIVATE_KEY"), os.getenv("VAPID_PUBLIC_KEY") - if env_priv: - try: - d = int.from_bytes(b64url_decode(env_priv), "big") - key = ec.derive_private_key(d, ec.SECP256R1()) - log.info("VAPID keys loaded from environment") - return cls(key) - except Exception as e: - log.warning("Invalid VAPID_PRIVATE_KEY in env: %s", e) - try: - if os.path.exists(path): - with open(path, "r", encoding="utf-8") as f: - blob = json.load(f) - d = int.from_bytes(b64url_decode(blob["private_key"]), "big") - log.info("VAPID keys loaded from %s", path) - return cls(ec.derive_private_key(d, ec.SECP256R1())) - except Exception as e: - log.warning("Could not load VAPID keys (%s) - generating new pair", e) - key = ec.generate_private_key(ec.SECP256R1()) - inst = cls(key) - inst.save(path) - log.info("Generated new VAPID key pair (saved to %s)", path) - return inst - - def jwt(self, aud): - """ES256 JWT для заголовка Authorization: vapid t=..., k=...""" - header = b64url_encode(json.dumps({"typ": "JWT", "alg": "ES256"}, - separators=(",", ":")).encode()) - payload = b64url_encode(json.dumps( - {"aud": aud, "exp": int(time.time()) + 12 * 3600, "sub": VAPID_CONTACT}, - separators=(",", ":")).encode()) - signing_input = ("%s.%s" % (header, payload)).encode("ascii") - der = self.private_key.sign(signing_input, ec.ECDSA(hashes.SHA256())) - r, s = decode_dss_signature(der) - sig = r.to_bytes(32, "big") + s.to_bytes(32, "big") - return "%s.%s.%s" % (header, payload, b64url_encode(sig)) - - -VAPID = None -PUSH_ENABLED = False -if CRYPTO_AVAILABLE: - try: - VAPID = VapidKeys.load_or_create(VAPID_FILE) - PUSH_ENABLED = True - except Exception as e: - log.error("Push notifications disabled: %s", e) -else: - log.warning("`cryptography` not installed - push notifications disabled") - - -def _hkdf_expand(prk, info, length): - return HKDFExpand(algorithm=hashes.SHA256(), length=length, info=info).derive(prk) - - -def encrypt_push_payload(payload_bytes, p256dh_b64, auth_secret_b64, record_size=1024): - """ - aes128gcm content-encoding (RFC 8188-style для Web Push). - Возвращает (body_bytes, content_encoding). - """ - if not CRYPTO_AVAILABLE: - raise RuntimeError("cryptography library is required for push payloads") - - ua_public = b64url_decode(p256dh_b64) # 65 bytes, uncompressed point - auth_secret = b64url_decode(auth_secret_b64) # 16 bytes - - server_private = ec.generate_private_key(ec.SECP256R1()) - server_public = server_private.public_key().public_bytes( - serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint) - - peer_public = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), ua_public) - ecdh_secret = server_private.exchange(ec.ECDH(), peer_public) - - prk_key = hmac.new(auth_secret, ecdh_secret, hashlib.sha256).digest() - context = b"WebPush: info\x00" + ua_public + server_public + struct.pack(">H", len(ua_public)) - salt = os.urandom(16) - - prk = hmac.new(salt, prk_key, hashlib.sha256).digest() - content_key = _hkdf_expand(prk, b"Content-Encoding: aes128gcm\x00", 16) - nonce = _hkdf_expand(prk, b"Content-Encoding: nonce\x00" + context, 12) - - pad_len = record_size - (len(payload_bytes) % record_size) - padded = payload_bytes + b"\x02" + b"\x00" * (pad_len - 1) - - header = salt + struct.pack(">I", record_size) + struct.pack(">B", len(server_public)) + server_public - ciphertext = AESGCM(content_key).encrypt(nonce, padded, header) - return header + ciphertext, "aes128gcm" - - -def send_web_push(subscription, payload_obj, ttl=3600): - """ - Отправляет одно push-уведомление. - Возвращает (ok, status_code, gone) - gone=True, если подписка истекла (404/410). - """ - if not PUSH_ENABLED: - return False, 0, False - endpoint = subscription.get("endpoint", "") - keys = subscription.get("keys", {}) or {} - p256dh, auth = keys.get("p256dh"), keys.get("auth") - if not endpoint or not p256dh or not auth: - return False, 0, True - - payload_bytes = json.dumps(payload_obj, ensure_ascii=False, - separators=(",", ":")).encode("utf-8") - if len(payload_bytes) > 900: - payload_bytes = payload_bytes[:900] - - try: - body, encoding = encrypt_push_payload(payload_bytes, p256dh, auth) - except Exception as e: - log.error("Push encryption failed: %s", e) - return False, 0, False - - try: - from urllib.request import Request, urlopen - aud = "/".join(endpoint.split("/")[:3]) - token = VAPID.jwt(aud) - req = Request(endpoint, data=body, method="POST") - req.add_header("Authorization", "vapid t=%s, k=%s" % (token, VAPID.public_b64)) - req.add_header("Content-Encoding", encoding) - req.add_header("Content-Type", "application/octet-stream") - req.add_header("TTL", str(ttl)) - topic = payload_obj.get("tag") - if topic: - req.add_header("Topic", re.sub(r"[^a-zA-Z0-9\-_]", "-", topic)[:60]) - with urlopen(req, timeout=10) as resp: - return True, resp.status, False - except Exception as e: - code = getattr(e, "code", None) or getattr(e, "status", None) - if hasattr(e, "read"): - try: - log.warning("Push send failed %s: %s %s", code, e, e.read()[:200]) - except Exception: - pass - else: - log.warning("Push send failed: %s", e) - gone = code in (404, 410) - return False, code, gone - - -# ------------------------------------------------------------- хранилище подписок -def get_subscriptions(data, username): - subs = (data.get("push_subscriptions") or {}).get(username) - return subs if isinstance(subs, list) else [] - - -def save_subscription(data, username, subscription): - subs = get_subscriptions(data, username) - endpoint = subscription.get("endpoint", "") - subs = [s for s in subs if s.get("endpoint") != endpoint] - subs.append({ - "endpoint": endpoint, - "keys": { - "p256dh": (subscription.get("keys") or {}).get("p256dh", ""), - "auth": (subscription.get("keys") or {}).get("auth", ""), - }, - "created": now_str(), - "user_agent": request.headers.get("User-Agent", "")[:200], - }) - data.setdefault("push_subscriptions", {})[username] = subs - - -def remove_subscription(data, username, endpoint): - subs = get_subscriptions(data, username) - data.setdefault("push_subscriptions", {})[username] = [ - s for s in subs if s.get("endpoint") != endpoint] - - -def parse_conv_key(key): - """Ключ диалога хранится как str(tuple). Парсим устойчиво к кавычкам в никах.""" - if isinstance(key, tuple): - return key - try: - import ast - val = ast.literal_eval(key) - if isinstance(val, tuple) and len(val) == 2: - return val - except Exception: - pass - m = re.findall(r"'([^']*)'|\"([^\"]*)\"", str(key)) - parts = [a or b for a, b in m] - if len(parts) == 2: - return tuple(parts) - return tuple() - - -class PushNotifier: - """ - Фоновый сканер: уведомляет подписчиков о новых сообщениях и новых видео. - Плюс немедленная отправка при появлении сообщения. - Все методы выполняются внутри app.app_context() (url_for и пр.). - """ - - def __init__(self, interval=20): - self.interval = interval - self._seen_messages = set() - self._seen_stories = set() - self._send_lock = threading.Lock() - self._stop = threading.Event() - self._thread = threading.Thread(target=self._loop, name="push-notifier", daemon=True) - - def start(self): - # инициализация «уже увиденного», чтобы не разослать старые события - try: - with DB.read() as data: - for messages in data.get("direct_messages", {}).values(): - for m in messages: - if isinstance(m, dict) and m.get("message_id"): - self._seen_messages.add(m["message_id"]) - for p in data.get("posts", []): - if isinstance(p, dict) and p.get("id"): - self._seen_stories.add(p["id"]) - except Exception as e: - log.warning("Notifier init failed: %s", e) - self._thread.start() - - def _loop(self): - while not self._stop.wait(self.interval): - try: - self.scan_once() - except Exception as e: - log.warning("Notifier scan error: %s", e) - - def scan_once(self): - with DB.read() as data: - new_messages = [] - for conv_key, messages in data.get("direct_messages", {}).items(): - for m in messages: - mid = m.get("message_id") - if mid and mid not in self._seen_messages: - new_messages.append((conv_key, m)) - new_stories = [p for p in data.get("posts", []) - if p.get("id") and p["id"] not in self._seen_stories] - for conv_key, m in new_messages: - self._seen_messages.add(m.get("message_id")) - self._notify_message(conv_key, m) - for p in new_stories: - self._seen_stories.add(p.get("id")) - self._notify_story(p) - - # ------------------------------------------------------------ отправка - def _send_to_user_snapshot(self, username, payload): - """Берёт снапшот подписок под замком и отправляет вне замка.""" - with DB.read() as data: - subs = [dict(s) for s in get_subscriptions(data, username)] - if not subs or not PUSH_ENABLED: - return [] - dead = [] - with self._send_lock: - for sub in subs: - ok, code, gone = send_web_push(sub, payload) - if gone: - dead.append(sub.get("endpoint", "")) - return dead - - def _cleanup_dead(self, username, dead_endpoints): - if not dead_endpoints: - return - - def _fn(data): - for endpoint in dead_endpoints: - remove_subscription(data, username, endpoint) - try: - DB.mutate(_fn, wait=False) - except Exception as e: - log.warning("Could not clean dead subscriptions: %s", e) - - def _notify_message(self, conv_key, message): - with app.app_context(): - jobs = [] - with DB.read() as data: - sender = message.get("sender", "Someone") - text = (message.get("text") or "").strip() - participants = parse_conv_key(conv_key) - for recipient in [u for u in participants if u != sender]: - user = data.get("users", {}).get(recipient) - if not isinstance(user, dict) or not user.get("notify_messages", True): - continue - jobs.append((recipient, { - "title": "\U0001F4EC New message from %s" % sender, - "body": text[:140] if text else "Sent you a message", - "url": "/messages/%s" % sender, - "tag": "msg-%s" % hashlib.md5( - str(sorted(participants)).encode()).hexdigest()[:12], - "kind": "message", - })) - for recipient, payload in jobs: - self._cleanup_dead(recipient, self._send_to_user_snapshot(recipient, payload)) - - def _notify_story(self, story): - with app.app_context(): - jobs = [] - with DB.read() as data: - uploader = story.get("uploader", "Someone") - title = story.get("title", "Untitled") - for username, user in data.get("users", {}).items(): - if username == uploader: - continue - if not isinstance(user, dict) or not user.get("notify_videos", True): - continue - jobs.append((username, { - "title": "\U0001F3AC New %s: %s" % ( - "video" if story.get("type") == "video" else "story", title), - "body": "by %s - watch now on %s" % (uploader, SITE_NAME), - "url": "/story/%s" % story.get("id", ""), - "tag": "story-%s" % story.get("id", ""), - "kind": "story", - })) - for username, payload in jobs: - self._cleanup_dead(username, self._send_to_user_snapshot(username, payload)) - - def push_message_now(self, conv_key, message): - if not PUSH_ENABLED: - return - try: - self._seen_messages.add(message.get("message_id")) - threading.Thread(target=self._notify_message, args=(conv_key, message), - daemon=True).start() - except Exception as e: - log.warning("Immediate push failed: %s", e) - - def push_story_now(self, story): - if not PUSH_ENABLED: - return - try: - self._seen_stories.add(story.get("id")) - threading.Thread(target=self._notify_story, args=(story,), daemon=True).start() - except Exception as e: - log.warning("Immediate story push failed: %s", e) - - def push_test(self, username): - with app.app_context(): - payload = { - "title": "\U0001F514 Notifications work!", - "body": "You will now get alerts for new messages and videos.", - "url": "/notifications", - "tag": "test-%d" % int(time.time()), - "kind": "test", - } - self._cleanup_dead(username, self._send_to_user_snapshot(username, payload)) - - -NOTIFIER = PushNotifier(interval=20) - - - -# ================================================================= Flask app -app = Flask(__name__) - - -def _load_or_create_secret(): - """Стабильный secret key: env -> файл -> случайный (и сохраняем). - Благодаря файлу перезапуск сервера НЕ разлогинивает пользователей.""" - env_key = os.getenv("FLASK_SECRET_KEY") - if env_key: - return env_key - try: - if os.path.exists(SECRET_FILE): - with open(SECRET_FILE, "r", encoding="utf-8") as f: - key = f.read().strip() - if len(key) >= 32: - return key - key = base64.urlsafe_b64encode(os.urandom(48)).decode("ascii") - with open(SECRET_FILE, "w", encoding="utf-8") as f: - f.write(key) - try: - os.chmod(SECRET_FILE, 0o600) - except Exception: - pass - log.info("Generated new persistent secret key at %s", SECRET_FILE) - return key - except Exception as e: - log.warning("Secret key persistence failed (%s) - using random key", e) - return base64.urlsafe_b64encode(os.urandom(48)).decode("ascii") - - -app.secret_key = _load_or_create_secret() -app.config.update( - PERMANENT_SESSION_LIFETIME=timedelta(days=SESSION_DAYS), - SESSION_COOKIE_HTTPONLY=True, - SESSION_COOKIE_SAMESITE="Lax", - SESSION_COOKIE_SECURE=_env_bool("SESSION_COOKIE_SECURE", False), - SESSION_REFRESH_EACH_REQUEST=True, # «скользящее» продление сессии - MAX_CONTENT_LENGTH=MAX_UPLOAD_BYTES + 8 * 1024 * 1024, - JSON_AS_ASCII=False, -) - -REMEMBER_COOKIE = "adusis_remember" -REMEMBER_DAYS = SESSION_DAYS -REMEMBER_MAX_TOKENS = 5 - - -# ------------------------------------------------------------------ auth utils -def hash_password(password): - return generate_password_hash(password, method="pbkdf2:sha256:600000") - - -def _is_hashed(stored): - return isinstance(stored, str) and stored.startswith(("pbkdf2:", "scrypt:", "argon2")) - - -def verify_password(stored, password): - """Проверка пароля. Поддерживает legacy-пароли открытым текстом - (они будут автоматически перехэшированы при входе).""" - if not stored: - return False - if _is_hashed(stored): - try: - return check_password_hash(stored, password) - except Exception: - return False - return hmac.compare_digest(str(stored), str(password)) - - -def _hash_token(token): - return hashlib.sha256(token.encode("utf-8")).hexdigest() - - -def create_remember_token(data, username, user_agent=""): - token = base64.urlsafe_b64encode(os.urandom(32)).decode("ascii").rstrip("=") - expires = datetime.now() + timedelta(days=REMEMBER_DAYS) - user = data.get("users", {}).get(username) - if not isinstance(user, dict): - return token, expires - tokens = [t for t in user.get("remember_tokens", []) - if isinstance(t, dict) and t.get("expires", "0") > now_str()] - tokens.append({"hash": _hash_token(token), "expires": expires.strftime(TS_FMT), - "created": now_str(), "ua": user_agent[:120]}) - user["remember_tokens"] = tokens[-REMEMBER_MAX_TOKENS:] - return token, expires - - -def consume_remember_token(data, token): - """Ищет пользователя по токену «запомнить меня». Возвращает username или None.""" - if not token: - return None - th = _hash_token(token) - for username, user in data.get("users", {}).items(): - if not isinstance(user, dict): - continue - for t in user.get("remember_tokens", []): - if isinstance(t, dict) and t.get("hash") == th and t.get("expires", "0") > now_str(): - return username - return None - - -def revoke_remember_token(data, username, token): - user = data.get("users", {}).get(username) - if isinstance(user, dict) and token: - th = _hash_token(token) - user["remember_tokens"] = [t for t in user.get("remember_tokens", []) - if not (isinstance(t, dict) and t.get("hash") == th)] - - -# ------------------------------------------------------------- brute-force guard -_login_attempts = {} -_login_attempts_lock = threading.Lock() - - -def _rate_key(): - return (request.remote_addr or "?", (request.form.get("username") or "").lower()[:64]) - - -def login_rate_limited(): - key = _rate_key() - now = time.time() - with _login_attempts_lock: - hits = [t for t in _login_attempts.get(key, []) if now - t < 300] - _login_attempts[key] = hits - if len(hits) >= 10: - return True - _login_attempts.setdefault(key, []).append(now) - if len(_login_attempts) > 5000: - _login_attempts.clear() - return False - - -def clear_login_attempts(): - with _login_attempts_lock: - _login_attempts.pop(_rate_key(), None) - - -# ------------------------------------------------------------------ decorators -def login_required(view): - @wraps(view) - def wrapped(*args, **kwargs): - if "username" not in session: - flash("Please log in to continue.", "error") - return redirect(url_for("login", next=request.path)) - return view(*args, **kwargs) - return wrapped - - -# ------------------------------------------------------------ request lifecycle -@app.before_request -def before_request_func(): - g.start_time = time.time() - g.username = session.get("username") - - # --- восстановление сессии по токену «запомнить меня» --- - if "username" not in session: - token = request.cookies.get(REMEMBER_COOKIE) - if token: - try: - with DB.read() as data: - username = consume_remember_token(data, token) - if username: - session["username"] = username - session.permanent = True - g.username = username - log.info("Session restored from remember token for %s", username) - except Exception as e: - log.warning("Remember-token restore failed: %s", e) - - # --- присутствие (не чаще раза в 60 секунд на пользователя) --- - username = g.username - if username: - key = "last_seen_%s" % username - now = time.time() - last = getattr(g, "_presence_cache", None) - if last is None: - last = _PRESENCE.get(key, 0.0) - if now - last > 60: - _PRESENCE[key] = now - - def _touch(d, u=username): - if isinstance(d.get("users", {}).get(u), dict): - d["users"][u]["last_seen"] = now_str() - try: - DB.mutate(_touch, wait=False) - except Exception as e: - log.warning("Presence update failed: %s", e) - - -_PRESENCE = {} - - -@app.after_request -def after_request_func(response): - response.headers.setdefault("X-Content-Type-Options", "nosniff") - response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin") - response.headers.setdefault("Permissions-Policy", "geolocation=(), microphone=(), camera=(self)") - return response - - -# ------------------------------------------------------------ контекст шаблонов -@app.context_processor -def inject_globals(): - def ctx_unread(): - if not g.get("username"): - return 0 - with DB.read() as data: - return count_unread_messages(data, g.username) - return { - "site_name": SITE_NAME, - "logo_url": LOGO_URL, - "push_enabled": PUSH_ENABLED, - "current_username": g.get("username"), - "unread_count": ctx_unread(), - } - - -def count_unread_messages(data, current_user): - count = 0 - if not current_user: - return 0 - for conv_key, messages in (data.get("direct_messages") or {}).items(): - participants = parse_conv_key(conv_key) - if current_user not in participants: - continue - for msg in messages: - if isinstance(msg, dict) and msg.get("sender") != current_user and not msg.get("read"): - count += 1 - return count - - -def is_user_online(data, username): - if not username or username not in (data.get("users") or {}): - return False - last_seen_str = (data["users"][username] or {}).get("last_seen", "1970-01-01 00:00:00") - try: - last_seen = datetime.strptime(last_seen_str, TS_FMT) - return (datetime.now() - last_seen).total_seconds() < 300 - except (ValueError, TypeError): - return False - - -def get_conversation_key(user1, user2): - return tuple(sorted((user1, user2))) - - -# ==================================================================== DESIGN -BASE_CSS = """ -/* ========================================================================== - ADUSIS — "Aurora Noir" design system - Слоистая тёмная тема, стекло, неоновые акценты, пружинная анимация. - ========================================================================== */ -*,*::before,*::after{box-sizing:border-box} -:root{ - /* --- поверхность --- */ - --bg:#06060c; --bg2:#0a0912; --bg3:#100e1c; - --surface:rgba(255,255,255,.038); --surface2:rgba(255,255,255,.065); - --surface3:rgba(255,255,255,.10); - --border:rgba(255,255,255,.075); --border2:rgba(255,255,255,.14); - --hl:rgba(255,255,255,.10); /* верхний блик на карточках */ - - /* --- текст --- */ - --text:#f7f5fd; --text2:#a8a2c0; --text3:#6f6989; - - /* --- акценты --- */ - --pink:#ff4fd8; --pink2:#ff8ae8; --purple:#8b5cf6; --purple2:#a78bfa; - --gold:#ffd166; --green:#2fe0a1; --red:#ff5c7a; --blue:#5cc8ff; - --grad:linear-gradient(115deg,#ff4fd8 0%,#8b5cf6 52%,#5cc8ff 100%); - --grad-warm:linear-gradient(115deg,#ff6ad5,#ff2e63); - --grad-cool:linear-gradient(115deg,#5cc8ff,#8b5cf6); - --grad-gold:linear-gradient(115deg,#ffd166,#ff9f43); - --grad-soft:linear-gradient(115deg,rgba(255,79,216,.14),rgba(139,92,246,.14)); - - /* --- радиусы --- */ - --r1:10px; --r2:14px; --r3:20px; --r4:28px; --r5:36px; --rfull:999px; - - /* --- тени --- */ - --sh1:0 1px 2px rgba(0,0,0,.4),0 4px 14px rgba(0,0,0,.28); - --sh2:0 8px 30px rgba(0,0,0,.45); - --sh3:0 20px 60px rgba(0,0,0,.55); - --glow:0 8px 30px rgba(255,79,216,.28); - --glow-cool:0 8px 30px rgba(92,200,255,.25); - --ring:0 0 0 1px rgba(255,255,255,.10),0 0 0 5px rgba(139,92,246,.20); - - /* --- движение --- */ - --ease:cubic-bezier(.22,1,.36,1); - --spring:cubic-bezier(.34,1.56,.64,1); - --fast:140ms; --med:240ms; --slow:420ms; - - /* --- раскладка --- */ - --side-w:264px; --maxw:1240px; - --safe-b:env(safe-area-inset-bottom,0px); - --safe-t:env(safe-area-inset-top,0px); -} - -/* ---------------------------------------------------------------- reset */ -html{-webkit-text-size-adjust:100%;scroll-behavior:smooth} -body{ - margin:0; background:var(--bg); color:var(--text); - font-family:'Inter',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif; - font-size:15px; line-height:1.55; letter-spacing:-.005em; - -webkit-font-smoothing:antialiased; text-rendering:optimizeLegibility; - min-height:100vh; overflow-x:hidden; -} -img,video{max-width:100%; display:block} -a{color:inherit; text-decoration:none} -button,input,textarea,select{font:inherit; color:inherit} -h1,h2,h3,h4{margin:0; line-height:1.15; letter-spacing:-.025em; font-weight:800} -p{margin:0 0 12px} -::selection{background:rgba(255,79,216,.35); color:#fff} -:focus-visible{outline:none; box-shadow:var(--ring); border-radius:var(--r2)} - -/* ------------------------------------------- атмосферный фон (aurora) */ -body::before{ - content:''; position:fixed; inset:0; z-index:-2; pointer-events:none; - background: - radial-gradient(58vw 58vw at 12% -8%, rgba(255,79,216,.16), transparent 62%), - radial-gradient(52vw 52vw at 92% 4%, rgba(92,200,255,.13), transparent 60%), - radial-gradient(60vw 46vw at 68% 108%, rgba(139,92,246,.16), transparent 62%), - linear-gradient(180deg,#07060e 0%,#06060c 40%,#08070f 100%); -} -body::after{ /* тонкое зерно, чтобы фон не был «плоским» */ - content:''; position:fixed; inset:0; z-index:-1; pointer-events:none; opacity:.5; - background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='140' height='140'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='140' height='140' filter='url(%23n)' opacity='.055'/%3E%3C/svg%3E"); -} - -/* ------------------------------------------------------------- каркас */ -.app{display:flex; gap:28px; max-width:var(--maxw); margin:0 auto; padding:0 22px} -.main{flex:1; min-width:0; padding:26px 0 120px} -.main.narrow{max-width:520px; margin:0 auto} - -/* ------------------------------------------------------------- сайдбар */ -.sidebar{ - width:var(--side-w); flex:none; position:sticky; top:0; align-self:flex-start; - height:100vh; padding:22px 14px calc(18px + var(--safe-b)); display:flex; flex-direction:column; gap:18px; - border-right:1px solid var(--border); -} -.brand{display:flex; align-items:center; gap:11px; padding:6px 8px; border-radius:var(--r3)} -.brand img{width:38px; height:38px; border-radius:11px; box-shadow:var(--glow)} -.brand .name{display:block; font-weight:900; font-size:1.12rem; letter-spacing:-.03em; - background:var(--grad); -webkit-background-clip:text; background-clip:text; color:transparent} -.brand .tag{display:block; font-size:.66rem; text-transform:uppercase; letter-spacing:.16em; color:var(--text3)} -.nav{display:flex; flex-direction:column; gap:3px; flex:1; overflow-y:auto; scrollbar-width:thin} -.nav-link{ - position:relative; display:flex; align-items:center; gap:12px; padding:11px 13px; - border-radius:var(--r2); color:var(--text2); font-weight:600; font-size:.93rem; - transition:color var(--fast) var(--ease), background var(--fast) var(--ease), transform var(--fast) var(--ease); -} -.nav-link svg{width:20px; height:20px; flex:none; transition:transform var(--med) var(--spring)} -.nav-link:hover{color:var(--text); background:var(--surface2); transform:translateX(2px)} -.nav-link:hover svg{transform:scale(1.12)} -.nav-link.active{ - color:#fff; background:linear-gradient(100deg,rgba(255,79,216,.20),rgba(139,92,246,.14) 60%,transparent); - box-shadow:inset 0 0 0 1px rgba(255,255,255,.09); -} -.nav-link.active::before{ - content:''; position:absolute; left:-14px; top:50%; transform:translateY(-50%); - width:3px; height:22px; border-radius:0 3px 3px 0; background:var(--grad); box-shadow:var(--glow); -} -.nav-link.active svg{color:var(--pink2)} -.badge{ - margin-left:auto; min-width:20px; height:20px; padding:0 6px; border-radius:var(--rfull); - display:inline-flex; align-items:center; justify-content:center; - font-size:.7rem; font-weight:800; color:#fff; background:var(--grad-warm); box-shadow:0 2px 10px rgba(255,46,99,.4); -} -.badge.muted{background:var(--surface3); color:var(--text2); box-shadow:none; font-weight:700} -.badge.green{background:linear-gradient(115deg,#2fe0a1,#12b981); box-shadow:0 2px 10px rgba(47,224,161,.35)} -.badge.gold{background:var(--grad-gold); color:#3a2500; box-shadow:0 2px 10px rgba(255,209,102,.35)} -.user-card{ - display:flex; align-items:center; gap:12px; padding:11px; border-radius:var(--r3); - background:var(--surface); border:1px solid var(--border); transition:border-color var(--fast), transform var(--fast) var(--ease); -} -.user-card:hover{border-color:var(--border2); transform:translateY(-1px)} -.user-card .who{min-width:0; display:flex; flex-direction:column; gap:2px} -.user-card b{font-size:.9rem; white-space:nowrap; overflow:hidden; text-overflow:ellipsis} -.user-card span{font-size:.74rem; color:var(--text3)} -.coin-pill{ - display:inline-flex; align-items:center; gap:5px; padding:2px 9px; border-radius:var(--rfull); - background:rgba(255,209,102,.13); color:var(--gold); font-weight:800; font-size:.74rem; - border:1px solid rgba(255,209,102,.22); -} -.coin-pill svg{width:13px; height:13px} - -/* ------------------------------------------------------------- топбар */ -.topbar{ - display:none; position:sticky; top:0; z-index:60; align-items:center; gap:10px; - padding:calc(9px + var(--safe-t)) 14px 9px; margin:0 -22px 6px; - background:rgba(8,7,14,.72); -webkit-backdrop-filter:blur(20px) saturate(160%); backdrop-filter:blur(20px) saturate(160%); - border-bottom:1px solid var(--border); -} -.topbar .brand{flex:1; min-width:0} -.topbar .brand img{width:30px; height:30px; border-radius:9px} -.topbar .brand span{font-weight:800; font-size:1rem; letter-spacing:-.02em; - background:var(--grad); -webkit-background-clip:text; background-clip:text; color:transparent} -.topbar .spacer{flex:1} -.icon-btn{ - position:relative; display:inline-flex; align-items:center; justify-content:center; - width:40px; height:40px; border-radius:var(--r2); border:1px solid transparent; - background:var(--surface); color:var(--text2); cursor:pointer; - transition:all var(--fast) var(--ease); -} -.icon-btn svg{width:20px; height:20px} -.icon-btn:hover{color:#fff; background:var(--surface3); border-color:var(--border2); transform:translateY(-1px)} -.icon-btn:active{transform:scale(.94)} -.icon-btn .dot{ - position:absolute; top:5px; right:5px; min-width:16px; height:16px; padding:0 4px; - border-radius:var(--rfull); background:var(--grad-warm); color:#fff; - font-size:.62rem; font-weight:800; display:flex; align-items:center; justify-content:center; - border:2px solid var(--bg); animation:pulse 2.4s var(--ease) infinite; -} - -/* --------------------------------------------------- нижняя навигация */ -.bottomnav{ - display:none; position:fixed; left:50%; transform:translateX(-50%); bottom:calc(10px + var(--safe-b)); - z-index:70; width:min(560px,calc(100vw - 24px)); padding:7px; - background:rgba(12,10,20,.82); -webkit-backdrop-filter:blur(22px) saturate(170%); backdrop-filter:blur(22px) saturate(170%); - border:1px solid var(--border2); border-radius:var(--r5); box-shadow:var(--sh3); -} -.bottomnav .items{display:flex; align-items:center; justify-content:space-around; gap:2px} -.bottomnav a{ - position:relative; flex:1; display:flex; flex-direction:column; align-items:center; gap:3px; - padding:8px 4px 7px; border-radius:var(--r3); color:var(--text3); font-size:.66rem; font-weight:700; - transition:color var(--fast) var(--ease), transform var(--med) var(--spring); -} -.bottomnav a svg{width:22px; height:22px; transition:transform var(--med) var(--spring)} -.bottomnav a:active{transform:scale(.9)} -.bottomnav a.active{color:#fff} -.bottomnav a.active svg{color:var(--pink2); transform:translateY(-2px) scale(1.08)} -.bottomnav a.active::after{ - content:''; position:absolute; bottom:1px; width:18px; height:3px; border-radius:3px; background:var(--grad); box-shadow:var(--glow); -} -.bottomnav .dot{ - position:absolute; top:5px; right:calc(50% - 18px); min-width:16px; height:16px; padding:0 4px; - border-radius:var(--rfull); background:var(--grad-warm); color:#fff; font-size:.6rem; font-weight:800; - display:flex; align-items:center; justify-content:center; border:2px solid rgba(12,10,20,.9); -} - -/* --------------------------------------------------------- аватарки */ -.avatar{border-radius:var(--rfull); object-fit:cover; background:var(--surface3); flex:none} -.avatar-ph{ - display:inline-flex; align-items:center; justify-content:center; border-radius:var(--rfull); - background:var(--grad); color:#fff; font-weight:800; flex:none; letter-spacing:0; - box-shadow:inset 0 0 0 1px rgba(255,255,255,.14); -} -.avatar-wrap{position:relative; display:inline-flex; flex:none} -.dot-status{ - position:absolute; right:-1px; bottom:-1px; width:12px; height:12px; border-radius:var(--rfull); - border:2.5px solid var(--bg); background:var(--text3); display:block; -} -.dot-status.online{background:var(--green); box-shadow:0 0 0 0 rgba(47,224,161,.55); animation:pulse 2.2s infinite} -.dot-status.offline{background:#4a4660} - -/* ------------------------------------------------------------ кнопки */ -.btn{ - --btn-bg:var(--surface2); - position:relative; display:inline-flex; align-items:center; justify-content:center; gap:8px; - padding:11px 18px; border-radius:var(--r2); border:1px solid var(--border2); - background:var(--btn-bg); color:var(--text); font-weight:700; font-size:.92rem; cursor:pointer; - overflow:hidden; white-space:nowrap; - transition:transform var(--fast) var(--spring), box-shadow var(--med) var(--ease), filter var(--fast); -} -.btn svg{width:18px; height:18px; flex:none} -.btn::after{ /* блик сверху */ - content:''; position:absolute; inset:0; border-radius:inherit; pointer-events:none; - background:linear-gradient(180deg,rgba(255,255,255,.16),transparent 55%); opacity:.7; -} -.btn:hover{transform:translateY(-2px); box-shadow:var(--sh2)} -.btn:active{transform:translateY(0) scale(.975)} -.btn:disabled{opacity:.5; pointer-events:none} -.btn-primary,.btn:not(.btn-ghost):not(.btn-gold):not(.btn-sm){ - background:var(--grad); border-color:transparent; color:#fff; box-shadow:var(--glow); -} -.btn-primary:hover,.btn:not(.btn-ghost):not(.btn-gold):not(.btn-sm):hover{box-shadow:0 12px 34px rgba(255,79,216,.4)} -.btn-ghost{background:var(--surface); border-color:var(--border); color:var(--text2)} -.btn-ghost:hover{color:#fff; background:var(--surface2); border-color:var(--border2)} -.btn-gold{background:var(--grad-gold); border-color:transparent; color:#3a2500; box-shadow:0 8px 26px rgba(255,209,102,.3)} -.btn-lg{padding:14px 24px; font-size:1rem; border-radius:var(--r3)} -.btn-sm{padding:8px 13px; font-size:.84rem; border-radius:var(--r1); gap:6px} -.btn-sm svg{width:15px; height:15px} -.btn-block{width:100%} -.btn-danger{background:linear-gradient(115deg,#ff5c7a,#ff2e63); border-color:transparent; color:#fff} - -/* ------------------------------------------------------------- чипы */ -.chip{ - display:inline-flex; align-items:center; gap:7px; padding:8px 14px; border-radius:var(--rfull); - background:var(--surface); border:1px solid var(--border); color:var(--text2); - font-size:.86rem; font-weight:700; cursor:pointer; - transition:all var(--fast) var(--ease); -} -.chip svg{width:16px; height:16px} -.chip:hover{color:#fff; background:var(--surface2); border-color:var(--border2); transform:translateY(-1px)} -.chip.on{background:var(--grad); border-color:transparent; color:#fff; box-shadow:var(--glow)} - -/* ------------------------------------------------------------- карточки */ -.card{ - position:relative; background:linear-gradient(180deg,var(--surface2),var(--surface)); - border:1px solid var(--border); border-radius:var(--r3); box-shadow:var(--sh1); - -webkit-backdrop-filter:blur(12px); backdrop-filter:blur(12px); -} -.card::before{ /* верхний блик */ - content:''; position:absolute; inset:0; border-radius:inherit; pointer-events:none; - background:linear-gradient(180deg,var(--hl),transparent 30%); -} -.card-pad{padding:20px} -.card-hover{transition:transform var(--med) var(--ease), box-shadow var(--med) var(--ease), border-color var(--fast)} -.card-hover:hover{transform:translateY(-3px); box-shadow:var(--sh2); border-color:var(--border2)} - -/* ------------------------------------------------- сетка историй */ -.story-grid{display:grid; grid-template-columns:repeat(auto-fill,minmax(230px,1fr)); gap:18px} -.story-grid.featured{grid-template-columns:repeat(auto-fill,minmax(230px,1fr))} -.story-card{overflow:hidden; display:flex; flex-direction:column; padding:0; isolation:isolate} -.story-card .thumb{ - position:relative; display:block; aspect-ratio:4/5; overflow:hidden; background:var(--bg3); -} -.story-card .thumb img,.story-card .thumb video{width:100%; height:100%; object-fit:cover; transition:transform var(--slow) var(--ease)} -.story-card:hover .thumb img,.story-card:hover .thumb video{transform:scale(1.07)} -.story-card .thumb::after{ - content:''; position:absolute; inset:0; pointer-events:none; - background:linear-gradient(180deg,rgba(6,6,12,.05) 0%,transparent 32%,rgba(6,6,12,.62) 100%); -} -.story-card .body{padding:13px 15px 15px; display:flex; flex-direction:column; gap:9px} -.story-card .title{font-size:.98rem; font-weight:700; letter-spacing:-.015em; - display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; min-height:2.3em} -.story-card .title a{transition:color var(--fast)} -.story-card .title a:hover{color:var(--pink2)} -.story-card .stats{display:flex; align-items:center; gap:12px; color:var(--text3); font-size:.78rem; font-weight:600} -.story-card .stats span{display:inline-flex; align-items:center; gap:5px} -.story-card .stats svg{width:15px; height:15px} -.story-card.playing .thumb img{transform:scale(1.04)} - -.tag-hot,.tag-type,.tag-dur{ - position:absolute; z-index:3; display:inline-flex; align-items:center; gap:5px; - padding:4px 9px; border-radius:var(--rfull); font-size:.68rem; font-weight:800; letter-spacing:.03em; - background:rgba(10,8,16,.6); -webkit-backdrop-filter:blur(8px); backdrop-filter:blur(8px); - border:1px solid rgba(255,255,255,.14); color:#fff; -} -.tag-hot{top:10px; left:10px; background:linear-gradient(115deg,#ff2e63,#ff6ad5); border-color:transparent; box-shadow:0 4px 14px rgba(255,46,99,.45)} -.tag-type{top:10px; right:10px} -.tag-type svg{width:13px; height:13px} -.tag-dur{bottom:10px; right:10px; font-variant-numeric:tabular-nums; opacity:0; transform:translateY(4px); transition:all var(--med) var(--ease)} -.tag-dur.show{opacity:1; transform:none} -.play-ov{ - position:absolute; inset:0; z-index:2; display:grid; place-items:center; opacity:0; - transition:opacity var(--med) var(--ease); pointer-events:none; -} -.play-ov span{ - width:58px; height:58px; border-radius:var(--rfull); display:grid; place-items:center; - background:rgba(10,8,16,.5); -webkit-backdrop-filter:blur(10px); backdrop-filter:blur(10px); - border:1px solid rgba(255,255,255,.22); box-shadow:0 10px 30px rgba(0,0,0,.5); - transform:scale(.7); transition:transform var(--med) var(--spring); -} -.play-ov span svg,.play-ov svg{width:24px; height:24px; margin-left:2px; color:#fff} -.story-card:hover .play-ov{opacity:1} -.story-card:hover .play-ov span{transform:scale(1)} -.uploader-chip{ - position:absolute; left:10px; bottom:10px; z-index:4; display:flex; align-items:center; gap:8px; - padding:4px 11px 4px 4px; border-radius:var(--rfull); max-width:calc(100% - 20px); - background:rgba(10,8,16,.55); -webkit-backdrop-filter:blur(10px); backdrop-filter:blur(10px); - border:1px solid rgba(255,255,255,.14); color:#fff; font-size:.76rem; font-weight:700; - transition:transform var(--fast) var(--ease), background var(--fast); -} -.uploader-chip:hover{transform:translateY(-2px); background:rgba(20,16,30,.75)} -.uploader-chip img,.uploader-chip .avatar-ph{width:28px; height:28px; font-size:.8rem; border:1.5px solid rgba(255,255,255,.32)} -.uploader-chip span{white-space:nowrap; overflow:hidden; text-overflow:ellipsis} - -/* featured-карточка (первая в ленте) */ -.story-card.featured{grid-column:span 2} -@media (max-width:640px){ .story-card.featured{grid-column:span 2} } -.story-card.featured .thumb{aspect-ratio:16/10} -.story-card.featured .title{font-size:1.1rem; -webkit-line-clamp:2} - -/* ------------------------------------------------------- заголовки */ -.page-head{display:flex; align-items:flex-end; justify-content:space-between; gap:18px; flex-wrap:wrap; margin-bottom:22px} -.page-title{font-size:clamp(1.7rem,3.4vw,2.5rem); font-weight:900; letter-spacing:-.035em} -.page-sub{color:var(--text2); font-size:.95rem; margin-top:6px} -.grad{background:var(--grad); -webkit-background-clip:text; background-clip:text; color:transparent} -.section-title{display:flex; align-items:center; gap:9px; font-size:1.05rem; font-weight:800; margin:26px 0 14px; letter-spacing:-.02em} -.section-title svg{width:19px; height:19px; color:var(--pink2)} -.eyebrow{font-size:.68rem; font-weight:800; text-transform:uppercase; letter-spacing:.18em; color:var(--text3); margin-bottom:8px} - -/* -------------------------------------------------- пустые состояния */ -.empty{ - text-align:center; padding:56px 24px; border-radius:var(--r4); border:1px dashed var(--border2); - background:linear-gradient(180deg,var(--surface),transparent); -} -.empty .art{ - width:76px; height:76px; margin:0 auto 18px; border-radius:var(--r4); display:grid; place-items:center; - background:var(--grad-soft); border:1px solid var(--border2); color:var(--pink2); - animation:float 5s var(--ease) infinite; -} -.empty .art svg{width:34px; height:34px} -.empty h3{font-size:1.2rem; margin-bottom:8px} -.empty p{color:var(--text2); max-width:420px; margin:0 auto 20px} - -/* -------------------------------------------------------- скелетоны */ -.skeleton{position:relative; overflow:hidden; background:var(--surface2); border-radius:var(--r2)} -.skeleton::after{ - content:''; position:absolute; inset:0; transform:translateX(-100%); - background:linear-gradient(90deg,transparent,rgba(255,255,255,.09),transparent); - animation:shimmer 1.5s infinite; -} -.sk-card{border-radius:var(--r3); overflow:hidden; border:1px solid var(--border)} -.sk-card .sk-thumb{aspect-ratio:4/5} -.sk-card .sk-body{padding:14px} -.sk-line{height:11px; border-radius:6px; margin-bottom:9px} -.sk-line.w60{width:60%} .sk-line.w40{width:40%} .sk-line.w80{width:80%} - -/* ---------------------------------------------------------- профиль */ -.prof-cover{ - position:relative; height:190px; border-radius:var(--r3) var(--r3) 0 0; overflow:hidden; - background: - radial-gradient(70% 130% at 12% 0%, rgba(255,79,216,.55), transparent 60%), - radial-gradient(70% 130% at 88% 10%, rgba(92,200,255,.45), transparent 62%), - radial-gradient(90% 140% at 50% 120%, rgba(139,92,246,.5), transparent 65%), - linear-gradient(120deg,#161028,#0d0a18); -} -.prof-cover .deco{ - position:absolute; inset:0; opacity:.5; - background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='120'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.8' numOctaves='3'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='120' height='120' filter='url(%23n)' opacity='.16'/%3E%3C/svg%3E"); -} -.prof-cover::after{ - content:''; position:absolute; inset:auto 0 0 0; height:60%; - background:linear-gradient(180deg,transparent,rgba(8,7,14,.85)); -} -.prof-head{display:flex; gap:20px; align-items:flex-end; padding:0 24px 20px; margin-top:-52px; position:relative; flex-wrap:wrap} -.prof-head .avatar,.prof-head .avatar-ph{border:4px solid #0b0912; box-shadow:0 12px 34px rgba(0,0,0,.6)} -.prof-head .who{flex:1; min-width:200px; padding-bottom:4px} -.prof-head h1{font-size:clamp(1.4rem,2.6vw,2rem); display:flex; align-items:center; gap:10px; flex-wrap:wrap} -.role-badge{ - display:inline-flex; align-items:center; gap:6px; padding:3px 10px; border-radius:var(--rfull); - font-size:.7rem; font-weight:800; text-transform:uppercase; letter-spacing:.09em; - background:var(--grad-soft); border:1px solid var(--border2); color:var(--pink2); -} -.prof-head .bio{color:var(--text2); font-size:.92rem; margin-top:8px; max-width:520px} -.stat-row{display:grid; grid-template-columns:repeat(auto-fit,minmax(120px,1fr)); gap:12px; margin:18px 0} -.stat{ - padding:14px 16px; border-radius:var(--r2); background:var(--surface); border:1px solid var(--border); - transition:transform var(--fast) var(--ease), border-color var(--fast); -} -.stat:hover{transform:translateY(-2px); border-color:var(--border2)} -.stat b{display:block; font-size:1.35rem; font-weight:900; letter-spacing:-.03em; - background:var(--grad); -webkit-background-clip:text; background-clip:text; color:transparent} -.stat span{font-size:.72rem; color:var(--text3); text-transform:uppercase; letter-spacing:.12em; font-weight:700} -.tabs{display:flex; gap:4px; padding:4px; border-radius:var(--rfull); background:var(--surface); border:1px solid var(--border); width:max-content; margin-bottom:18px} -.tabs a{padding:8px 16px; border-radius:var(--rfull); font-size:.87rem; font-weight:700; color:var(--text2); transition:all var(--fast) var(--ease)} -.tabs a:hover{color:#fff} -.tabs a.on{background:var(--grad); color:#fff; box-shadow:var(--glow)} - -/* --------------------------------------------------- страница истории */ -.story-layout{display:grid; grid-template-columns:minmax(0,1fr) 320px; gap:24px; align-items:start} -.media-wrap{position:relative; border-radius:var(--r4); overflow:hidden; background:#000; box-shadow:var(--sh3); border:1px solid var(--border)} -.media-wrap::after{content:''; position:absolute; inset:0; pointer-events:none; box-shadow:inset 0 0 0 1px rgba(255,255,255,.07)} -.imgview{width:100%; max-height:78vh; object-fit:contain; background:#000; display:block} -.media-glow{position:absolute; inset:12% 8% -6%; z-index:-1; filter:blur(46px); opacity:.55; border-radius:var(--r5); background:var(--grad)} -.action-bar{display:flex; gap:10px; flex-wrap:wrap; align-items:center; margin:20px 0} -.action-bar .btn{min-height:44px} -.count-pill{ - display:inline-flex; align-items:center; justify-content:center; min-width:24px; padding:1px 7px; - border-radius:var(--rfull); background:rgba(0,0,0,.28); font-size:.8rem; font-weight:800; font-variant-numeric:tabular-nums; -} -.like-btn.liked{background:var(--grad-warm); border-color:transparent; color:#fff; box-shadow:0 8px 24px rgba(255,46,99,.4)} -.like-btn.liked svg{fill:currentColor} -@keyframes pop{0%{transform:scale(1)}45%{transform:scale(1.22)}100%{transform:scale(1)}} -.pulsing{animation:pop .42s var(--spring)} -.side-box{display:flex; flex-direction:column; gap:16px; position:sticky; top:20px} - -/* ------------------------------------------------------- комментарии */ -.comment{display:flex; gap:12px; padding:14px 0; border-bottom:1px solid var(--border)} -.comment:last-child{border-bottom:0} -.comment .cbody{flex:1; min-width:0} -.comment .h{display:flex; align-items:center; gap:9px; margin-bottom:4px} -.comment .h a{font-weight:700; font-size:.9rem} -.comment .h a:hover{color:var(--pink2)} -.comment .h span{font-size:.74rem; color:var(--text3)} -.comment .txt{color:var(--text2); font-size:.92rem; overflow-wrap:anywhere} - -/* ------------------------------------------------------------- чат */ -.chat-head{display:flex; align-items:center; gap:14px; padding:14px 16px; margin-bottom:14px} -.msg-list{ - display:flex; flex-direction:column; gap:8px; padding:18px; border-radius:var(--r3); - background:linear-gradient(180deg,var(--surface),transparent); border:1px solid var(--border); - max-height:62vh; overflow-y:auto; scroll-behavior:smooth; -} -.msg{ - position:relative; max-width:min(72%,460px); padding:10px 14px; border-radius:18px; - font-size:.93rem; line-height:1.45; overflow-wrap:anywhere; animation:msgIn .28s var(--spring) both; -} -.msg .t{display:block; margin-top:4px; font-size:.66rem; opacity:.6; font-variant-numeric:tabular-nums} -.msg.in{align-self:flex-start; background:var(--surface3); border:1px solid var(--border); border-bottom-left-radius:6px} -.msg.out{align-self:flex-end; background:var(--grad); color:#fff; border-bottom-right-radius:6px; box-shadow:0 6px 20px rgba(139,92,246,.28)} -.msg .seen{display:inline-flex; vertical-align:-2px; margin-left:4px; opacity:.85} -.msg .seen svg{width:14px; height:14px} -.day-sep{align-self:center; margin:12px 0 6px; padding:4px 12px; border-radius:var(--rfull); - background:var(--surface2); border:1px solid var(--border); color:var(--text3); font-size:.7rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase} -.msg-form{display:flex; gap:10px; align-items:flex-end; margin-top:14px} -.msg-form textarea{ - flex:1; resize:none; padding:12px 16px; border-radius:var(--r3); max-height:160px; - background:var(--surface); border:1px solid var(--border); color:var(--text); - transition:border-color var(--fast), box-shadow var(--fast); -} -.msg-form textarea:focus{outline:none; border-color:rgba(255,79,216,.5); box-shadow:0 0 0 4px rgba(255,79,216,.12)} -.msg-form .btn{height:46px; padding:0 18px; border-radius:var(--r3)} -.conversation-item{display:flex; gap:14px; align-items:center; padding:14px 16px; margin-bottom:11px; color:var(--text)} -.conversation-item.unread{border-color:rgba(255,79,216,.45); background:var(--grad-soft)} -.conv-body{flex:1; min-width:0} -.conv-top{display:flex; align-items:center; gap:8px; font-size:.96rem} -.conv-top b{white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:180px} -.conv-time{font-size:.74rem; color:var(--text3); margin-left:auto; flex:none} -.conv-last{display:block; font-size:.86rem; color:var(--text2); white-space:nowrap; overflow:hidden; text-overflow:ellipsis} -.typing{display:inline-flex; gap:4px; align-items:center; padding:12px 16px; align-self:flex-start; - background:var(--surface3); border:1px solid var(--border); border-radius:18px; border-bottom-left-radius:6px} -.typing i{width:7px; height:7px; border-radius:50%; background:var(--text2); animation:blink 1.2s infinite} -.typing i:nth-child(2){animation-delay:.2s} .typing i:nth-child(3){animation-delay:.4s} - -/* ------------------------------------------------ список пользователей */ -.user-grid{display:grid; grid-template-columns:repeat(auto-fill,minmax(220px,1fr)); gap:14px} -.user-item{display:flex; align-items:center; gap:13px; padding:14px} -.user-item .who{min-width:0; display:flex; flex-direction:column; gap:2px} -.user-item b{font-size:.94rem; white-space:nowrap; overflow:hidden; text-overflow:ellipsis} -.user-item span{font-size:.76rem; color:var(--text3); display:flex; align-items:center; gap:5px} - -/* --------------------------------------------------- уведомления */ -.setting-row{ - display:flex; align-items:center; gap:14px; padding:16px; border-radius:var(--r2); - background:var(--surface); border:1px solid var(--border); margin-bottom:10px; -} -.setting-row .ic{ - width:42px; height:42px; border-radius:var(--r2); display:grid; place-items:center; flex:none; - background:var(--grad-soft); color:var(--pink2); border:1px solid var(--border2); -} -.setting-row .ic svg{width:20px; height:20px} -.setting-row .txt{flex:1; min-width:0} -.setting-row b{display:block; font-size:.94rem} -.setting-row small{color:var(--text3); font-size:.8rem} -.switch{position:relative; width:52px; height:30px; flex:none} -.switch input{position:absolute; opacity:0; width:100%; height:100%; margin:0; cursor:pointer} -.switch i{ - position:absolute; inset:0; border-radius:var(--rfull); background:var(--surface3); - border:1px solid var(--border2); transition:background var(--med) var(--ease); -} -.switch i::after{ - content:''; position:absolute; top:3px; left:3px; width:22px; height:22px; border-radius:50%; - background:#fff; box-shadow:0 2px 8px rgba(0,0,0,.4); transition:transform var(--med) var(--spring); -} -.switch input:checked + i{background:var(--grad); border-color:transparent} -.switch input:checked + i::after{transform:translateX(22px)} -.switch input:disabled + i{opacity:.45} -.switch input:focus-visible + i{box-shadow:var(--ring)} - -/* --------------------------------------------------------- загрузка */ -.dropzone{ - position:relative; display:grid; place-items:center; gap:12px; text-align:center; - padding:44px 22px; border-radius:var(--r3); border:2px dashed var(--border2); - background:linear-gradient(180deg,var(--surface),transparent); cursor:pointer; - transition:all var(--med) var(--ease); -} -.dropzone:hover,.dropzone.drag{border-color:var(--pink); background:var(--grad-soft); transform:translateY(-2px)} -.dropzone .ic{width:64px; height:64px; border-radius:var(--r3); display:grid; place-items:center; - background:var(--grad-soft); border:1px solid var(--border2); color:var(--pink2)} -.dropzone .ic svg{width:28px; height:28px} -.dropzone b{font-size:1.02rem} -.dropzone small{color:var(--text3)} -.progress{height:8px; border-radius:var(--rfull); background:var(--surface3); overflow:hidden} -.progress i{display:block; height:100%; width:0; border-radius:inherit; background:var(--grad); transition:width var(--med) var(--ease)} - -/* ------------------------------------------------------------ формы */ -.field{margin-bottom:16px} -.field label{display:block; font-size:.78rem; font-weight:800; text-transform:uppercase; letter-spacing:.12em; color:var(--text3); margin-bottom:7px} -.input,.field input,.field textarea,.field select{ - width:100%; padding:12px 15px; border-radius:var(--r2); background:var(--surface); - border:1px solid var(--border); color:var(--text); transition:all var(--fast) var(--ease); -} -.field input:focus,.field textarea:focus,.field select:focus,.input:focus{ - outline:none; border-color:rgba(255,79,216,.55); box-shadow:0 0 0 4px rgba(255,79,216,.12); background:var(--surface2); -} -.field input::placeholder,.field textarea::placeholder{color:var(--text3)} -.hint{font-size:.78rem; color:var(--text3); margin-top:6px} -.checkline{display:flex; align-items:center; gap:9px; font-size:.88rem; color:var(--text2); cursor:pointer} -.checkline input{width:18px; height:18px; accent-color:#ff4fd8} - -/* --------------------------------------------------- авторизация */ -.auth{display:grid; grid-template-columns:1.05fr .95fr; gap:0; overflow:hidden; border-radius:var(--r4); border:1px solid var(--border); box-shadow:var(--sh3)} -.auth .promo{ - position:relative; padding:44px 40px; display:flex; flex-direction:column; justify-content:space-between; gap:28px; - background: - radial-gradient(60% 60% at 20% 15%, rgba(255,79,216,.32), transparent 60%), - radial-gradient(60% 60% at 85% 80%, rgba(92,200,255,.26), transparent 62%), - linear-gradient(160deg,#120f1f,#0a0812); -} -.auth .promo h2{font-size:clamp(1.6rem,2.6vw,2.2rem); letter-spacing:-.035em} -.auth .promo p{color:var(--text2)} -.auth .promo .points{display:flex; flex-direction:column; gap:12px} -.auth .promo .point{display:flex; gap:11px; align-items:flex-start; font-size:.9rem; color:var(--text2)} -.auth .promo .point svg{width:20px; height:20px; color:var(--pink2); flex:none; margin-top:1px} -.auth .form-side{padding:38px 34px; background:rgba(10,9,16,.6)} -@media (max-width:860px){ - .auth{grid-template-columns:1fr} - .auth .promo{display:none} -} - -/* -------------------------------------------------- тосты и модалки */ -.flash-stack{position:fixed; top:calc(16px + var(--safe-t)); right:16px; z-index:200; display:flex; flex-direction:column; gap:10px; max-width:min(360px,calc(100vw - 32px))} -.toast{ - display:flex; gap:12px; align-items:flex-start; padding:13px 15px; border-radius:var(--r2); - background:rgba(16,14,26,.92); -webkit-backdrop-filter:blur(18px); backdrop-filter:blur(18px); - border:1px solid var(--border2); box-shadow:var(--sh3); animation:toastIn .38s var(--spring) both; -} -.toast.out{animation:toastOut .3s var(--ease) forwards} -.toast .ic{width:26px; height:26px; border-radius:var(--rfull); display:grid; place-items:center; flex:none; font-size:.78rem; font-weight:900} -.toast.success .ic{background:rgba(47,224,161,.18); color:var(--green)} -.toast.error .ic{background:rgba(255,92,122,.18); color:var(--red)} -.toast.warning .ic{background:rgba(255,209,102,.18); color:var(--gold)} -.toast.info .ic{background:rgba(92,200,255,.18); color:var(--blue)} -.toast b{display:block; font-size:.88rem; text-transform:capitalize} -.toast span{font-size:.82rem; color:var(--text2)} -.modal{ - position:fixed; inset:0; z-index:300; display:none; place-items:center; padding:20px; - background:rgba(4,3,8,.72); -webkit-backdrop-filter:blur(10px); backdrop-filter:blur(10px); -} -.modal.open{display:grid; animation:fadeIn .2s var(--ease)} -.modal .box{ - width:min(520px,100%); max-height:86vh; overflow:auto; border-radius:var(--r4); - background:rgba(16,14,26,.97); border:1px solid var(--border2); box-shadow:var(--sh3); - animation:modalIn .34s var(--spring) both; -} -.modal .box .head{display:flex; align-items:center; justify-content:space-between; gap:12px; padding:18px 20px; border-bottom:1px solid var(--border)} -.modal .box .head h3{font-size:1.06rem} -.modal .box .content{padding:20px} -.steps{display:flex; flex-direction:column; gap:14px} -.step{display:flex; gap:13px; align-items:flex-start} -.step .n{ - width:28px; height:28px; border-radius:var(--rfull); display:grid; place-items:center; flex:none; - background:var(--grad); color:#fff; font-size:.82rem; font-weight:800; box-shadow:var(--glow); -} -.step .t b{display:block; font-size:.92rem; margin-bottom:2px} -.step .t span{font-size:.84rem; color:var(--text2)} - -/* -------------------------------------------------------- баннеры */ -.banner{ - display:flex; align-items:center; gap:13px; padding:12px 14px; margin-bottom:14px; - border-radius:var(--r3); background:linear-gradient(100deg,rgba(255,79,216,.14),rgba(139,92,246,.10)); - border:1px solid rgba(255,79,216,.28); box-shadow:0 8px 26px rgba(255,79,216,.12); - animation:slideDown .34s var(--spring) both; -} -.banner.hidden{display:none} -.banner .ic{width:38px; height:38px; border-radius:var(--r2); display:grid; place-items:center; flex:none; - background:var(--grad); color:#fff; box-shadow:var(--glow)} -.banner .ic svg{width:19px; height:19px} -.banner .txt{flex:1; min-width:0} -.banner .txt b{display:block; font-size:.92rem} -.banner .txt span{font-size:.8rem; color:var(--text2)} -.banner .x{background:none; border:0; color:var(--text3); font-size:1.3rem; cursor:pointer; padding:4px 8px; border-radius:var(--r1)} -.banner .x:hover{color:#fff; background:var(--surface2)} - -/* ------------------------------------------------------- футер */ -.foot{ - display:flex; justify-content:space-between; gap:14px; flex-wrap:wrap; margin-top:44px; padding-top:20px; - border-top:1px solid var(--border); color:var(--text3); font-size:.8rem; -} -.foot a{transition:color var(--fast)} -.foot a:hover{color:var(--pink2)} - -/* ------------------------------------------------ затемнение drawer */ -.overlay-scrim{position:fixed; inset:0; z-index:55; background:rgba(4,3,8,.6); opacity:0; pointer-events:none; transition:opacity var(--med) var(--ease); -webkit-backdrop-filter:blur(4px); backdrop-filter:blur(4px)} -.overlay-scrim.show{opacity:1; pointer-events:auto} - -/* --------------------------------------------------- анимации */ -@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(255,46,99,.45)}70%{box-shadow:0 0 0 9px rgba(255,46,99,0)}100%{box-shadow:0 0 0 0 rgba(255,46,99,0)}} -@keyframes shimmer{100%{transform:translateX(100%)}} -@keyframes float{0%,100%{transform:translateY(0)}50%{transform:translateY(-8px)}} -@keyframes fadeIn{from{opacity:0}to{opacity:1}} -@keyframes slideDown{from{opacity:0; transform:translateY(-14px)}to{opacity:1; transform:none}} -@keyframes toastIn{from{opacity:0; transform:translateX(24px) scale(.96)}to{opacity:1; transform:none}} -@keyframes toastOut{to{opacity:0; transform:translateX(24px) scale(.96)}} -@keyframes modalIn{from{opacity:0; transform:translateY(18px) scale(.96)}to{opacity:1; transform:none}} -@keyframes msgIn{from{opacity:0; transform:translateY(8px) scale(.97)}to{opacity:1; transform:none}} -@keyframes blink{0%,60%,100%{opacity:.25; transform:translateY(0)}30%{opacity:1; transform:translateY(-3px)}} -.reveal{opacity:0; transform:translateY(18px)} -.reveal.in{opacity:1; transform:none; transition:opacity .55s var(--ease), transform .55s var(--ease)} -.ripple{position:absolute; border-radius:50%; transform:scale(0); background:rgba(255,255,255,.32); pointer-events:none; animation:ripple .6s var(--ease) forwards} -@keyframes ripple{to{transform:scale(2.6); opacity:0}} - -/* --------------------------------------------------- адаптив */ -@media (max-width:1080px){ - .story-layout{grid-template-columns:1fr} - .side-box{position:static} -} -@media (max-width:900px){ - :root{--side-w:0px} - .app{padding:0 14px} - .sidebar{ - position:fixed; left:0; top:0; bottom:0; z-index:58; width:min(300px,84vw); - background:rgba(11,9,18,.96); -webkit-backdrop-filter:blur(24px); backdrop-filter:blur(24px); - transform:translateX(-104%); transition:transform var(--med) var(--ease); - border-right:1px solid var(--border2); padding-top:calc(18px + var(--safe-t)); - } - .sidebar.open{transform:none; box-shadow:var(--sh3)} - .nav-link.active::before{left:0} - .topbar{display:flex} - .bottomnav{display:block} - .main{padding-top:12px} - .story-grid{grid-template-columns:repeat(2,1fr); gap:12px} - .story-card.featured{grid-column:span 2} - .story-card .title{font-size:.9rem} - .page-title{font-size:clamp(1.5rem,6vw,2rem)} - .msg-list{max-height:56vh} - .prof-head{margin-top:-40px; padding:0 16px 16px} - .prof-cover{height:150px} - .flash-stack{left:16px; right:16px; max-width:none} -} -@media (max-width:520px){ - .story-grid{grid-template-columns:1fr} - .story-card.featured{grid-template-columns:1fr; grid-column:span 1} - .action-bar{gap:8px} - .action-bar .btn{flex:1 1 auto} - .auth .form-side{padding:26px 20px} -} -@media (prefers-reduced-motion:reduce){ - *,*::before,*::after{animation-duration:.01ms !important; animation-iteration-count:1 !important; transition-duration:.01ms !important} - html{scroll-behavior:auto} - .reveal{opacity:1; transform:none} -} - -/* ------------------------------------------------ доступность */ -.skip{position:absolute; left:-9999px; top:0; z-index:400; padding:12px 18px; background:var(--grad); color:#fff; border-radius:0 0 var(--r2) 0; font-weight:700} -.skip:focus{left:0} -.sr{position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0} - -/* ------------------------------------------------ дополнительные блокы */ -.chips-row{display:flex;gap:9px;flex-wrap:wrap;margin-bottom:22px} -.wrap{max-width:100%} -table.tbl{width:100%;border-collapse:collapse;font-size:.9rem} -table.tbl th{text-align:left;padding:11px 14px;font-size:.7rem;text-transform:uppercase;letter-spacing:.12em;color:var(--text3);border-bottom:1px solid var(--border)} -table.tbl td{padding:13px 14px;border-bottom:1px solid var(--border);color:var(--text2)} -table.tbl tr:last-child td{border-bottom:0} -table.tbl tr:hover td{background:var(--surface)} -table.tbl td b{color:var(--text)} -.amt-pos{color:var(--green);font-weight:800} -.amt-neg{color:var(--red);font-weight:800} -.mini-stat{display:flex;align-items:center;gap:9px;padding:11px 13px;border-radius:var(--r2);background:var(--surface);border:1px solid var(--border)} -.mini-stat svg{width:17px;height:17px;color:var(--pink2);flex:none} -.mini-stat b{font-size:1.05rem;font-weight:800;display:block;line-height:1.2} -.mini-stat span{font-size:.72rem;color:var(--text3)} -.ref-card{display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:16px;border-radius:var(--r2); - background:var(--grad-soft);border:1px solid rgba(255,79,216,.28)} -.ref-card code{flex:1;min-width:180px;padding:11px 14px;border-radius:var(--r1);background:rgba(0,0,0,.35); - border:1px solid var(--border);font-size:.82rem;color:var(--pink2);overflow-wrap:anywhere} -.story-meta{display:flex;align-items:center;gap:10px;flex-wrap:wrap;color:var(--text3);font-size:.84rem;margin-top:10px} -.story-meta .sep{width:4px;height:4px;border-radius:50%;background:var(--text3);display:inline-block} -.badge-row{display:flex;gap:8px;flex-wrap:wrap;margin:10px 0} -.pill{display:inline-flex;align-items:center;gap:6px;padding:4px 11px;border-radius:var(--rfull); - background:var(--surface2);border:1px solid var(--border);font-size:.74rem;font-weight:700;color:var(--text2)} -.pill svg{width:13px;height:13px} -.pill.gold{background:rgba(255,209,102,.14);color:var(--gold);border-color:rgba(255,209,102,.25)} -.pill.green{background:rgba(47,224,161,.14);color:var(--green);border-color:rgba(47,224,161,.25)} -.pill.pink{background:rgba(255,79,216,.14);color:var(--pink2);border-color:rgba(255,79,216,.28)} - -/* --------------------------------------------- кинематографичная сцена */ -.media-stage{position:relative; z-index:0} -.media-stage .media-glow{filter:blur(52px); opacity:.5; transform:scale(.94)} -.media-stage .media-wrap{position:relative; z-index:1} - -/* --------------------------------------------------- авторизация (доп) */ -.auth .promo .brand{padding:0} -.auth .form-side h1{letter-spacing:-.03em} -.auth-alt{margin-top:18px;font-size:.88rem;color:var(--text2);text-align:center} -.auth-alt a{color:var(--pink2);font-weight:700} -.auth-alt a:hover{text-decoration:underline} -.role-grid{display:grid;grid-template-columns:1fr 1fr;gap:9px} -.role-opt{position:relative;display:block;cursor:pointer} -.role-opt input{position:absolute;opacity:0} -.role-opt span{display:block;padding:11px 12px;border-radius:var(--r2);text-align:center; - background:var(--surface);border:1px solid var(--border);font-size:.84rem;font-weight:700;color:var(--text2); - transition:all var(--fast) var(--ease)} -.role-opt:hover span{border-color:var(--border2);color:var(--text)} -.role-opt input:checked + span{background:var(--grad-soft);border-color:rgba(255,79,216,.5);color:#fff;box-shadow:0 4px 16px rgba(255,79,216,.16)} -.ref-box{display:flex;align-items:center;gap:9px;padding:12px 14px;border-radius:var(--r2);margin-bottom:18px; - background:var(--grad-soft);border:1px solid rgba(255,79,216,.3);font-size:.86rem;color:var(--text2)} -.ref-box b{color:var(--pink2)} -.ref-box svg{width:17px;height:17px;color:var(--pink2);flex:none} -@media (max-width:520px){ .role-grid{grid-template-columns:1fr} } - -/* --------------------------------------------- плавающая кнопка наверх */ -.fab{ - position:fixed; right:18px; bottom:calc(84px + var(--safe-b)); z-index:65; - width:46px; height:46px; border-radius:var(--r-full); display:grid; place-items:center; - background:rgba(16,14,26,.86); -webkit-backdrop-filter:blur(16px); backdrop-filter:blur(16px); - border:1px solid var(--border2); color:var(--text2); box-shadow:var(--sh2); cursor:pointer; - opacity:0; transform:translateY(14px) scale(.9); pointer-events:none; - transition:all var(--med) var(--spring); -} -.fab.show{opacity:1; transform:none; pointer-events:auto} -.fab:hover{color:#fff; border-color:var(--pink); box-shadow:var(--glow)} -.fab svg{width:20px;height:20px} -@media (min-width:901px){ .fab{bottom:26px} } - -/* --------------------------------------- транзакции и мелкие элементы */ -.tx-list{display:flex;flex-direction:column;gap:8px} -.tx{display:flex;align-items:center;gap:13px;padding:13px 15px;border-radius:var(--r2); - background:var(--surface);border:1px solid var(--border);transition:border-color var(--fast),transform var(--fast) var(--ease)} -.tx:hover{border-color:var(--border2);transform:translateX(2px)} -.tx .ic{width:34px;height:34px;border-radius:var(--r1);display:grid;place-items:center;flex:none;font-weight:800;font-size:1rem} -.tx .ic.pos{background:rgba(47,224,161,.14);color:var(--green)} -.tx .ic.neg{background:rgba(255,92,122,.14);color:var(--red)} -.tx .what{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px} -.tx .what b{font-size:.9rem} -.tx .what span{font-size:.78rem;color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} -.tx .amt{font-weight:800;font-variant-numeric:tabular-nums;font-size:.95rem;flex:none} -.tx .amt.pos{color:var(--green)} .tx .amt.neg{color:var(--red)} -.form-note{font-size:.82rem;color:var(--text3);line-height:1.5} -.status-card{display:flex;gap:16px;align-items:center;padding:20px;border-radius:var(--r3); - background:var(--grad-soft);border:1px solid rgba(255,79,216,.3);margin-bottom:20px;flex-wrap:wrap} -.status-card .ic{width:52px;height:52px;border-radius:var(--r2);background:var(--grad);display:grid;place-items:center; - color:#fff;flex:none;box-shadow:var(--glow)} -.status-card .ic svg{width:26px;height:26px} -.status-card .t{flex:1;min-width:180px} -.status-card .t b{display:block;font-size:1.05rem;margin-bottom:2px} -.status-card .t span{font-size:.88rem;color:var(--text2)} -.notif-note{display:flex;gap:11px;align-items:flex-start;padding:14px 16px;border-radius:var(--r2); - background:var(--surface);border:1px solid var(--border);font-size:.86rem;color:var(--text2);margin-top:14px} -.notif-note svg{width:18px;height:18px;color:var(--pink2);flex:none;margin-top:1px} -""" - -# ------------------------------------------------------------- SVG-иконки (inline) -ICONS = { - "sparkle": '', - "fire": '', - "user": '', - "users": '', - "upload": '', - "mail": '', - "coin": '', - "logout": '', - "login": '', - "plus": '', - "bell": '', - "menu": '', - "close": '', - "play": '', - "image": '', - "heart": '', - "eye": '', - "chat": '', - "search": '', - "send": '', - "check": '', - "doublecheck": '', - "phone": '', - "download": '', - "share": '', - "gift": '', - "trash": '', - "rocket": '', - "settings": '', - "video": '', - "home": '', - "link": '', - "copy": '', - "clock": '', - "wifi-off": '', -} - - -def icon(name, cls=""): - svg = ICONS.get(name, ICONS["sparkle"]) - if cls: - return svg.replace("' - % (cls, style, html.escape(username), url, - json.dumps((username or "?")[:1].upper()))) - else: - out = ('' - % (cls, style, html.escape((username or "?")[:1].upper()))) - if online is not None: - out = ('%s' - % (out, "online" if online else "offline")) - return out - - -def story_thumb_html(story): - mtype = story.get("type", "photo") - url = media_url(story.get("filename", ""), mtype) - title = html.escape(story.get("title", "Untitled")) - if mtype == "video": - poster = story.get("poster") or "" - poster_attr = (' poster="%s"' % html.escape(poster)) if poster else "" - return ('' - % (poster_attr, url)) - return '%s' % (url, title) - - -def story_card_html(story, show_uploader=True, users_lookup=None, featured=False, - reveal_delay=None): - """Карточка истории: превью, длительность, автор, статистика.""" - promoted = story.get("is_currently_promoted") - is_video = story.get("type") == "video" - href = url_for("story_page", story_id=story.get("id", "")) - uploader = story.get("uploader", "unknown") - likes = len(story.get("likes", []) or []) - views = story.get("views", 0) - jerks = story.get("jerked_off_count", 0) - comments = len(story.get("comments", []) or []) - uploader_data = (users_lookup or {}).get(uploader, {}) - - chip = "" - if show_uploader: - chip = ('%s%s' - % (url_for("user_profile", username=uploader), - avatar_html(uploader_data, uploader, 28), - html.escape(uploader))) - dur = '' if is_video else "" - - reveal_cls = " reveal" if reveal_delay is not None else "" - delay_attr = (' data-delay="%d"' % reveal_delay) if reveal_delay else "" - return """ -
- - %(hot)s - %(type_icon)s - %(play_icon)s - %(dur)s - %(thumb)s - - %(chip)s -
-

%(title)s

-
- %(heart)s %(likes)s - %(eye)s %(views)s - %(chat)s %(comments)s - %(jerks_html)s -
-
-
""" % { - "playing": "", "featured": " featured" if featured else "", - "reveal": reveal_cls, "delay": delay_attr, - "sid": html.escape(story.get("id", "")), - "href": href, "title": html.escape(story.get("title", "Untitled")), - "hot": '🔥 HOT' if promoted else "", - "type_icon": icon("video" if is_video else "image"), - "play_icon": icon("play") if is_video else "", - "dur": dur, - "thumb": story_thumb_html(story), - "chip": chip, - "heart": icon("heart"), "eye": icon("eye"), "chat": icon("chat"), - "likes": likes, "views": views, "comments": comments, - "jerks_html": '🍆 %d' % jerks, - } - - -def empty_state(title, text, action_label=None, action_href=None, art="sparkle"): - action = ('%s' % (action_href, html.escape(action_label)) - if action_label else "") - return ('
%s

%s

%s

%s
' - % (icon(art), html.escape(title), html.escape(text), action)) - - -def flash_toasts(): - """Server-side flash -> тосты.""" - from flask import get_flashed_messages - out = [] - for category, message in get_flashed_messages(with_categories=True): - ic = {"success": "✓", "error": "!", "warning": "⚠", "info": "i"}.get(category, "i") - out.append('
%s' - '
%s%s
' - % (html.escape(category), ic, html.escape(category), - html.escape(message))) - return "".join(out) - - -# ------------------------------------------------------------------ head / page -def page_html(title, description, body, *, path=None, noindex=False, css="", - js="", jsonld=None, og_type="website", og_image=None, active=""): - """Собирает полноценный HTML-документ: SEO-мета, PWA-мета, навигация, скрипты.""" - canonical = abs_url(path or request.path) - og_img = og_image or abs_url("/pwa/icon-512.png") - ld = "" - if jsonld: - ld = ('' - % json.dumps(jsonld, ensure_ascii=False)) - robots = ("noindex,nofollow" if noindex else - "index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1") - - head = """ - - -{title} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -{ld} -""".format( - title=html.escape(title), description=html.escape(description), - robots=robots, canonical=canonical, site=SITE_NAME, og_type=og_type, - og_img=og_img, ld=ld, base_css=BASE_CSS, page_css=css) - - return """ - -{head} - - -
-{topbar} -
- {sidebar} -
- {banners} - {body} - -
-
-{bottomnav} - -
{toasts}
- - - - - - -""".format( - head=head, - topbar=topbar_html(active), - sidebar=sidebar_html(active), - main_class="narrow" if active in ("login", "register") else "", - banners=banners_html(), - body=body, - year=datetime.now().year, site=SITE_NAME, - bottomnav=bottomnav_html(active), - toasts=flash_toasts(), - close_icon=icon("close"), - app_js=render_app_js(), - page_js=js, - ) - - -# ------------------------------------------------------------------- navigation -def _unread_and_user(username): - """Один проход по БД: непрочитанные + данные пользователя + счётчик.""" - if not username: - return 0, 0, {} - with DB.read() as data: - return (count_unread_messages(data, username), - len(data.get("users", {})), - (data.get("users", {}) or {}).get(username, {})) - - -def sidebar_html(active=""): - username = g.get("username") - unread, user_count, u = _unread_and_user(username) - - links = [("home", "Latest", "/feed/latest", "sparkle"), - ("hot", "Hot", "/feed/hot", "fire")] - if username: - links += [("profile", "Profile", "/profile", "user"), - ("upload", "Upload", "/upload", "upload"), - ("messages", "Messages", "/messages", "mail"), - ("users", "Users", "/users", "users"), - ("wallet", "AduCoin", "/transactions", "coin")] - else: - links += [("users", "Users", "/users", "users")] - - items = [] - for key, label, href, ic in links: - badge = "" - if key == "messages" and unread: - badge = '%d' % unread - elif key == "users": - badge = '%d' % user_count - cls = "nav-link active" if active == key else "nav-link" - items.append('%s%s%s' - % (href, cls, icon(ic), label, badge)) - - items.append('%sNotifications' - % ("nav-link active" if active == "notifications" else "nav-link", icon("bell"))) - if username: - items.append('%sLogout' - % icon("logout")) - user_card = """ - - {avatar} - {name}{coin} - """.format(avatar=avatar_html(u, username, 44, online=True), - name=html.escape(username), - coin='%s %d' % (icon("coin"), (u or {}).get("aducoin", 0))) - else: - items.append('%sLogin' - % ("nav-link active" if active == "login" else "nav-link", icon("login"))) - items.append('%sRegister' - % ("nav-link active" if active == "register" else "nav-link", icon("plus"))) - user_card = ('' - '?' - 'GuestSign in to continue') - - return """ -""".format(logo=LOGO_URL, site=SITE_NAME, links="".join(items), user_card=user_card) - - -def topbar_html(active=""): - username = g.get("username") - unread, _, _ = _unread_and_user(username) - badge = '%d' % unread if unread else "" - if username: - right = ('%s%s' - '%s' - '' - % (icon("mail"), badge, icon("bell"), icon("menu"))) - else: - right = ('%s' - 'Login' - '' - % (icon("bell"), icon("menu"))) - return """ -
- - {site}{site} - - {right} -
""".format(menu=icon("menu"), logo=LOGO_URL, site=SITE_NAME, right=right) - - -def bottomnav_html(active=""): - if g.get("username"): - items = [("home", "/feed/latest", "home", "Home"), - ("hot", "/feed/hot", "fire", "Hot"), - ("upload", "/upload", "upload", "Upload"), - ("messages", "/messages", "mail", "Chats"), - ("profile", "/profile", "user", "Me")] - unread, _, _ = _unread_and_user(g.get("username")) - else: - items = [("home", "/feed/latest", "home", "Home"), - ("hot", "/feed/hot", "fire", "Hot"), - ("users", "/users", "users", "Users"), - ("login", "/login", "login", "Login"), - ("register", "/register", "plus", "Join")] - unread = 0 - links = [] - for key, href, ic, label in items: - badge = '%d' % unread if (key == "messages" and unread) else "" - cls = "active" if active == key else "" - links.append('%s%s%s' % (href, cls, icon(ic), label, badge)) - return '' % "".join(links) - - -def banners_html(): - """Баннер «Установить приложение» + «Включить уведомления».""" - out = [] - out.append(""" -""" % (icon("download"), SITE_NAME)) - if g.get("username") and PUSH_ENABLED: - out.append(""" -""" % icon("bell")) - return "".join(out) - - -APP_JS = r""" -(function () { - "use strict"; - var VAPID_KEY = __VAPID_KEY__; - var IS_LOGGED_IN = __LOGGED_IN__; - var PUSH_SUPPORTED = __PUSH_SUPPORTED__; - var deferredPrompt = null; - var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) || - (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1); - var isStandalone = window.matchMedia("(display-mode: standalone)").matches || - window.navigator.standalone === true; - var isTouch = window.matchMedia("(hover: none)").matches; - var reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; - - /* ============================================================ сайдбар */ - window.toggleSidebar = function () { - var sb = document.getElementById("sidebar"); - var scrim = document.getElementById("scrim"); - var open = sb.classList.toggle("open"); - if (scrim) scrim.classList.toggle("show", open); - document.body.style.overflow = open && window.innerWidth <= 900 ? "hidden" : ""; - }; - window.closeSidebar = function () { - var sb = document.getElementById("sidebar"); - var scrim = document.getElementById("scrim"); - if (sb) sb.classList.remove("open"); - if (scrim) scrim.classList.remove("show"); - document.body.style.overflow = ""; - }; - var scrimEl = document.getElementById("scrim"); - if (scrimEl) scrimEl.addEventListener("click", window.closeSidebar); - - /* ============================================================== тосты */ - function killToast(t) { - t.classList.add("out"); - setTimeout(function () { if (t.parentNode) t.parentNode.removeChild(t); }, 300); - } - setTimeout(function () { - document.querySelectorAll("#toasts .toast").forEach(function (t) { killToast(t); }); - }, 5200); - - window.toast = function (title, text, kind) { - var stack = document.getElementById("toasts"); - if (!stack) return; - var ic = { success: "check", error: "!", warning: "!", info: "i" }[kind || "info"] || "i"; - var el = document.createElement("div"); - el.className = "toast " + (kind || "info"); - el.setAttribute("role", "status"); - el.innerHTML = '' + ic + '
'; - el.querySelector("b").textContent = title; - el.querySelector("span:last-child").textContent = text || ""; - stack.appendChild(el); - setTimeout(function () { killToast(el); }, 5200); - }; - - /* ============================================================= модалки */ - window.openModal = function (id) { - var m = document.getElementById(id); - if (m) { m.classList.add("open"); document.body.style.overflow = "hidden"; } - }; - window.closeModal = function (id) { - var m = document.getElementById(id); - if (m) { m.classList.remove("open"); document.body.style.overflow = ""; } - }; - document.addEventListener("keydown", function (e) { - if (e.key === "Escape") { - ["imgModal", "installModal", "pushModal"].forEach(window.closeModal); - window.closeSidebar(); - } - }); - document.querySelectorAll(".modal").forEach(function (m) { - m.addEventListener("click", function (e) { if (e.target === m) window.closeModal(m.id); }); - }); - window.viewImage = function (src) { - var img = document.getElementById("imgModalImg"); - if (img) img.src = src; - window.openModal("imgModal"); - }; - - /* ============================================================ баннеры */ - window.dismissBanner = function (id) { - var el = document.getElementById(id); - if (el) el.classList.add("hidden"); - try { localStorage.setItem(id + "_dismissed", "1"); } catch (e) {} - }; - function bannerDismissed(id) { - try { return localStorage.getItem(id + "_dismissed") === "1"; } catch (e) { return false; } - } - - /* ================================================== service worker */ - if ("serviceWorker" in navigator) { - window.addEventListener("load", function () { - navigator.serviceWorker.register("/service-worker.js", { scope: "/" }) - .then(function (reg) { window.__swReg = reg; }) - .catch(function (err) { console.warn("SW registration failed", err); }); - }); - } - function swReady(timeoutMs) { - if (!("serviceWorker" in navigator)) return Promise.reject(new Error("no-service-worker")); - var ready = navigator.serviceWorker.ready; - if (!timeoutMs) return ready; - return new Promise(function (resolve, reject) { - var done = false; - var timer = setTimeout(function () { - if (!done) { done = true; reject(new Error("sw-timeout")); } - }, timeoutMs); - ready.then(function (reg) { - if (!done) { done = true; clearTimeout(timer); resolve(reg); } - }, function (err) { - if (!done) { done = true; clearTimeout(timer); reject(err); } - }); - }); - } - - /* =================================================== PWA install */ - window.addEventListener("beforeinstallprompt", function (e) { - e.preventDefault(); - deferredPrompt = e; - var b = document.getElementById("installBanner"); - if (b && !bannerDismissed("installBanner") && !isStandalone) b.classList.remove("hidden"); - }); - window.installPWA = function () { - if (deferredPrompt) { - deferredPrompt.prompt(); - deferredPrompt.userChoice.then(function (res) { - if (res && res.outcome === "accepted") { - var b = document.getElementById("installBanner"); - if (b) b.classList.add("hidden"); - } - deferredPrompt = null; - }); - } else { - window.openInstallModal(); - } - }; - function step(title, text) { - return '
' + (window.__stepN = (window.__stepN || 0) + 1) + - '' + title + "" + text + "
"; - } - window.openInstallModal = function () { - window.__stepN = 0; - var body = document.getElementById("installBody"); - var title = document.getElementById("installTitle"); - if (!body) return; - var siteName = document.title.replace(/\s*-\s*.*$/, ""); - if (isStandalone) { - title.textContent = "App installed"; - body.innerHTML = '

You are already running ' + - siteName + " as an installed app. Enjoy the full-screen experience!

"; - } else if (isIOS) { - title.textContent = "Install on iPhone / iPad"; - body.innerHTML = - '

On iOS the app is added from Safari — it takes 10 seconds:

' + - '
' + - step("Tap the Share button", "Safari toolbar at the bottom (iPhone) or top (iPad): a square with an arrow pointing up.") + - step("Choose Add to Home Screen", "Scroll the share sheet, tap Add to Home Screen, then confirm with Add.") + - step("Open " + siteName + " from the Home Screen", "It launches full-screen, like a native app, with no browser bars.") + - "
" + - '
' + - "Push notifications on iPhone require iOS 16.4 or newer and the app installed to the Home Screen. " + - "No Share button? Make sure the site is open in Safari.
"; - } else { - title.textContent = "Install app"; - body.innerHTML = - '

Install for a faster, full-screen, offline-ready experience:

' + - '
' + - step("Tap Install below", "Your browser may ask for confirmation — approve it.") + - step("Or use the browser menu", "Chrome / Edge: menu → Install app. Firefox: menu → Install.") + - step("Launch from desktop or app drawer", "The app runs in its own window and keeps working offline.") + - "
" + - '"; - } - window.openModal("installModal"); - }; - - /* ================================================ push-уведомления */ - function urlB64ToUint8Array(b64) { - if (!b64) throw new Error("no-vapid-key"); - var pad = "=".repeat((4 - b64.length % 4) % 4); - var s = (b64 + pad).replace(/-/g, "+").replace(/_/g, "/"); - var raw = window.atob(s), out = new Uint8Array(raw.length); - for (var i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i); - return out; - } - function pushManagerAvailable() { - return "PushManager" in window && "serviceWorker" in navigator && - "Notification" in window && !!VAPID_KEY; - } - window.pushStatus = function () { - return fetch("/api/push/status", { credentials: "same-origin" }) - .then(function (r) { return r.json(); }) - .catch(function () { return null; }); - }; - function describePushProblem() { - if (!("serviceWorker" in navigator)) return "This browser does not support service workers."; - if (!("Notification" in window)) return "This browser does not support notifications."; - if (!("PushManager" in window)) { - if (isIOS) return "On iPhone, push works only in the installed app (iOS 16.4+). Add it to the Home Screen first."; - return "This browser does not support push notifications."; - } - if (!VAPID_KEY) return "Push is not configured on the server."; - return null; - } - function showPushModal(state) { - var body = document.getElementById("pushBody"); - if (!body) return; - var siteName = document.title.replace(/\s*-\s*.*$/, ""); - if (state === "denied") { - body.innerHTML = '

Notifications are blocked for this site. ' + - "To enable them, open your browser's site settings, allow notifications, then reload the page.

" + - (isIOS ? '

On iPhone: Settings → Notifications → ' + - siteName + " → Allow Notifications. The app must be installed to the Home Screen first.

" : ""); - } else { - body.innerHTML = '

' + (state || "Push is unavailable.") + "

" + - (isIOS ? '

iPhone: open the site in Safari, then ' + - "Share → Add to Home Screen, open the installed app and tap Enable again.

" : ""); - } - window.openModal("pushModal"); - } - window.showPushModal = showPushModal; - - window.subscribePush = function () { - if (!IS_LOGGED_IN) { window.location.href = "/login?next=/notifications"; return; } - var problem = describePushProblem(); - if (problem) { showPushModal(problem); return; } - if (Notification.permission === "denied") { showPushModal("denied"); return; } - swReady(15000).then(function (reg) { - if (!reg.pushManager) throw new Error(describePushProblem() || "no-push-manager"); - return reg.pushManager.subscribe({ - userVisibleOnly: true, - applicationServerKey: urlB64ToUint8Array(VAPID_KEY) - }); - }).then(function (sub) { - return fetch("/api/push/subscribe", { - method: "POST", credentials: "same-origin", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(sub.toJSON()) - }); - }).then(function (r) { return r.json(); }).then(function (res) { - if (res && res.ok) { - toast("Notifications enabled", "You will get alerts for messages and new videos.", "success"); - refreshPushUI(true); - } else { - toast("Could not enable", (res && res.error) || "Try again later.", "error"); - } - }).catch(function (err) { - console.warn("subscribe error", err); - var msg = err && err.message ? err.message : String(err); - if (msg === "sw-timeout") { - toast("Service worker not ready", "Reload the page and try again.", "error"); - } else if (typeof Notification !== "undefined" && Notification.permission === "denied") { - showPushModal("denied"); - } else { - showPushModal(msg); - } - }); - }; - - window.unsubscribePush = function () { - if (!IS_LOGGED_IN) return; - swReady(15000).then(function (reg) { return reg.pushManager.getSubscription(); }) - .then(function (sub) { - if (!sub) { refreshPushUI(false); return null; } - return fetch("/api/push/unsubscribe", { - method: "POST", credentials: "same-origin", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ endpoint: sub.endpoint }) - }).then(function (r) { return r.json(); }) - .then(function () { return sub.unsubscribe(); }); - }) - .then(function () { - toast("Notifications disabled", "You can enable them again at any time.", "info"); - refreshPushUI(false); - }) - .catch(function (e) { toast("Error", String(e && e.message ? e.message : e), "error"); }); - }; - - window.testPush = function () { - fetch("/api/push/test", { method: "POST", credentials: "same-origin" }) - .then(function (r) { return r.json(); }) - .then(function (res) { - toast(res.ok ? "Test sent" : "Nothing sent", - res.ok ? "Check your notifications." : (res.error || "Subscribe first."), - res.ok ? "success" : "warning"); - }); - }; - - function refreshPushUI(on) { - if (on) { - var pb = document.getElementById("pushBanner"); - if (pb) pb.classList.add("hidden"); - } - document.querySelectorAll("[data-push-state]").forEach(function (el) { - el.textContent = on ? "Disable notifications" : "Enable notifications"; - el.setAttribute("data-push-state", on ? "on" : "off"); - el.onclick = on ? window.unsubscribePush : window.subscribePush; - }); - var badge = document.getElementById("pushStateBadge"); - if (badge) { - badge.className = "badge " + (on ? "green" : "muted"); - badge.textContent = on ? "Subscribed" : "Not subscribed"; - } - } - - /* ======================================== превью видео: длительность */ - function fmtDur(sec) { - sec = Math.round(sec || 0); - var m = Math.floor(sec / 60), s = sec % 60; - return m + ":" + (s < 10 ? "0" : "") + s; - } - document.querySelectorAll("video.story-preview").forEach(function (v) { - var card = v.closest(".story-card"); - var dur = card ? card.querySelector("[data-dur]") : null; - function showDur() { - if (dur && v.duration && isFinite(v.duration)) { - dur.textContent = fmtDur(v.duration); - dur.classList.add("show"); - } - } - if (v.readyState >= 1) showDur(); - v.addEventListener("loadedmetadata", showDur); - v.addEventListener("durationchange", showDur); - - if (!card || isTouch) return; - card.addEventListener("mouseenter", function () { - v.play().then(function () { card.classList.add("playing"); }).catch(function () {}); - }); - card.addEventListener("mouseleave", function () { - v.pause(); - try { v.currentTime = 0; } catch (e) {} - card.classList.remove("playing"); - }); - }); - - /* мобильные: автопревью видимых карточек */ - if (isTouch && "IntersectionObserver" in window) { - var visObserver = new IntersectionObserver(function (entries) { - entries.forEach(function (en) { - var card = en.target; - var v = card.querySelector("video.story-preview"); - if (!v) return; - if (en.isIntersecting && en.intersectionRatio > 0.6) { - v.play().then(function () { card.classList.add("playing"); }).catch(function () {}); - } else { - v.pause(); - card.classList.remove("playing"); - } - }); - }, { threshold: [0, 0.6, 1] }); - document.querySelectorAll(".story-card").forEach(function (c) { visObserver.observe(c); }); - } - - /* лайтбокс для фото в ленте (мобильные) */ - document.querySelectorAll(".story-card .thumb img").forEach(function (img) { - img.addEventListener("click", function (e) { - if (isTouch) { e.preventDefault(); window.viewImage(img.src); } - }); - }); - - /* ============================================== reveal + ripple */ - if (!reduceMotion && "IntersectionObserver" in window) { - var revealObs = new IntersectionObserver(function (entries) { - entries.forEach(function (en) { - if (en.isIntersecting) { - var el = en.target; - var delay = Math.min(parseInt(el.getAttribute("data-delay") || "0", 10), 240); - setTimeout(function () { el.classList.add("in"); }, delay); - revealObs.unobserve(el); - } - }); - }, { rootMargin: "0px 0px -8% 0px", threshold: .06 }); - document.querySelectorAll(".reveal").forEach(function (el) { revealObs.observe(el); }); - } else { - document.querySelectorAll(".reveal").forEach(function (el) { el.classList.add("in"); }); - } - - document.querySelectorAll(".btn, .chip, .icon-btn").forEach(function (el) { - el.addEventListener("pointerdown", function (e) { - if (reduceMotion) return; - var r = el.getBoundingClientRect(); - var size = Math.max(r.width, r.height); - var span = document.createElement("span"); - span.className = "ripple"; - span.style.width = span.style.height = size + "px"; - span.style.left = (e.clientX - r.left - size / 2) + "px"; - span.style.top = (e.clientY - r.top - size / 2) + "px"; - el.appendChild(span); - setTimeout(function () { if (span.parentNode) span.parentNode.removeChild(span); }, 620); - }); - }); - - /* ============================================== авто-рост текстареа */ - document.querySelectorAll("textarea[data-autogrow]").forEach(function (ta) { - function grow() { - ta.style.height = "auto"; - ta.style.height = Math.min(ta.scrollHeight, 160) + "px"; - } - ta.addEventListener("input", grow); - grow(); - }); - - /* ============================================== действия с историями */ - window.postJSON = function (url, payload) { - return fetch(url, { - method: "POST", credentials: "same-origin", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload || {}) - }).then(function (r) { return r.json(); }); - }; - - window.likeStory = function (storyId, btn) { - fetch("/like/" + storyId, { method: "POST", credentials: "same-origin" }) - .then(function (r) { return r.json(); }) - .then(function (d) { - if (d.error) { window.location.href = "/login"; return; } - var c = btn.querySelector(".like-count"); - if (c) c.textContent = d.likes; - btn.classList.toggle("liked", !!d.liked); - if (d.liked) { - btn.classList.add("pulsing"); - setTimeout(function () { btn.classList.remove("pulsing"); }, 430); - } - }) - .catch(function () {}); - }; - - window.jerkOff = function (storyId, btn) { - fetch("/jerk_off/" + storyId, { method: "POST", credentials: "same-origin" }) - .then(function (r) { return r.json(); }) - .then(function (d) { - var c = btn.querySelector(".jerk-count"); - if (c) c.textContent = d.jerked_off_count; - btn.classList.add("pulsing"); - setTimeout(function () { btn.classList.remove("pulsing"); }, 430); - }) - .catch(function () {}); - }; - - window.shareStory = function (title, url) { - if (navigator.share) { - navigator.share({ title: title, url: url }).catch(function () {}); - } else if (navigator.clipboard) { - navigator.clipboard.writeText(url).then(function () { - toast("Link copied", "Story link copied to clipboard.", "success"); - }); - } else { - prompt("Copy link:", url); - } - }; - - window.copyText = function (text, okMsg) { - function done() { toast("Copied", okMsg || "Copied to clipboard.", "success"); } - if (navigator.clipboard) { - navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text, done); }); - } else { - fallbackCopy(text, done); - } - }; - function fallbackCopy(text, done) { - var ta = document.createElement("textarea"); - ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0"; - document.body.appendChild(ta); ta.select(); - try { document.execCommand("copy"); done(); } catch (e) {} - document.body.removeChild(ta); - } - - /* ============================================== загрузка файла (upload) */ - var dz = document.getElementById("dropzone"); - if (dz) { - var input = document.getElementById("fileInput"); - var nameEl = document.getElementById("fileName"); - ["dragenter", "dragover"].forEach(function (ev) { - dz.addEventListener(ev, function (e) { e.preventDefault(); dz.classList.add("drag"); }); - }); - ["dragleave", "drop"].forEach(function (ev) { - dz.addEventListener(ev, function (e) { e.preventDefault(); dz.classList.remove("drag"); }); - }); - dz.addEventListener("drop", function (e) { - if (e.dataTransfer && e.dataTransfer.files.length && input) { - input.files = e.dataTransfer.files; - if (nameEl) nameEl.textContent = e.dataTransfer.files[0].name; - } - }); - dz.addEventListener("click", function () { if (input) input.click(); }); - if (input) { - input.addEventListener("change", function () { - if (nameEl) nameEl.textContent = input.files.length ? input.files[0].name : ""; - }); - } - var form = document.getElementById("uploadForm"); - if (form) { - form.addEventListener("submit", function () { - var btn = form.querySelector("button[type=submit]"); - var bar = document.getElementById("upBar"); - if (btn) { btn.disabled = true; btn.innerHTML = "Uploading…"; } - if (bar) { - bar.style.width = "12%"; - setTimeout(function () { bar.style.width = "68%"; }, 400); - setTimeout(function () { bar.style.width = "92%"; }, 1600); - } - }); - } - } - - /* ============================================== чат: прокрутка и Enter */ - var list = document.getElementById("msgList"); - if (list) list.scrollTop = list.scrollHeight; - var msgInput = document.getElementById("msgInput"); - if (msgInput) { - msgInput.addEventListener("keydown", function (e) { - if (e.key === "Enter" && !e.shiftKey) { - e.preventDefault(); - var form = document.getElementById("msgForm"); - if (form) form.requestSubmit ? form.requestSubmit() : form.submit(); - } - }); - } - - /* ============================================== счётчики в профиле */ - document.querySelectorAll("[data-count]").forEach(function (el) { - var target = parseInt(el.getAttribute("data-count"), 10) || 0; - if (reduceMotion) { el.textContent = target; return; } - var start = performance.now(), dur = 700; - function tick(now) { - var p = Math.min(1, (now - start) / dur); - var eased = 1 - Math.pow(1 - p, 3); - el.textContent = Math.round(target * eased).toLocaleString("en-US"); - if (p < 1) requestAnimationFrame(tick); - } - requestAnimationFrame(tick); - }); - - /* ============================================== кнопка «наверх» */ - var toTop = document.getElementById("toTop"); - if (toTop) { - var onScroll = function () { - toTop.classList.toggle("show", window.scrollY > 640); - }; - window.addEventListener("scroll", onScroll, { passive: true }); - onScroll(); - } - - /* ============================================== старт */ - document.addEventListener("DOMContentLoaded", function () { - if (!isStandalone) { - var b = document.getElementById("installBanner"); - if (b && !bannerDismissed("installBanner") && (isIOS || deferredPrompt)) b.classList.remove("hidden"); - } - if (IS_LOGGED_IN && PUSH_SUPPORTED && "Notification" in window && - Notification.permission === "default" && !bannerDismissed("pushBanner")) { - var pb = document.getElementById("pushBanner"); - if (pb) pb.classList.remove("hidden"); - } - if (IS_LOGGED_IN && PUSH_SUPPORTED) { - window.pushStatus().then(function (st) { - if (st && st.subscribed) refreshPushUI(true); - }); - } - }); -})(); -""" - - -# =================================================================== PWA layer -def render_app_js(): - key = VAPID.public_b64 if VAPID else "" - logged = "true" if g.get("username") else "false" - push_supported = "true" if PUSH_ENABLED else "false" - return (APP_JS.replace("__VAPID_KEY__", json.dumps(key)) - .replace("__PUSH_SUPPORTED__", push_supported) - .replace("__LOGGED_IN__", logged)) - - -@app.route("/manifest.json") -def manifest(): - start_url = "/?source=pwa" - man = { - "name": "%s — Stories & Coins" % SITE_NAME, - "short_name": SITE_NAME, - "description": "Discover stories, chat with members and earn AduCoin.", - "id": "/", - "start_url": start_url, - "scope": "/", - "display": "standalone", - "display_override": ["standalone", "fullscreen", "minimal-ui"], - "orientation": "portrait", - "background_color": "#07060d", - "theme_color": "#07060d", - "lang": "en", - "dir": "ltr", - "categories": ["social", "entertainment", "video"], - "prefer_related_applications": False, - "icons": [ - {"src": "/pwa/icon-192.png", "sizes": "192x192", "type": "image/png", - "purpose": "any"}, - {"src": "/pwa/icon-512.png", "sizes": "512x512", "type": "image/png", - "purpose": "any"}, - {"src": "/pwa/icon-maskable-192.png", "sizes": "192x192", "type": "image/png", - "purpose": "maskable"}, - {"src": "/pwa/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", - "purpose": "maskable"}, - ], - "shortcuts": [ - {"name": "Latest", "url": "/feed/latest", "icons": [{"src": "/pwa/icon-192.png", "sizes": "192x192"}]}, - {"name": "Hot", "url": "/feed/hot", "icons": [{"src": "/pwa/icon-192.png", "sizes": "192x192"}]}, - {"name": "Upload", "url": "/upload", "icons": [{"src": "/pwa/icon-192.png", "sizes": "192x192"}]}, - {"name": "Messages", "url": "/messages", "icons": [{"src": "/pwa/icon-192.png", "sizes": "192x192"}]}, - ], - } - resp = jsonify(man) - resp.headers["Cache-Control"] = "public, max-age=3600" - return resp - - -@app.route("/pwa/icon-.png") -def pwa_icon(size): - size = 192 if size not in (192, 512) else size - return Response(get_icon("any", size), mimetype="image/png", - headers={"Cache-Control": "public, max-age=604800, immutable"}) - - -@app.route("/pwa/icon-maskable-.png") -def pwa_icon_maskable(size): - size = 192 if size not in (192, 512) else size - return Response(get_icon("maskable", size), mimetype="image/png", - headers={"Cache-Control": "public, max-age=604800, immutable"}) - - -@app.route("/pwa/apple-touch-icon.png") -def pwa_apple_icon(): - return Response(get_icon("any", 180), mimetype="image/png", - headers={"Cache-Control": "public, max-age=604800, immutable"}) - - -@app.route("/pwa/badge.png") -def pwa_badge(): - return Response(get_icon("badge", 96), mimetype="image/png", - headers={"Cache-Control": "public, max-age=604800, immutable"}) - - -SERVICE_WORKER_JS = r""" -/* Adusis service worker: offline shell + push notifications */ -var CACHE = "adusis-v3"; -var SHELL = ["/", "/offline", "/manifest.json", "/pwa/icon-192.png", "/pwa/badge.png"]; - -self.addEventListener("install", function (event) { - event.waitUntil( - caches.open(CACHE).then(function (cache) { return cache.addAll(SHELL); }) - .then(function () { return self.skipWaiting(); }) - .catch(function () {}) - ); -}); - -self.addEventListener("activate", function (event) { - event.waitUntil( - caches.keys().then(function (keys) { - return Promise.all(keys.map(function (k) { return k === CACHE ? null : caches.delete(k); })); - }).then(function () { return self.clients.claim(); }) - ); -}); - -self.addEventListener("message", function (event) { - if (event.data === "skipWaiting") self.skipWaiting(); -}); - -self.addEventListener("fetch", function (event) { - var req = event.request; - if (req.method !== "GET") return; - - var url = new URL(req.url); - - // навигация: network-first, затем кэш, затем офлайн-страница - if (req.mode === "navigate") { - event.respondWith( - fetch(req).then(function (resp) { - var copy = resp.clone(); - caches.open(CACHE).then(function (c) { c.put(req, copy); }); - return resp; - }).catch(function () { - return caches.match(req).then(function (r) { - return r || caches.match("/offline") || new Response( - "

Offline

Reconnect to continue browsing.

", - { status: 200, headers: { "Content-Type": "text/html; charset=utf-8" } }); - }); - }) - ); - return; - } - - // медиа с Hugging Face: cache-first + фоновое обновление - if (url.hostname.indexOf("huggingface.co") !== -1) { - event.respondWith( - caches.match(req).then(function (cached) { - var network = fetch(req).then(function (resp) { - if (resp && resp.status === 200) { - var copy = resp.clone(); - caches.open(CACHE).then(function (c) { c.put(req, copy); }); - } - return resp; - }).catch(function () { return cached; }); - return cached || network; - }) - ); - return; - } - - // картинки и статика: cache-first с фоновым обновлением - var isImage = req.destination === "image" || - /\.(png|jpe?g|gif|webp|svg|ico|mp4|webm)(\?|$)/i.test(url.pathname); - if (isImage || url.pathname.indexOf("/pwa/") === 0 || - url.pathname === "/manifest.json" || url.pathname === "/service-worker.js") { - event.respondWith( - caches.match(req).then(function (cached) { - var network = fetch(req).then(function (resp) { - if (resp && (resp.status === 200 || resp.type === "opaque")) { - var copy = resp.clone(); - caches.open(CACHE).then(function (c) { c.put(req, copy); }); - } - return resp; - }).catch(function () { return cached; }); - return cached || network; - }) - ); - } -}); - -/* ------------------------- push ------------------------- */ -self.addEventListener("push", function (event) { - var data = {}; - try { data = event.data ? event.data.json() : {}; } catch (e) { - try { data = { title: "New update", body: event.data.text() }; } catch (e2) {} - } - var title = data.title || SITE_TITLE_PLACEHOLDER; - var options = { - body: data.body || "Open the app to see what is new.", - icon: "/pwa/icon-192.png", - badge: "/pwa/badge.png", - tag: data.tag || ("adusis-" + Date.now()), - renotify: true, - vibrate: [120, 60, 120], - data: { url: data.url || "/" }, - actions: [ - { action: "open", title: "Open" }, - { action: "dismiss", title: "Dismiss" } - ] - }; - event.waitUntil( - self.registration.showNotification(title, options).catch(function () {}) - ); -}); - -self.addEventListener("notificationclick", function (event) { - event.notification.close(); - if (event.action === "dismiss") return; - var target = (event.notification.data && event.notification.data.url) || "/"; - event.waitUntil( - self.clients.matchAll({ type: "window", includeUncontrolled: true }).then(function (clients) { - for (var i = 0; i < clients.length; i++) { - var c = clients[i]; - if (c.url.indexOf(target) !== -1 && "focus" in c) return c.focus(); - } - if (self.clients.openWindow) return self.clients.openWindow(target); - }) - ); -}); - -self.addEventListener("pushsubscriptionchange", function (event) { - event.waitUntil( - self.registration.pushManager.subscribe({ - userVisibleOnly: true, - applicationServerKey: VAPID_KEY_PLACEHOLDER - }).then(function (sub) { - return fetch("/api/push/subscribe", { - method: "POST", - credentials: "same-origin", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(sub.toJSON ? sub.toJSON() : sub) - }); - }).catch(function () {}) - ); -}); -""" - - -@app.route("/service-worker.js") -def service_worker(): - js = SERVICE_WORKER_JS - js = js.replace("SITE_TITLE_PLACEHOLDER", json.dumps(SITE_NAME)) - key = VAPID.public_b64 if VAPID else "" - js = js.replace("VAPID_KEY_PLACEHOLDER", json.dumps(key)) - resp = Response(js, mimetype="application/javascript") - resp.headers["Service-Worker-Allowed"] = "/" - resp.headers["Cache-Control"] = "no-cache" - return resp - - -@app.route("/offline") -def offline_page(): - body = """ -
-
-
-
%s
-

You are offline

-

Check your connection — cached stories will open again once you are back online.

- Try again -
-
-
""" % icon("rocket") - return page_html("Offline — %s" % SITE_NAME, - "You are currently offline.", - body, path="/offline", noindex=True) - - -# ====================================================================== SEO -@app.route("/demo-avatar/.png") -def demo_avatar(seed): - """Сгенерированный аватар (демо-данные / пользователи без фото).""" - return Response(_make_avatar_png(seed or "a"), mimetype="image/png", - headers={"Cache-Control": "public, max-age=86400"}) - - -@app.route("/demo-media/.png") -def demo_media(seed): - """Сгенерированное превью для демо-историй.""" - return Response(_make_demo_media_png(seed or "demo", 720, 900), mimetype="image/png", - headers={"Cache-Control": "public, max-age=86400"}) - - -@app.route("/robots.txt") -def robots_txt(): - lines = [ - "User-agent: *", - "Allow: /", - "Disallow: /messages", - "Disallow: /profile", - "Disallow: /upload", - "Disallow: /transactions", - "Disallow: /notifications", - "Disallow: /api/", - "Disallow: /search?", - "Clean-param: source /", - "", - "Sitemap: %s/sitemap.xml" % abs_url(""), - ] - return Response("\n".join(lines) + "\n", mimetype="text/plain") - - -def _sitemap_url(loc, lastmod=None, changefreq="daily", priority="0.8", extras=""): - return ("%s%s%s%s%s" - % (loc, ("%s" % lastmod) if lastmod else "", - changefreq, priority, extras)) - - -@app.route("/sitemap.xml") -def sitemap_xml(): - now = datetime.now().strftime("%Y-%m-%d") - urls = [] - urls.append(_sitemap_url(abs_url("/feed/latest"), now, "hourly", "1.0")) - urls.append(_sitemap_url(abs_url("/feed/hot"), now, "hourly", "0.9")) - urls.append(_sitemap_url(abs_url("/users"), now, "daily", "0.7")) - - try: - with DB.read() as data: - stories = sorted(data.get("posts", []), - key=lambda p: str(p.get("upload_date", "")), reverse=True) - for p in stories[:20000]: - sid = p.get("id") - if not sid: - continue - loc = abs_url("/story/%s" % sid) - lastmod = str(p.get("upload_date", ""))[:10] or None - title = html.escape(p.get("title", "Untitled")) - desc = html.escape((p.get("description") or p.get("title") or "")[:4000]) - murl = media_url(p.get("filename", ""), p.get("type", "photo")) - if p.get("type") == "video": - extras = ( - "" - "%s" - "%s" - "%s" - "%s" - "%s" - "no" - "" % (LOGO_URL, title, desc, murl, lastmod or now) - ) - else: - extras = ("%s%s" - "%s" % (murl, title, desc)) - urls.append(_sitemap_url(loc, lastmod, "weekly", "0.8", extras)) - - usernames = sorted((data.get("users") or {}).keys())[:20000] - for u in usernames: - urls.append(_sitemap_url(abs_url("/user/%s" % u), None, "weekly", "0.6")) - except Exception as e: - log.warning("Sitemap generation error: %s", e) - - xml = ('\n' - '%s' - % "".join(urls)) - resp = Response(xml, mimetype="application/xml") - resp.headers["Cache-Control"] = "public, max-age=1800" - return resp - - -# =================================================================== Push API -@app.route("/api/push/vapid") -def api_push_vapid(): - return jsonify({"enabled": PUSH_ENABLED, - "publicKey": VAPID.public_b64 if VAPID else ""}) - - -@app.route("/api/push/status") -def api_push_status(): - if not g.get("username"): - return jsonify({"logged_in": False, "supported": PUSH_ENABLED, - "subscribed": False, "permission": "default"}) - subscribed = False - settings = {"notify_messages": True, "notify_videos": True} - try: - with DB.read() as data: - subscribed = bool(get_subscriptions(data, g.username)) - u = (data.get("users", {}).get(g.username) or {}) - settings["notify_messages"] = bool(u.get("notify_messages", True)) - settings["notify_videos"] = bool(u.get("notify_videos", True)) - except Exception: - pass - return jsonify({ - "logged_in": True, - "supported": PUSH_ENABLED, - "subscribed": subscribed, - "permission": "default", - "settings": settings, - }) - - -@app.route("/api/push/subscribe", methods=["POST"]) -def api_push_subscribe(): - if not g.get("username"): - return jsonify({"ok": False, "error": "login required"}), 401 - if not PUSH_ENABLED: - return jsonify({"ok": False, "error": "push disabled on server"}), 503 - payload = request.get_json(silent=True) or {} - endpoint = payload.get("endpoint") - keys = payload.get("keys") or {} - if not endpoint or not keys.get("p256dh") or not keys.get("auth"): - return jsonify({"ok": False, "error": "invalid subscription"}), 400 - username = g.username - - def _fn(data): - save_subscription(data, username, payload) - DB.mutate(_fn, wait=True) - log.info("Push subscription stored for %s", username) - return jsonify({"ok": True}) - - -@app.route("/api/push/unsubscribe", methods=["POST"]) -def api_push_unsubscribe(): - if not g.get("username"): - return jsonify({"ok": False, "error": "login required"}), 401 - payload = request.get_json(silent=True) or {} - endpoint = payload.get("endpoint") - username = g.username - - def _fn(data): - if endpoint: - remove_subscription(data, username, endpoint) - else: - data.setdefault("push_subscriptions", {})[username] = [] - DB.mutate(_fn, wait=True) - return jsonify({"ok": True}) - - -@app.route("/api/push/settings", methods=["POST"]) -def api_push_settings(): - if not g.get("username"): - return jsonify({"ok": False, "error": "login required"}), 401 - payload = request.get_json(silent=True) or {} - username = g.username - - def _fn(data): - u = data.get("users", {}).get(username) - if isinstance(u, dict): - if "notify_messages" in payload: - u["notify_messages"] = bool(payload["notify_messages"]) - if "notify_videos" in payload: - u["notify_videos"] = bool(payload["notify_videos"]) - DB.mutate(_fn, wait=True) - return jsonify({"ok": True}) - - -@app.route("/api/push/test", methods=["POST"]) -def api_push_test(): - if not g.get("username"): - return jsonify({"ok": False, "error": "login required"}), 401 - if not PUSH_ENABLED: - return jsonify({"ok": False, "error": "push disabled on server"}), 503 - with DB.read() as data: - if not get_subscriptions(data, g.username): - return jsonify({"ok": False, "error": "not subscribed"}), 400 - NOTIFIER.push_test(g.username) - return jsonify({"ok": True}) - - -@app.route("/healthz") -def healthz(): - h = DB.health() - h.update({"push": PUSH_ENABLED, "hf": not HF_DISABLED, "ok": True}) - return jsonify(h) - - -# ==================================================================== pages -PAGE_CSS_AUTH = """ -.auth .form-side .sub{color:var(--text2);font-size:.92rem;margin-bottom:22px} -.auth .form-side form{margin-top:6px} -""" - - -@app.route("/register", methods=["GET", "POST"]) -def register(): - referral_code = request.args.get("ref", "").strip() or request.form.get("referral_code", "").strip() - - if request.method == "POST": - username = (request.form.get("username") or "").strip() - password = request.form.get("password") or "" - role = request.form.get("role") or "" - ref_code_used = (request.form.get("referral_code") or "").strip() - - if not username or not password or not role: - flash("Username, password and role are required.", "error") - return redirect(url_for("register", ref=ref_code_used)) - if len(username) < 3: - flash("Username must be at least 3 characters.", "error") - return redirect(url_for("register", ref=ref_code_used)) - if not re.fullmatch(r"[A-Za-z0-9_.\-]+", username): - flash("Username may contain letters, digits, dot, dash and underscore only.", "error") - return redirect(url_for("register", ref=ref_code_used)) - if len(password) < MIN_PASSWORD_LEN: - flash("Password must be at least %d characters." % MIN_PASSWORD_LEN, "error") - return redirect(url_for("register", ref=ref_code_used)) - if role not in USER_ROLES: - flash("Invalid role selected.", "error") - return redirect(url_for("register", ref=ref_code_used)) - - referrer_username, reward = None, 0 - try: - with DB.read() as data: - if username in data.get("users", {}): - flash("Username already exists — choose another.", "error") - return redirect(url_for("register", ref=ref_code_used)) - if ref_code_used: - for r_user, r_data in data.get("users", {}).items(): - if isinstance(r_data, dict) and r_data.get("referral_code") == ref_code_used: - referrer_username = r_user - break - if not referrer_username: - flash("Invalid referral code.", "warning") - else: - reward = REFERRAL_REWARDS.get(role, DEFAULT_REWARD) - new_ref = generate_unique_referral_code(data) - - def _create(d): - d.setdefault("users", {})[username] = { - "password": hash_password(password), - "role": role, "bio": "", "link": "", "avatar": None, - "aducoin": 0, "referral_code": new_ref, - "referred_by": referrer_username, - "last_seen": now_str(), - "notify_messages": True, "notify_videos": True, - "remember_tokens": [], - } - if referrer_username and reward > 0 and referrer_username in d["users"]: - d["users"][referrer_username]["aducoin"] = \ - d["users"][referrer_username].get("aducoin", 0) + reward - log_transaction(d, referrer_username, "earn_referral", reward, - "Referral reward for inviting '%s' (%s)" % (username, role), - related_user=username) - with DB.write(wait=True) as d: - if username in d.get("users", {}): - flash("Username already exists — choose another.", "error") - return redirect(url_for("register", ref=ref_code_used)) - _create(d) - except Exception as e: - log.error("Registration failed: %s", e, exc_info=True) - flash("Registration failed — please try again.", "error") - return redirect(url_for("register", ref=ref_code_used)) - - flash("Welcome to %s, %s! Please log in." % (SITE_NAME, username), "success") - if referrer_username and reward > 0: - flash("Your referrer %s received %d AduCoin!" % (referrer_username, reward), "success") - return redirect(url_for("login")) - - with DB.read() as data: - user_count = len(data.get("users", {})) - body = """ -
-
- %(site)s%(site)sstories & coins -
-

Join the community

-

Stories worth
sharing — and
coins worth earning.

-
-
%(sparkle)s Publish photos & videos with instant previews
-
%(coin_icon)s Earn AduCoin for uploads, views and invites
-
%(bell_icon)s Push notifications for messages and new stories
-
%(phone_icon)s Installable app — works full-screen and offline
-
-
-

Free forever · no email required · your data stays yours

-
-
-

Create account

-

Join %(site)s and start earning AduCoin

- %(ref_html)s -
-
- - -
-
- - -
-
- -
- %(roles)s -
-
- - -
-

Already a member? Log in

-
-
""" % { - "logo": LOGO_URL, - "site": SITE_NAME, - "sparkle": icon("sparkle"), "coin_icon": icon("coin"), - "bell_icon": icon("bell"), "phone_icon": icon("phone"), - "ref_html": ('
%s Referral code %s applied — your inviter gets a bonus!
' - % (icon("gift"), html.escape(referral_code)) if referral_code else ""), - "minlen": MIN_PASSWORD_LEN, - "roles": "".join( - '" % (html.escape(r), html.escape(r.title())) - for r in USER_ROLES), - "u_val": html.escape(request.form.get("username", "")), - "ref": html.escape(referral_code), - "login_url": url_for("login"), - } - return page_html("Register — %s" % SITE_NAME, - "Create a free %s account: share stories, chat and earn AduCoin." % SITE_NAME, - body, path="/register", css=PAGE_CSS_AUTH, active="register") - - -@app.route("/login", methods=["GET", "POST"]) -def login(): - next_url = request.args.get("next") or request.form.get("next") or url_for("feed") - - if request.method == "POST": - username = (request.form.get("username") or "").strip() - password = request.form.get("password") or "" - remember = request.form.get("remember") == "on" - - if login_rate_limited(): - flash("Too many login attempts. Try again in a few minutes.", "error") - return redirect(url_for("login", next=next_url)) - - user_record, upgraded = None, False - with DB.read() as data: - u = (data.get("users", {}) or {}).get(username) - if isinstance(u, dict) and verify_password(u.get("password"), password): - user_record = u - if not _is_hashed(u.get("password")): - upgraded = True # legacy plaintext пароль — обновим на хеш - - if user_record is not None: - if upgraded: - def _upgrade(d): - if username in d.get("users", {}): - d["users"][username]["password"] = hash_password(password) - DB.mutate(_upgrade, wait=True) - log.info("Upgraded legacy password hash for %s", username) - clear_login_attempts() - session["username"] = username - session.permanent = True - token, expires = None, None - if remember: - def _tok(d): - return create_remember_token(d, username, request.headers.get("User-Agent", "")) - # wait=True: токен обязан попасть в базу ДО того, как уйдёт cookie - with DB.write(wait=True) as d: - token, expires = _tok(d) - DB.mutate(lambda d: d["users"][username].__setitem__("last_seen", now_str()) - if isinstance(d.get("users", {}).get(username), dict) else None, wait=False) - resp = redirect(safe_next(next_url)) - if token: - resp.set_cookie(REMEMBER_COOKIE, token, - max_age=int((expires - datetime.now()).total_seconds()), - httponly=True, samesite="Lax", - secure=app.config["SESSION_COOKIE_SECURE"], path="/") - flash("Welcome back, %s!" % username, "success") - return resp - - flash("Invalid username or password.", "error") - return redirect(url_for("login", next=next_url)) - - with DB.read() as data: - user_count = len(data.get("users", {})) - body = """ -
-
- %(site)s%(site)sstories & coins -
-

Welcome back

-

Your community,
your stories,
your coins.

-
-
%(sparkle)s Fresh stories from creators you follow
-
%(coin_icon)s Track your AduCoin balance and rewards
-
%(mail_icon)s Private messages with read receipts
-
%(phone_icon)s Installable, full-screen, offline-ready
-
-
-

Free forever · no email required · your data stays yours

-
-
-

Log in

-

Continue to %(site)s

-
- -
- - -
-
- - -
- - -
-

New here? Create an account

-
-
""" % {"logo": LOGO_URL, "site": SITE_NAME, "days": REMEMBER_DAYS, - "sparkle": icon("sparkle"), "coin_icon": icon("coin"), - "mail_icon": icon("mail"), "phone_icon": icon("phone"), - "next": html.escape(next_url), - "u_val": html.escape(request.form.get("username", "")), - "reg_url": url_for("register")} - return page_html("Login — %s" % SITE_NAME, - "Log in to %s to share stories, chat and earn AduCoin." % SITE_NAME, - body, path="/login", css=PAGE_CSS_AUTH, active="login") - - -def safe_next(target): - """Защита от open-redirect.""" - if not target: - return url_for("feed") - if target.startswith("/") and not target.startswith("//"): - return target - return url_for("feed") - - -@app.route("/logout") -def logout(): - username = session.get("username") - token = request.cookies.get(REMEMBER_COOKIE) - if username: - def _clean(d): - revoke_remember_token(d, username, token) - u = d.get("users", {}).get(username) - if isinstance(u, dict): - u["last_seen"] = now_str() - try: - DB.mutate(_clean, wait=False) - except Exception as e: - log.warning("Logout cleanup failed: %s", e) - session.pop("username", None) - flash("You have been logged out.", "success") - resp = redirect(url_for("login")) - resp.delete_cookie(REMEMBER_COOKIE, path="/") - return resp - - -# ------------------------------------------------------------------- feed -@app.route("/", endpoint="feed") -def index(): - return feed_page("latest") - - -@app.route("/feed/", endpoint="feed_mode") -def feed_page(mode="latest"): - if mode not in ("latest", "hot"): - mode = "latest" - with DB.read() as data: - posts = [p for p in data.get("posts", []) if isinstance(p, dict)] - users_lookup = {u: (d if isinstance(d, dict) else {}) - for u, d in (data.get("users") or {}).items()} - now = datetime.now() - processed = [] - for p in posts: - p = dict(p) # копия: служе��ные ключи не попадают в базу - p.setdefault("title", "Untitled") - p.setdefault("type", "photo") - p.setdefault("filename", "") - p.setdefault("uploader", "unknown") - p.setdefault("upload_date", "1970-01-01 00:00:00") - p.setdefault("likes", []) - p.setdefault("views", 0) - p.setdefault("comments", []) - p.setdefault("jerked_off_count", 0) - promoted = False - if p.get("promoted_until"): - try: - promoted = datetime.strptime(p["promoted_until"], TS_FMT) > now - except (ValueError, TypeError): - p["promoted_until"] = None - p["is_currently_promoted"] = promoted - p["_uploader_online"] = is_user_online(data, p.get("uploader")) - processed.append(p) - if mode == "hot": - def hot_score(p): - return (len(p.get("likes", []) or []) * 3 - + p.get("jerked_off_count", 0) * 2 - + int(p.get("views", 0) / 10)) - stories = sorted(processed, - key=lambda p: (p["is_currently_promoted"], - hot_score(p), - str(p.get("upload_date", ""))), - reverse=True) - else: - stories = sorted(processed, key=lambda x: str(x.get("upload_date", "")), reverse=True) - - title = "Hot stories right now" if mode == "hot" else "Latest stories" - desc = ("Trending promoted stories on %s." % SITE_NAME if mode == "hot" - else "Fresh stories and videos shared by the %s community." % SITE_NAME) - jsonld = { - "@context": "https://schema.org", - "@type": "CollectionPage", - "name": "%s — %s" % (SITE_NAME, title), - "url": abs_url(request.path), - "isPartOf": {"@type": "WebSite", "name": SITE_NAME, "url": abs_url("/")}, - "mainEntity": { - "@type": "ItemList", - "numberOfItems": len(stories), - "itemListElement": [ - {"@type": "ListItem", "position": i + 1, - "url": abs_url("/story/%s" % s.get("id", "")), - "name": s.get("title", "Untitled")} - for i, s in enumerate(stories[:50]) - ], - }, - } - - chips = """ -""" % ("on" if mode == "latest" else "", icon("sparkle"), - "on" if mode == "hot" else "", icon("fire"), icon("search")) - - if stories: - cards = [] - for idx, s in enumerate(stories): - cards.append(story_card_html(s, users_lookup=users_lookup, - featured=(idx == 0 and len(stories) > 2), - reveal_delay=(min(idx, 8) * 55))) - grid = ('
%s
' % "".join(cards)) - else: - grid = empty_state( - "Nothing here yet" if mode == "latest" else "No hot stories right now", - ("Be the first to upload a story!" if mode == "latest" - else "Promote one of your stories to feature it here."), - "Upload a story" if (mode == "latest" and g.get("username")) else None, - url_for("upload") if (mode == "latest" and g.get("username")) else None, - art="upload" if mode == "latest" else "fire") - - body = """ -
-
-
-

%s

-

%s

-

%s

-
- %s -
- %s - %s -
""" % ( - ("Community feed" if mode == "latest" else "Trending now"), - ('%s' % html.escape(title.split()[0])) + " " + html.escape(" ".join(title.split()[1:])), - html.escape(desc), - ('%s Upload' % (url_for("upload"), icon("upload")) - if g.get("username") else 'Join to upload' % url_for("register")), - chips, - grid) - - return page_html("%s — %s" % (title, SITE_NAME), desc, body, - path=request.path, jsonld=jsonld, og_type="website", - active="home" if mode == "latest" else "hot") - - -# ------------------------------------------------------------------- search -@app.route("/search") -def search(): - q = (request.args.get("q") or "").strip().lower() - stories, users = [], [] - if q: - with DB.read() as data: - users_lookup = {u: (d if isinstance(d, dict) else {}) - for u, d in (data.get("users") or {}).items()} - for p in data.get("posts", []): - if not isinstance(p, dict): - continue - hay = " ".join(str(p.get(k, "")) for k in ("title", "description", "uploader")).lower() - if q in hay: - p = dict(p) - p.setdefault("type", "photo") - p["_uploader_online"] = is_user_online(data, p.get("uploader")) - stories.append(p) - stories.sort(key=lambda x: str(x.get("upload_date", "")), reverse=True) - for uname, udata in (data.get("users") or {}).items(): - if q in uname.lower(): - users.append({"name": uname, "data": udata if isinstance(udata, dict) else {}, - "online": is_user_online(data, uname)}) - - stories_html = "" - users_html = "" - if q: - if stories: - stories_html = ('

Stories (%d)

' % len(stories) + - '
%s
' - % "".join(story_card_html(s, users_lookup=users_lookup) - for s in stories[:60])) - else: - stories_html = empty_state("No stories found", "Try a different keyword.", - None, None, art="search") - if users: - users_html = ('

People (%d)

' % len(users) + - '
%s
' % "".join( - '%s' - '%s%s' - % (url_for("user_profile", username=u["name"]), - avatar_html(u["data"], u["name"], 54, online=u.get("online")), - html.escape(u["name"]), - html.escape(str(u["data"].get("role") or "member").title())) - for u in users[:40])) - else: - users_html = empty_state("No people found", "Try a different keyword.", - None, None, art="users") - - body = """ -
-

Search

-

Find stories and people on {site}

-
-
- - -
- -
- {stories} - {users} -
""".format(site=SITE_NAME, q=html.escape(q), icon=icon("search"), - stories=stories_html, users=users_html) - return page_html("Search — %s" % SITE_NAME, - "Search stories and members on %s." % SITE_NAME, - body, path="/search", noindex=True, active="home") - - -# ------------------------------------------------------------------- profile -PAGE_CSS_PROFILE = """ -.settings-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;align-items:start} -@media (max-width:900px){.settings-grid{grid-template-columns:1fr}} -.my-story{display:flex;gap:14px;align-items:center;padding:13px;border-radius:var(--r2); - background:var(--surface);border:1px solid var(--border);margin-bottom:10px;transition:border-color var(--fast)} -.my-story:hover{border-color:var(--border2)} -.my-story img,.my-story video{width:58px;height:58px;border-radius:var(--r1);object-fit:cover;flex:none} -.my-story .info{flex:1;min-width:0} -.my-story .info b{display:block;font-size:.92rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} -.my-story .info span{font-size:.78rem;color:var(--text3)} -.my-story .acts{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end} -""" - - -@app.route("/profile", methods=["GET", "POST"]) -@login_required -def profile(): - username = session["username"] - - if request.method == "POST": - # ---- удаление истории ---- - if "delete_story" in request.form: - story_id = request.form.get("story_id", "") - removed = [] - - def _del(d): - for p in d.get("posts", []): - if p.get("id") == story_id and p.get("uploader") == username: - removed.append(p) - d["posts"] = [p for p in d.get("posts", []) - if not (p.get("id") == story_id and p.get("uploader") == username)] - with DB.write(wait=True) as d: - _del(d) - if removed: - flash("Story deleted.", "success") - else: - flash("Story not found or no permission.", "error") - return redirect(url_for("profile")) - - # ---- продвижение ---- - if "promote_story" in request.form: - return _do_promote(username, request.form.get("story_id", "")) - - # ---- обновление профиля ---- - if "update_profile" in request.form: - bio = (request.form.get("bio") or "").strip()[:500] - link = (request.form.get("link") or "").strip()[:200] - role = request.form.get("role") or "" - avatar_file = request.files.get("avatar") - changed = False - avatar_path = None - - if role and role not in USER_ROLES: - flash("Invalid role selected.", "error") - return redirect(url_for("profile")) - - if avatar_file and avatar_file.filename: - if not allowed_file(avatar_file.filename, ALLOWED_IMAGE_EXT): - flash("Invalid avatar type (png, jpg, jpeg, gif).", "error") - return redirect(url_for("profile")) - ext = os.path.splitext(avatar_file.filename)[1].lower() - # случайный суффикс: имя всегда уникально, поэтому старый - # аватар корректно удаляется, а браузер не берёт кэш - fname = secure_filename("%s_avatar_%d_%d%s" - % (username, int(time.time()), random.randint(100, 999), ext)) - temp_path = os.path.join(UPLOAD_FOLDER, fname) - old_avatar = None - try: - avatar_file.save(temp_path) - if HF_DISABLED or not HF_AVAILABLE or not HF_TOKEN_WRITE: - raise RuntimeError("Hugging Face storage is not configured") - with DB.read() as d: - old_avatar = (d.get("users", {}).get(username) or {}).get("avatar") - api = HfApi() - api.upload_file( - path_or_fileobj=temp_path, path_in_repo="avatars/%s" % fname, - repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, - commit_message="Avatar update for %s" % username) - avatar_path = "avatars/%s" % fname - if old_avatar and old_avatar != avatar_path: - try: - api.delete_file(path_in_repo=old_avatar, repo_id=REPO_ID, - repo_type="dataset", token=HF_TOKEN_WRITE) - log.info("Deleted old avatar %s for %s", old_avatar, username) - except Exception as hf_del_e: - log.warning("Could not delete old avatar %s: %s", old_avatar, hf_del_e) - except Exception as e: - log.error("Avatar upload failed: %s", e) - flash("Avatar upload failed — check server storage config.", "error") - finally: - if os.path.exists(temp_path): - os.remove(temp_path) - - def _upd(d): - nonlocal changed - u = d.get("users", {}).get(username) - if not isinstance(u, dict): - return - if u.get("bio") != bio: - u["bio"] = bio; changed = True - if u.get("link") != link: - u["link"] = link; changed = True - if role and u.get("role") != role: - u["role"] = role; changed = True - if avatar_path: - u["avatar"] = avatar_path; changed = True - with DB.write(wait=True) as d: - _upd(d) - flash("Profile updated!" if changed else "No changes detected.", - "success" if changed else "warning") - return redirect(url_for("profile")) - - with DB.read() as data: - u = (data.get("users", {}) or {}).get(username, {}) - my_posts = [] - now = datetime.now() - for p in data.get("posts", []): - if not isinstance(p, dict) or p.get("uploader") != username: - continue - p = dict(p) # копия: служебные ключи не попадают в базу - promoted = False - if p.get("promoted_until"): - try: - promoted = datetime.strptime(p["promoted_until"], TS_FMT) > now - except (ValueError, TypeError): - pass - p["is_currently_promoted"] = promoted - my_posts.append(p) - my_posts.sort(key=lambda x: str(x.get("upload_date", "")), reverse=True) - txs = sorted([t for t in data.get("transactions", []) if t.get("user") == username], - key=lambda x: str(x.get("timestamp", "")), reverse=True)[:8] - user_count = len(data.get("users", {})) - - referral_code = u.get("referral_code", "") - referral_link = url_for("register", ref=referral_code, _external=True) if referral_code else "" - - _likes_total = sum(len(p.get("likes", []) or []) for p in my_posts) - _views_total = sum(int(p.get("views", 0) or 0) for p in my_posts) - _jerks_total = sum(int(p.get("jerked_off_count", 0) or 0) for p in my_posts) - - def _stat(value, label, ic): - return ('
0%s %s
' - % (int(value), icon(ic), label)) - - stats = ('
%s
' % "".join([ - _stat(len(my_posts), "Stories", "video"), - _stat(_likes_total, "Likes", "heart"), - _stat(_views_total, "Views", "eye"), - _stat(_jerks_total, "Reactions", "fire"), - _stat(u.get("aducoin", 0), "AduCoin", "coin"), - ])) - - stories_html = "" - if my_posts: - rows = [] - for p in my_posts: - rows.append(""" -
- - - %(title)s - %(meta)s - - - %(promote_btn)s -
- - - -
-
-
""" % { - "thumb": media_url(p.get("filename", ""), p.get("type", "photo")), - "href": url_for("story_page", story_id=p.get("id", "")), - "title": html.escape(p.get("title", "Untitled")), - "meta": "%s · %s likes · %s views%s" % ( - fmt_dt(p.get("upload_date", "")), - len(p.get("likes", []) or []), p.get("views", 0), - " · promoted until %s" % fmt_dt(p["promoted_until"]) if p.get("is_currently_promoted") else ""), - "sid": html.escape(p.get("id", "")), - "trash": icon("trash"), - "promote_btn": ( - '
' - '' - '' - '
' - % (html.escape(p.get("id", "")), icon("rocket"), PROMOTE_COST) - if not p.get("is_currently_promoted") else - '%s Promoted' % icon("fire")), - }) - stories_html = "".join(rows) - else: - stories_html = empty_state("No stories yet", "Upload your first story to start earning.", - "Upload story", url_for("upload"), art="upload") - - tx_html = "" - if txs: - items = "".join( - '
%s' - '%s%s' - '%+d
' - % ("pos" if t.get("amount", 0) > 0 else "neg", - "↗" if t.get("amount", 0) > 0 else "↘", - html.escape(str(t.get("type", "")).replace("_", " ").title()), - html.escape(str(t.get("description", ""))), - "pos" if t.get("amount", 0) > 0 else "neg", t.get("amount", 0)) - for t in txs) - tx_html = '
%s
' % items - else: - tx_html = empty_state("No transactions yet", "Earn AduCoin by uploading stories and getting views.", - None, None, art="coin") - - body = """ -
-
-
-
- %(avatar)s -
-

Your profile

-

%(name)s %(coin)s %(balance)d

-
- %(role_icon)s %(role)s - %(online)s - Joined via %(referred)s -
- -
-
-
- %(stats)s - -
-
-

%(settings_icon)s Edit profile

-
- -
-
-
-
-
-
-
-
- -
-
- -
-

%(gift_icon)s Referral program

-

Invite friends — you both win. You get AduCoin when someone registers with your code.

-
- %(ref_code)s - -
-

Rewards: white girl / couple / BBC alpha bull — 100 coins, white boy — 50 coins.

-

%(coin_icon)s Recent AduCoin activity

- %(tx)s - View full history -
-
- -

%(video_icon)s My stories (%(count)d)

- %(stories)s -
- -""" % { - "avatar": avatar_html(u, username, 132), - "name": html.escape(username), - "coin": icon("coin"), "balance": u.get("aducoin", 0), - "role": html.escape(str(u.get("role") or "member").title()), - "online": (' Online' if is_user_online({"users": {username: u}}, username) else "Offline"), - "referred": html.escape(str(u.get("referred_by") or "direct signup")), - "upload_icon": icon("upload"), "mail_icon": icon("mail"), - "bell_icon": icon("bell"), "settings_icon": icon("settings"), - "check_icon": icon("check"), "gift_icon": icon("gift"), - "coin_icon": icon("coin"), "video_icon": icon("video"), - "role_icon": icon("user"), "users_icon": icon("users"), - "copy_icon": icon("copy"), - "bio": html.escape(u.get("bio", "")), "link": html.escape(u.get("link", "")), - "roles": "".join('' - % (html.escape(r), "selected" if u.get("role") == r else "", html.escape(r.title())) - for r in USER_ROLES), - "ref_code": html.escape(referral_code or "—"), - "ref_link": html.escape(referral_link), - "tx": tx_html, "stories": stories_html, "count": len(my_posts), - "stats": stats, - } - - return page_html("%s's profile — %s" % (username, SITE_NAME), - "Profile of %s on %s: stories, AduCoin balance and referral link." - % (username, SITE_NAME), - body, path="/profile", noindex=True, - css=PAGE_CSS_PROFILE, active="profile") - - -def _do_promote(username, story_id): - ok, msg, kind = False, "", "error" - with DB.write(wait=True) as d: - u = d.get("users", {}).get(username) - story = next((p for p in d.get("posts", []) if p.get("id") == story_id), None) - if not isinstance(u, dict) or story is None: - msg, kind = "Story not found.", "error" - elif story.get("uploader") != username: - msg, kind = "You can only promote your own stories.", "error" - else: - if story.get("promoted_until"): - try: - if datetime.strptime(story["promoted_until"], TS_FMT) > datetime.now(): - msg, kind = "This story is already promoted.", "warning" - else: - story["promoted_until"] = None - except (ValueError, TypeError): - story["promoted_until"] = None - if not msg: - balance = u.get("aducoin", 0) - if balance < PROMOTE_COST: - msg, kind = ("Not enough AduCoin — you need %d, you have %d." - % (PROMOTE_COST, balance)), "error" - else: - u["aducoin"] = balance - PROMOTE_COST - story["promoted_until"] = (datetime.now() + timedelta(days=PROMOTE_DURATION_DAYS)).strftime(TS_FMT) - log_transaction(d, username, "promote_post", -PROMOTE_COST, - "Promoted story '%s'" % story.get("title", "Untitled"), - related_story_id=story_id) - ok = True - if ok: - flash("Story promoted to Hot for %d days!" % PROMOTE_DURATION_DAYS, "success") - else: - flash(msg, kind) - return redirect(url_for("profile")) - - -# ------------------------------------------------------------------- story page -PAGE_CSS_STORY = """ -.side-box .card-pad{text-align:center} -""" - - -@app.route("/story/", methods=["GET", "POST"]) -def story_page(story_id): - username = session.get("username") - - if request.method == "POST" and "add_comment" in request.form: - if not username: - flash("Log in to comment.", "error") - return redirect(url_for("login", next=request.path)) - text = (request.form.get("comment_text") or "").strip() - if not text: - flash("Comment cannot be empty.", "error") - return redirect(url_for("story_page", story_id=story_id)) - if len(text) > 1000: - flash("Comment too long (max 1000 characters).", "error") - return redirect(url_for("story_page", story_id=story_id)) - comment = {"username": username, "text": text, "timestamp": now_str()} - with DB.write(wait=True) as d: - story = next((p for p in d.get("posts", []) if p.get("id") == story_id), None) - if story is None: - flash("Story disappeared.", "error") - return redirect(url_for("feed")) - if not isinstance(story.get("comments"), list): - story["comments"] = [] - story["comments"].append(comment) - flash("Comment added!", "success") - return redirect(url_for("story_page", story_id=story_id) + "#comments") - - with DB.read() as data: - story = next((p for p in data.get("posts", []) if isinstance(p, dict) and p.get("id") == story_id), None) - if story is None: - flash("Story not found.", "error") - return redirect(url_for("feed")) - story = dict(story) - story.setdefault("title", "Untitled") - story.setdefault("description", "") - story.setdefault("type", "photo") - story.setdefault("filename", "") - story.setdefault("uploader", "unknown") - story.setdefault("upload_date", "") - story.setdefault("likes", []) - story.setdefault("views", 0) - story.setdefault("jerked_off_count", 0) - story.setdefault("comments", []) - promoted = False - if story.get("promoted_until"): - try: - promoted = datetime.strptime(story["promoted_until"], TS_FMT) > datetime.now() - except (ValueError, TypeError): - pass - story["is_currently_promoted"] = promoted - uploader = story.get("uploader") - users_lookup = {u: (d if isinstance(d, dict) else {}) - for u, d in (data.get("users") or {}).items()} - uploader_data = users_lookup.get(uploader, {}) - uploader_online = is_user_online(data, uploader) - sender_balance = ((data.get("users", {}) or {}).get(username) or {}).get("aducoin", 0) if username else 0 - uploader_story_count = sum(1 for p in data.get("posts", []) if p.get("uploader") == uploader) - related = [dict(p) for p in data.get("posts", []) - if isinstance(p, dict) and p.get("uploader") == uploader and p.get("id") != story_id] - related.sort(key=lambda x: str(x.get("upload_date", "")), reverse=True) - related = related[:4] - for p in related: - p.setdefault("title", "Untitled") - p.setdefault("type", "photo") - p.setdefault("filename", "") - p["_uploader_online"] = uploader_online - - can_donate = bool(username) and username != uploader - liked = bool(username) and username in (story.get("likes") or []) - murl = media_url(story.get("filename", ""), story.get("type", "photo")) - comments = sorted(story.get("comments") or [], key=lambda c: str(c.get("timestamp", ""))) - - if story.get("type") == "video": - poster = story.get("poster") or LOGO_URL - media = ('' - % (poster, murl)) - else: - media = '%s' % ( - murl, html.escape(story.get("title", ""))) - - comments_html = "" - for c in comments: - cuser = c.get("username", "?") - comments_html += """ -
- %(cavatar)s -
-
%(cuser)s%(ctime)s
-
%(ctext)s
-
-
""" % {"cid": html.escape(str(c.get("timestamp", "")).replace(" ", "-")), - "cavatar": avatar_html(users_lookup.get(cuser), cuser, 40), - "curl": url_for("user_profile", username=cuser), - "cuser": html.escape(cuser), - "ctime": html.escape(fmt_dt(c.get("timestamp", ""))), - "ctext": html.escape(c.get("text", ""))} - - jsonld = { - "@context": "https://schema.org", - "@type": "VideoObject" if story.get("type") == "video" else "ImageObject", - "name": story.get("title", "Untitled"), - "description": (story.get("description") or story.get("title") or "")[:500], - "thumbnailUrl": LOGO_URL, - "contentUrl": murl, - "uploadDate": story.get("upload_date"), - "genre": "Adult", - "isFamilyFriendly": False, - "interactionStatistic": [ - {"@type": "InteractionCounter", "interactionType": "https://schema.org/WatchAction", - "userInteractionCount": story.get("views", 0)}, - ], - "creator": {"@type": "Person", "name": uploader, - "url": abs_url("/user/%s" % uploader)}, - "url": abs_url(request.path), - } - jsonld = [jsonld, { - "@context": "https://schema.org", "@type": "BreadcrumbList", - "itemListElement": [ - {"@type": "ListItem", "position": 1, "name": "Latest", "item": abs_url("/feed/latest")}, - {"@type": "ListItem", "position": 2, "name": story.get("title", "Story"), - "item": abs_url(request.path)}, - ]}] - - body = """ -
-
-
-
-
-
%(media)s
-
-

%(title)s %(hot)s

-
- - - %(eye)s %(views)d - %(chat)s %(ncomments)d - -
- %(donate)s -
-

%(info_icon)s Details

-

%(description)s

-

Uploaded %(uploaded)s by - %(uploader)s

-
-
-

%(chat_icon)s Comments (%(ncomments)d)

- %(comment_form)s -
%(comments)s
-
-
- - -
-
-""" % { - "media": media, - "title": html.escape(story.get("title", "Untitled")), - "hot": 'HOT' if story.get("is_currently_promoted") else "", - "liked": "liked" if liked else "", - "sid": html.escape(story_id), - "heart": icon("heart"), "eye": icon("eye"), "chat": icon("chat"), - "likes": len(story.get("likes") or []), - "jerks": story.get("jerked_off_count", 0), - "views": story.get("views", 0), - "ncomments": len(comments), - "title_js": json.dumps(story.get("title", "Story")), - "share": icon("share"), - "donate": (""" -
-

%(gift)s Support %(uploader)s

-
- - -
-

Your balance: %(balance)d AduCoin

-
""" % {"action": url_for("donate_story", story_id=story_id), - "gift": icon("gift"), "uploader": html.escape(uploader), - "balance": sender_balance}) if can_donate else - ('
' - '%s Log in to donate AduCoin and comment.
' - % (icon("gift"), url_for("login", next=request.path)) if not username else ""), - "info_icon": icon("sparkle"), - "description": html.escape(story.get("description") or "No description provided."), - "uploaded": html.escape(time_ago(story.get("upload_date", "")) or "recently"), - "uploader_url": url_for("user_profile", username=uploader), - "uploader": html.escape(uploader), - "chat_icon": icon("chat"), - "comment_form": (""" -
- -
- -
- -
""" % {"send": icon("send")}) if username else - ('

Log in to comment.' - % url_for("login", next=request.path)), - "comments": comments_html or empty_state("No comments yet", "Be the first to comment!", - None, None, art="chat"), - "avatar": avatar_html(uploader_data, uploader, 92), - "uploader_stories": uploader_story_count, - "online": (' online now' if uploader_online else "offline"), - "message_btn": ('%s Message' - % (url_for("conversation", other_username=uploader), icon("mail"))) - if (username and username != uploader) else "", - "related_html": (""" -

-

More from %(uploader)s

-
%(cards)s
-
""" % {"uploader": html.escape(uploader), - "cards": "".join(story_card_html(p, show_uploader=False, - users_lookup=users_lookup) for p in related)}) - if related else "", - } - - return page_html("%s — %s" % (story.get("title", "Story"), SITE_NAME), - (story.get("description") or story.get("title") or "Watch on %s" % SITE_NAME)[:300], - body, path=request.path, jsonld=jsonld, - og_type="video.other" if story.get("type") == "video" else "article", - og_image=murl, css=PAGE_CSS_STORY, active="home") - - -# ------------------------------------------------------------------- donate -@app.route("/donate/", methods=["POST"]) -@login_required -def donate_story(story_id): - sender = session["username"] - try: - amount = int(request.form.get("amount") or 0) - if amount <= 0: - raise ValueError - except (ValueError, TypeError): - flash("Invalid amount.", "error") - return redirect(url_for("story_page", story_id=story_id)) - - ok = False - with DB.write(wait=True) as d: - story = next((p for p in d.get("posts", []) if p.get("id") == story_id), None) - if story is None: - flash("Story not found.", "error") - return redirect(url_for("feed")) - recipient = story.get("uploader") - users = d.get("users", {}) - if recipient not in users: - flash("Story uploader not found.", "error") - return redirect(url_for("story_page", story_id=story_id)) - if recipient == sender: - flash("You cannot donate to your own post.", "error") - return redirect(url_for("story_page", story_id=story_id)) - if sender not in users: - session.pop("username", None) - flash("Account not found — please log in again.", "error") - return redirect(url_for("login")) - balance = users[sender].get("aducoin", 0) - if balance < amount: - flash("Not enough AduCoin — you have %d." % balance, "error") - return redirect(url_for("story_page", story_id=story_id)) - users[sender]["aducoin"] = balance - amount - users[recipient]["aducoin"] = users[recipient].get("aducoin", 0) + amount - log_transaction(d, sender, "donation_sent", -amount, - "Donated to '%s' for '%s'" % (recipient, story.get("title", "Untitled")), - related_user=recipient, related_story_id=story_id) - log_transaction(d, recipient, "donation_received", amount, - "Received from '%s' for '%s'" % (sender, story.get("title", "Untitled")), - related_user=sender, related_story_id=story_id) - ok = True - if ok: - flash("Donated %d AduCoin — thank you!" % amount, "success") - return redirect(url_for("story_page", story_id=story_id)) - - -# ------------------------------------------------------------------- upload -PAGE_CSS_UPLOAD = """ -#fileInput{display:none} -""" - - -@app.route("/upload", methods=["GET", "POST"]) -@login_required -def upload(): - username = session["username"] - - if request.method == "POST": - title = (request.form.get("title") or "").strip()[:150] - description = (request.form.get("description") or "").strip()[:2000] - file = request.files.get("file") - - if not file or not file.filename: - flash("File is required.", "error") - return redirect(url_for("upload")) - if not title: - flash("Title is required.", "error") - return redirect(url_for("upload")) - if not allowed_file(file.filename, ALLOWED_MEDIA_EXT): - flash("Invalid file type. Allowed: png, jpg, jpeg, gif, mp4, mov, avi, webm.", "error") - return redirect(url_for("upload")) - if HF_DISABLED or not HF_AVAILABLE or not HF_TOKEN_WRITE: - flash("Server storage is not configured (HF_TOKEN missing).", "error") - return redirect(url_for("upload")) - - ext = os.path.splitext(file.filename)[1].lower() - base_filename = secure_filename("%s_%d_%d%s" % (username, int(time.time()), random.randint(100, 999), ext)) - temp_path = os.path.join(UPLOAD_FOLDER, base_filename) - file_type = "video" if ext in (".mp4", ".mov", ".avi", ".webm") else "photo" - story = None - try: - file.save(temp_path) - if os.path.getsize(temp_path) > MAX_UPLOAD_BYTES: - os.remove(temp_path) - flash("File is too large (max %d MB)." % (MAX_UPLOAD_BYTES // 1024 // 1024), "error") - return redirect(url_for("upload")) - with DB.read() as data: - story_id = str(random.randint(100000, 999999)) - existing = {p.get("id") for p in data.get("posts", [])} - while story_id in existing: - story_id = str(random.randint(100000, 999999)) - - api = HfApi() - api.upload_file( - path_or_fileobj=temp_path, path_in_repo="%ss/%s" % (file_type, base_filename), - repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, - commit_message="Upload %s by %s (ID: %s)" % (file_type, username, story_id)) - - new_story = { - "id": story_id, "title": title, "description": description, - "filename": base_filename, "type": file_type, "uploader": username, - "upload_date": now_str(), "likes": [], "views": 0, "comments": [], - "jerked_off_count": 0, "views_reward_milestone": 0, "promoted_until": None, - } - with DB.write(wait=True) as d: - d.setdefault("posts", []).append(new_story) - u = d.get("users", {}).get(username) - if isinstance(u, dict): - u["aducoin"] = u.get("aducoin", 0) + UPLOAD_REWARD - log_transaction(d, username, "earn_upload", UPLOAD_REWARD, - "Uploaded story '%s'" % title, related_story_id=story_id) - NOTIFIER.push_story_now(new_story) - flash("Story uploaded! +%d AduCoin" % UPLOAD_REWARD, "success") - return redirect(url_for("story_page", story_id=story_id)) - except Exception as e: - log.error("Upload failed: %s", e, exc_info=True) - flash("Upload failed: %s" % html.escape(str(e))[:200], "error") - return redirect(url_for("upload")) - finally: - if os.path.exists(temp_path): - os.remove(temp_path) - - body = """ -
-
-

Upload a story

-

Photos and videos · up to %(maxmb)d MB · earn %(reward)d AduCoin per upload

-
-
-
-
-
-
-
- -
-
%(upload_icon)s
- Tap to choose a photo or video - or drag & drop it here · PNG, JPG, GIF, MP4, WEBM - -
- -
-
- -

You earn %(reward)d AduCoin for every upload.

-
-
-""" % {"maxmb": MAX_UPLOAD_BYTES // 1024 // 1024, "reward": UPLOAD_REWARD, - "upload_icon": icon("upload"), "rocket": icon("rocket")} - return page_html("Upload a story — %s" % SITE_NAME, - "Share a photo or video with the %s community and earn AduCoin." % SITE_NAME, - body, path="/upload", noindex=True, css=PAGE_CSS_UPLOAD, active="upload") - - -# ------------------------------------------------------------------- users -@app.route("/users", methods=["GET", "POST"]) -def users(): - q = "" - if request.method == "POST": - q = (request.form.get("search") or "").strip().lower() - with DB.read() as data: - users_data = data.get("users") or {} - user_list = [] - for uname, udata in users_data.items(): - udata = udata if isinstance(udata, dict) else {} - if q and q not in uname.lower(): - continue - user_list.append({"name": uname, "data": udata, - "online": is_user_online(data, uname)}) - user_list.sort(key=lambda x: (not x["online"], x["name"].lower())) - - cards = "".join(""" - - %(avatar)s - %(name)s - %(onlabel)s · %(role)s - -""" % {"url": url_for("user_profile", username=u["name"]), - "avatar": avatar_html(u["data"], u["name"], 56, online=u["online"]), - "name": html.escape(u["name"]), - "onlabel": "Online" if u["online"] else "Offline", - "role": html.escape(str(u["data"].get("role") or "member").title())} - for u in user_list) - - body = """ -
-
-

Community

-

%(count)d members on %(site)s

-
-
- - -
-
%(cards)s
-
""" % {"count": len(user_list), "site": SITE_NAME, "q": html.escape(q), - "search_icon": icon("search"), - "cards": cards or empty_state("No members found", "Try another search.", - None, None, art="users")} - return page_html("Community — %s" % SITE_NAME, - "Browse %d members of %s." % (len(user_list), SITE_NAME), - body, path="/users", active="users") - - -# ------------------------------------------------------------------- user profile -@app.route("/user/", methods=["GET"]) -def user_profile(username): - current = session.get("username") - if username == current: - return redirect(url_for("profile")) - - with DB.read() as data: - users_data = data.get("users") or {} - if username not in users_data: - flash("User '%s' not found." % username, "error") - return redirect(url_for("users")) - u = users_data[username] if isinstance(users_data[username], dict) else {} - online = is_user_online(data, username) - users_lookup = {u: (d if isinstance(d, dict) else {}) - for u, d in (data.get("users") or {}).items()} - posts = [] - for p in data.get("posts", []): - if not isinstance(p, dict) or p.get("uploader") != username: - continue - p = dict(p) # копия: служебные ключи не попадают в базу - p.setdefault("title", "Untitled") - p.setdefault("type", "photo") - p.setdefault("filename", "") - p["_uploader_online"] = online - posts.append(p) - posts.sort(key=lambda x: str(x.get("upload_date", "")), reverse=True) - user_count = len(users_data) - sender_balance = ((users_data.get(current) or {}).get("aducoin", 0) - if isinstance(users_data.get(current), dict) else 0) if current else 0 - - last_seen = "Unknown" - try: - dt = datetime.strptime(u.get("last_seen", ""), TS_FMT) - if online: - last_seen = "Online now" - else: - diff = datetime.now() - dt - if diff < timedelta(hours=1): - last_seen = "Seen %dm ago" % int(diff.total_seconds() // 60) - elif diff < timedelta(days=1): - last_seen = "Today at %s" % dt.strftime("%H:%M") - else: - last_seen = dt.strftime("%b %d, %Y") - except (ValueError, TypeError): - pass - - total_likes = sum(len(p.get("likes", []) or []) for p in posts) - total_views = sum(int(p.get("views", 0) or 0) for p in posts) - - jsonld = { - "@context": "https://schema.org", - "@type": "ProfilePage", - "mainEntity": { - "@type": "Person", "name": username, - "url": abs_url(request.path), - "description": (u.get("bio") or "%s on %s" % (username, SITE_NAME))[:300], - "interactionStatistic": [ - {"@type": "InteractionCounter", "interactionType": "https://schema.org/WriteAction", - "userInteractionCount": len(posts)}, - ], - }, - } - - body = """ -
-
-
-
- %(avatar)s -
-

%(name)s %(coin)s %(balance)d

-
- %(role)s - %(last_seen)s - %(stories)d stories -
- %(bio)s - %(link)s -
- %(msg_btn)s - %(donate_btn)s -
-
-
-
-
%(stories)dStories
-
%(likes)dLikes
-
%(views)dViews
-
%(coin_bal)dAduCoin
-
-

%(video_icon)s Stories by %(name)s

- %(grid)s -
-
""" % { - "avatar": avatar_html(u, username, 132), - "name": html.escape(username), - "coin": icon("coin"), "balance": u.get("aducoin", 0), - "role": html.escape(str(u.get("role") or "member").title()), - "on": "online" if online else "offline", - "last_seen": html.escape(last_seen), - "stories": len(posts), - "bio": ('

%s

' - % html.escape(u.get("bio", "")) if u.get("bio") else ""), - "link": ('

%s

' - % (html.escape(u.get("link", "")), html.escape(u.get("link", ""))) if u.get("link") else ""), - "msg_btn": ('%s Message' - % (url_for("conversation", other_username=username), icon("mail"))) - if current else ('Log in to message' - % url_for("login", next=request.path)), - "donate_btn": (""" -
- - -
""" % {"action": url_for("transfer_aducoin", recipient_username=username), - "balance": sender_balance, "gift": icon("gift")}) if current else "", - "likes": total_likes, "views": total_views, "coin_bal": u.get("aducoin", 0), - "video_icon": icon("video"), - "grid": ('
%s
' - % "".join(story_card_html(p, users_lookup=users_lookup) for p in posts) - if posts else empty_state("No stories yet", "%s has not uploaded anything." - % html.escape(username), None, None, art="image")), - } - return page_html("%s (@%s) — %s" % (username, username, SITE_NAME), - "%s on %s — %d stories, %d likes." % (username, SITE_NAME, len(posts), total_likes), - body, path=request.path, jsonld=jsonld, active="users") - - -# ------------------------------------------------------------------- transactions -@app.route("/transactions") -@login_required -def transactions(): - username = session["username"] - with DB.read() as data: - txs = sorted([t for t in data.get("transactions", []) if t.get("user") == username], - key=lambda x: str(x.get("timestamp", "")), reverse=True) - balance = ((data.get("users", {}) or {}).get(username) or {}).get("aducoin", 0) - - if txs: - items = "".join(""" -
- %(arrow)s - %(type)s%(desc)s%(time)s - %(amt)s -
""" % {"cls": "pos" if t.get("amount", 0) > 0 else "neg", - "arrow": "↗" if t.get("amount", 0) > 0 else "↘", - "type": html.escape(str(t.get("type", "")).replace("_", " ").title()), - "desc": html.escape(str(t.get("description", ""))), - "time": html.escape(fmt_dt(t.get("timestamp", ""))), - "amt": "%+d" % t.get("amount", 0) if t.get("amount", 0) != 0 else str(t.get("amount", 0))} - for t in txs) - listing = '
%s
' % items - else: - listing = empty_state("No transactions yet", - "Upload stories, collect views and invite friends to earn AduCoin.", - "Upload a story", url_for("upload"), art="coin") - - body = """ -
-
-

%(coin_icon)s AduCoin history

-

Every coin you earned and spent

-
-
- %(coin_icon)s %(balance)d AduCoin - Current balance - Back to profile -
- %(listing)s -
""" % {"coin_icon": icon("coin"), "balance": balance, "listing": listing} - return page_html("AduCoin history — %s" % SITE_NAME, - "Your AduCoin transaction history on %s." % SITE_NAME, - body, path="/transactions", noindex=True, active="wallet") - - -# ------------------------------------------------------------------- transfer -@app.route("/transfer_aducoin/", methods=["POST"]) -@login_required -def transfer_aducoin(recipient_username): - sender = session["username"] - if sender == recipient_username: - flash("You cannot transfer to yourself.", "error") - return redirect(url_for("user_profile", username=recipient_username)) - try: - amount = int(request.form.get("amount") or 0) - if amount <= 0: - raise ValueError - except (ValueError, TypeError): - flash("Invalid amount.", "error") - return redirect(url_for("user_profile", username=recipient_username)) - - ok = False - with DB.write(wait=True) as d: - users = d.get("users", {}) - if sender not in users: - session.pop("username", None) - flash("Account not found — please log in again.", "error") - return redirect(url_for("login")) - if recipient_username not in users: - flash("Recipient '%s' not found." % recipient_username, "error") - return redirect(url_for("users")) - balance = users[sender].get("aducoin", 0) - if balance < amount: - flash("Not enough AduCoin — you have %d." % balance, "error") - return redirect(url_for("user_profile", username=recipient_username)) - users[sender]["aducoin"] = balance - amount - users[recipient_username]["aducoin"] = users[recipient_username].get("aducoin", 0) + amount - log_transaction(d, sender, "transfer_sent", -amount, - "Sent to '%s'" % recipient_username, related_user=recipient_username) - log_transaction(d, recipient_username, "transfer_received", amount, - "Received from '%s'" % sender, related_user=sender) - ok = True - if ok: - flash("Transferred %d AduCoin to %s." % (amount, recipient_username), "success") - return redirect(url_for("user_profile", username=recipient_username)) - - -# ------------------------------------------------------------------- notifications page -PAGE_CSS_NOTIF = "" - - -@app.route("/notifications") -def notifications_page(): - if not g.get("username"): - body = """ -
-

Notifications

-

Log in to manage push notifications

-
- %(bell)s -

Stay in the loop

-

Log in to enable push notifications for new - messages and videos — they work even when the app is closed.

- Log in -
-
""" % {"bell": icon("bell"), "login": url_for("login", next="/notifications")} - return page_html("Notifications — %s" % SITE_NAME, - "Push notification settings for %s." % SITE_NAME, - body, path="/notifications", css=PAGE_CSS_NOTIF, active="notifications") - - settings = {"notify_messages": True, "notify_videos": True} - subs_count = 0 - with DB.read() as data: - u = (data.get("users", {}) or {}).get(g.username) or {} - settings["notify_messages"] = bool(u.get("notify_messages", True)) - settings["notify_videos"] = bool(u.get("notify_videos", True)) - subs_count = len(get_subscriptions(data, g.username)) - - body = """ -
-

Notifications

-

Push alerts for messages and new videos

- -
- %(bell)s - - Push notifications - %(state_text)s - - %(state_label)s - -
- -
- %(mail)s - New messagesGet notified when someone writes to you - -
-
- %(video)s - New videos & storiesGet notified when fresh content drops - -
- -
-

%(phone)s Installing on iPhone

-

Push on iOS needs the app on your Home Screen:

-
-
Open in SafariPush does not work in Chrome/Firefox on iOS
-
Share → Add to Home ScreenUse the share icon in Safari's toolbar
-
Open the app & tap EnableRequires iOS 16.4 or newer
-
- -
- -
- - -
-

Active devices: %(subs)d

-
-""" % {"bell": icon("bell"), "mail": icon("mail"), "video": icon("video"), - "phone": icon("phone"), "download": icon("download"), "send": icon("send"), - "state_text": "Checking status...", "state_cls": "muted", "state_label": "…", - "msg_on": "checked" if settings["notify_messages"] else "", - "vid_on": "checked" if settings["notify_videos"] else "", - "subs": subs_count} - return page_html("Notifications — %s" % SITE_NAME, - "Manage push notifications for messages and new videos on %s." % SITE_NAME, - body, path="/notifications", css=PAGE_CSS_NOTIF, active="notifications") - - -# ==================================================================== JSON API -@app.route("/like/", methods=["POST"]) -def like_story(story_id): - if not g.get("username"): - return jsonify({"error": "login required"}), 401 - username = g.username - result = {} - - def _fn(d): - story = next((p for p in d.get("posts", []) if p.get("id") == story_id), None) - if story is None: - result["error"] = "not found" - return - if not isinstance(story.get("likes"), list): - story["likes"] = [] - if username in story["likes"]: - story["likes"].remove(username) - liked = False - else: - story["likes"].append(username) - liked = True - result["likes"] = len(story["likes"]) - result["liked"] = liked - DB.mutate(_fn, wait=False) - if "error" in result: - return jsonify({"message": "Story not found"}), 404 - return jsonify({"message": "Success", "likes": result["likes"], "liked": result["liked"]}), 200 - - -@app.route("/jerk_off/", methods=["POST"]) -def jerk_off_story(story_id): - result = {} - - def _fn(d): - story = next((p for p in d.get("posts", []) if p.get("id") == story_id), None) - if story is None: - result["error"] = "not found" - return - if not isinstance(story.get("jerked_off_count"), int): - story["jerked_off_count"] = 0 - story["jerked_off_count"] += 1 - result["count"] = story["jerked_off_count"] - DB.mutate(_fn, wait=False) - if "error" in result: - return jsonify({"message": "Story not found"}), 404 - return jsonify({"message": "Success", "jerked_off_count": result["count"]}), 200 - - -@app.route("/view/", methods=["POST"]) -def increment_view(story_id): - result = {} - - def _fn(d): - story = next((p for p in d.get("posts", []) if p.get("id") == story_id), None) - if story is None: - result["error"] = "not found" - return - uploader = story.get("uploader") - if not isinstance(story.get("views"), int): - story["views"] = 0 - if not isinstance(story.get("views_reward_milestone"), int): - story["views_reward_milestone"] = 0 - story["views"] += 1 - current_views = story["views"] - last_milestone = story["views_reward_milestone"] - if uploader and isinstance(d.get("users", {}).get(uploader), dict): - current_m = current_views // VIEW_REWARD_THRESHOLD - last_m = last_milestone // VIEW_REWARD_THRESHOLD - if current_m > last_m: - reward = (current_m - last_m) * VIEW_REWARD_AMOUNT - d["users"][uploader]["aducoin"] = d["users"][uploader].get("aducoin", 0) + reward - story["views_reward_milestone"] = current_views - log_transaction(d, uploader, "earn_views", reward, - "Reached %d views on '%s'" % (current_m * VIEW_REWARD_THRESHOLD, - story.get("title", "Untitled")), - related_story_id=story_id) - result["reward_message"] = ("Awarded %d AduCoin to %s for %d views!" - % (reward, uploader, current_m * VIEW_REWARD_THRESHOLD)) - result["views"] = current_views - DB.mutate(_fn, wait=False) - if "error" in result: - return jsonify({"message": "Story not found"}), 404 - resp = {"message": "Success", "views": result["views"]} - if result.get("reward_message"): - resp["reward_message"] = result["reward_message"] - return jsonify(resp), 200 - - -# ==================================================================== messages -@app.route("/messages") -@login_required -def inbox(): - username = session["username"] - with DB.read() as data: - users_data = data.get("users") or {} - conversations = [] - for conv_key, messages in (data.get("direct_messages") or {}).items(): - participants = parse_conv_key(conv_key) - if username not in participants: - continue - other = next((u for u in participants if u != username), None) - if not other: - continue - msgs = [m for m in messages if isinstance(m, dict)] - if msgs: - last = sorted(msgs, key=lambda x: str(x.get("timestamp", "")))[-1] - last_text, last_time = last.get("text", ""), str(last.get("timestamp", "")) - unread = any(m.get("sender") != username and not m.get("read") for m in msgs) - else: - last_text, last_time, unread = "No messages yet", "", False - conversations.append({ - "other": other, "avatar": (users_data.get(other) or {}).get("avatar"), - "last_text": last_text, "last_time": last_time, "unread": unread, - "online": is_user_online(data, other)}) - conversations.sort(key=lambda c: (not c["unread"], c["last_time"]), reverse=True) - - items = "".join(""" - - %(avatar)s - - %(name)s - %(time)s - %(last)s - - %(badge)s -""" % {"unread": "unread" if c["unread"] else "", - "url": url_for("conversation", other_username=c["other"]), - "avatar": avatar_html(users_data.get(c["other"]), c["other"], 52), - "name": html.escape(c["other"]), - "on": "online" if c["online"] else "offline", - "time": html.escape(time_ago(c["last_time"]) if c["last_time"] else ""), - "last": html.escape(c["last_text"][:80]), - "badge": 'new' if c["unread"] else ""} - for c in conversations) - - body = """ -
-
-

Messages

-

Your private conversations

-
- %(users_icon)s Find people
- %(items)s -
""" % {"users_icon": icon("users"), - "items": items or empty_state("No conversations yet", - "Find someone in the community and say hi!", - "Browse community", url_for("users"), art="mail")} - return page_html("Messages — %s" % SITE_NAME, - "Your private conversations on %s." % SITE_NAME, - body, path="/messages", noindex=True, active="messages") - - -PAGE_CSS_CHAT = """ -.conversation-item{display:flex;gap:14px;align-items:center;padding:14px 16px;margin-bottom:11px;color:var(--text)} -.conversation-item.unread{border-color:rgba(255,79,216,.5);background:var(--grad-soft)} -.conv-body{flex:1;min-width:0} -.conv-top{display:flex;align-items:center;gap:8px;font-size:.98rem} -.conv-top b{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:180px} -.conv-time{font-size:.76rem;color:var(--text3);margin-left:auto;flex:none} -.conv-last{display:block;font-size:.86rem;color:var(--text2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} -""" - - -@app.route("/messages/", methods=["GET", "POST"]) -@login_required -def conversation(other_username): - username = session["username"] - conv_key = str(get_conversation_key(username, other_username)) - - if request.method == "POST": - text = (request.form.get("message_text") or "").strip() - if not text: - flash("Message cannot be empty.", "error") - return redirect(url_for("conversation", other_username=other_username)) - if len(text) > 2000: - flash("Message too long (max 2000 characters).", "error") - return redirect(url_for("conversation", other_username=other_username)) - message = {"message_id": str(uuid.uuid4()), "sender": username, - "text": text, "timestamp": now_str(), "read": False} - sent = False - with DB.write(wait=True) as d: - if other_username in (d.get("users") or {}): - if other_username == username: - flash("You cannot message yourself.", "warning") - return redirect(url_for("inbox")) - convs = d.setdefault("direct_messages", {}) - if not isinstance(convs.get(conv_key), list): - convs[conv_key] = [] - convs[conv_key].append(message) - sent = True - if sent: - NOTIFIER.push_message_now(conv_key, message) - else: - flash("User '%s' not found." % other_username, "error") - return redirect(url_for("conversation", other_username=other_username)) - - with DB.read() as data: - users_data = data.get("users") or {} - if other_username not in users_data: - flash("User '%s' not found." % other_username, "error") - return redirect(url_for("inbox")) - if other_username == username: - flash("You cannot message yourself.", "warning") - return redirect(url_for("inbox")) - other_data = users_data[other_username] if isinstance(users_data[other_username], dict) else {} - other_online = is_user_online(data, other_username) - messages = [m for m in (data.get("direct_messages", {}) or {}).get(conv_key, []) - if isinstance(m, dict)] - - # пометить входящие как прочитанные - def _mark(d): - for m in d.get("direct_messages", {}).get(conv_key, []): - if m.get("sender") == other_username and not m.get("read"): - m["read"] = True - try: - DB.mutate(_mark, wait=False) - except Exception as e: - log.warning("Could not mark messages read: %s", e) - - messages.sort(key=lambda m: str(m.get("timestamp", ""))) - bubbles = "" - last_day = None - for m in messages: - day = day_label(m.get("timestamp", "")) - if day and day != last_day: - bubbles += '
%s
' % html.escape(day) - last_day = day - bubbles += """ -
- %(text)s - %(time)s %(seen)s -
""" % {"cls": "out" if m.get("sender") == username else "in", - "text": html.escape(m.get("text", "")), - "time": html.escape(fmt_dt(m.get("timestamp", ""))), - "seen": ('%s' % icon("doublecheck")) - if (m.get("sender") == username and m.get("read")) else ""} - - body = """ -
-
- %(avatar)s -
-

%(name)s

-

%(onlabel)s

-
- Profile -
-
%(bubbles)s
-
- - -
-
-""" % {"avatar": avatar_html(other_data, other_username, 54), - "name": html.escape(other_username), - "on": "online" if other_online else "offline", - "onlabel": "Online now" if other_online else "Offline", - "profile_url": url_for("user_profile", username=other_username), - "bubbles": bubbles or '

No messages yet — say hi!

', - "send": icon("send")} - return page_html("Chat with %s — %s" % (other_username, SITE_NAME), - "Private conversation with %s on %s." % (other_username, SITE_NAME), - body, path=request.path, noindex=True, css=PAGE_CSS_CHAT, - active="messages") - - -# ==================================================================== errors -@app.errorhandler(404) -def not_found(e): - body = ('
%s
' - % empty_state("Page not found", "The page you are looking for does not exist.", - "Go to feed", url_for("feed"), art="search")) - return page_html("Not found — %s" % SITE_NAME, "Page not found.", body, - path="/404", noindex=True), 404 - - -@app.errorhandler(500) -def server_error(e): - body = ('
%s
' - % empty_state("Something went wrong", "Our team has been notified. Please try again.", - "Go to feed", url_for("feed"), art="rocket")) - return page_html("Error — %s" % SITE_NAME, "Server error.", body, - path="/500", noindex=True), 500 - - -# ==================================================================== main -def _bootstrap_data(): - """Первичная инициализация: гарантируем наличие файла и выгрузку в HF.""" - try: - with DB.read() as data: - need_upload = not DB.health().get("downloads") and DB.health().get("writes", 0) == 0 - if not os.path.exists(DATA_FILE): - log.info("Data file missing — creating from in-memory structure") - DB.mutate(lambda d: None, wait=True) - except Exception as e: - log.warning("Bootstrap warning: %s", e) - - -if __name__ == "__main__": - log.info("=" * 62) - log.info(" %s starting", SITE_NAME) - log.info(" Database : %s (queued writes + coalesced HF uploads)", DATA_FILE) - log.info(" HF sync : %s", "disabled" if HF_DISABLED else REPO_ID) - log.info(" Push : %s", "enabled (VAPID ready)" if PUSH_ENABLED else "disabled") - log.info("=" * 62) - _bootstrap_data() - NOTIFIER.start() - try: - from waitress import serve # опционально: продакшн-сервер - log.info("Starting waitress on port %d", PORT) - serve(app, host="0.0.0.0", port=PORT, threads=16) - except ImportError: - log.info("Starting Flask dev server on port %d (use gunicorn/waitress in prod)", PORT) - app.run(debug=False, host="0.0.0.0", port=PORT, threaded=True)