- Shared moderated MP3 profile music (with floating mini-player and MediaSession controls, zero bubble when absent) - AI video dubbing into Russian with burned-in ASS subtitles inside AgentChat (`services/members/dub.py`) - Picture-in-Picture 9:16 and background audio playback (`PlayControl` + `play_patch.py`) - System/custom .ttf fonts & emoji packs (`FontsAndEmoji`), account cleaner (`AccountCleaner`) - Feed blacklist, muted sound restoration, OLED burn-in shift, A/B flag editor, presets, long comments - Updated site homepage (`src/web/index.html`) for LihonT 2.3.0 Serena
324 lines
14 KiB
Python
324 lines
14 KiB
Python
"""Shared profile music stored per member and moderated by the owner via Telegram.
|
|
|
|
An installation proves ownership of its TikTok UID once (the same bio code as avatar shapes/frames), uploads an MP3
|
|
track up to ~3.5 MB, and waits for manual approval in Telegram. Only approved + active tracks are returned when
|
|
anyone visits a profile (`music_lookup` by `uid` or `@unique_id`). Profiles without an active approved track return
|
|
`{"track": None}` so the client renders no bubble at all.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
import community
|
|
from community import INSTALL, valid_uid
|
|
|
|
ID_RE = re.compile(r"[0-9a-f]{24}\Z")
|
|
MAX_RAW_BYTES = 3_800_000
|
|
MAX_DURATION = 240
|
|
UPLOAD_BODY = 5_500_000
|
|
MUSIC_STATES = ("new", "review", "approved", "rejected")
|
|
MP3_HDR = re.compile(rb"^(?:ID3|\xff[\xe0-\xff])")
|
|
|
|
|
|
def clean_handle(value) -> str:
|
|
if not isinstance(value, str):
|
|
return ""
|
|
handle = value.strip().lstrip("@").lower()
|
|
if not re.fullmatch(r"[a-z0-9_.]{2,30}", handle):
|
|
return ""
|
|
return handle
|
|
|
|
|
|
def clean_meta(value, default: str, limit: int = 48) -> str:
|
|
text = " ".join(str(value or "").split())[:limit].strip()
|
|
return text or default
|
|
|
|
|
|
def normalize_mp3(raw: bytes) -> tuple[bytes, int]:
|
|
"""Validates audio bytes with ffmpeg/ffprobe and re-encodes to clean 96k MP3. Returns (mp3_bytes, duration_sec)."""
|
|
if not isinstance(raw, (bytes, bytearray)) or len(raw) < 256 or len(raw) > MAX_RAW_BYTES:
|
|
raise ValueError("MP3 file size is invalid")
|
|
with tempfile.TemporaryDirectory(prefix="lihont-mp3-") as tmp:
|
|
src = Path(tmp) / "in.audio"
|
|
dst = Path(tmp) / "out.mp3"
|
|
src.write_bytes(bytes(raw))
|
|
probe = subprocess.run(
|
|
["ffprobe", "-v", "error", "-select_streams", "a:0",
|
|
"-show_entries", "stream=codec_type:format=duration", "-of", "json", str(src)],
|
|
capture_output=True, timeout=15, check=False,
|
|
)
|
|
if probe.returncode != 0:
|
|
raise ValueError("Unsupported or corrupt audio file")
|
|
try:
|
|
info = json.loads(probe.stdout.decode("utf-8", "replace"))
|
|
streams = info.get("streams") or []
|
|
dur = float((info.get("format") or {}).get("duration") or 0)
|
|
except (ValueError, TypeError):
|
|
raise ValueError("Unsupported or corrupt audio file")
|
|
if not streams or dur < 1.0:
|
|
raise ValueError("Audio is too short")
|
|
if dur > MAX_DURATION:
|
|
raise ValueError("Audio must be at most 4 minutes")
|
|
conv = subprocess.run(
|
|
["ffmpeg", "-y", "-v", "error", "-i", str(src), "-vn",
|
|
"-t", str(MAX_DURATION), "-ac", "2", "-ar", "44100", "-b:a", "96k",
|
|
"-map_metadata", "-1", "-f", "mp3", str(dst)],
|
|
capture_output=True, timeout=30, check=False,
|
|
)
|
|
if conv.returncode != 0 or not dst.is_file():
|
|
raise ValueError("Could not process audio file")
|
|
out = dst.read_bytes()
|
|
if len(out) < 256 or len(out) > MAX_RAW_BYTES:
|
|
raise ValueError("Processed MP3 exceeds limit")
|
|
return out, max(1, min(MAX_DURATION, int(round(dur))))
|
|
|
|
|
|
class MusicStore:
|
|
def __init__(self, registry, normalize=normalize_mp3):
|
|
self.r = registry
|
|
self.normalize = normalize
|
|
self.dir = Path(registry.art_dir).parent / "music"
|
|
with self.r.connect() as db:
|
|
db.execute(
|
|
"CREATE TABLE IF NOT EXISTS profile_music ("
|
|
"id TEXT PRIMARY KEY, "
|
|
"uid TEXT NOT NULL, "
|
|
"unique_id TEXT NOT NULL DEFAULT '', "
|
|
"title TEXT NOT NULL, "
|
|
"artist TEXT NOT NULL, "
|
|
"duration INTEGER NOT NULL DEFAULT 0, "
|
|
"sha256 TEXT NOT NULL, "
|
|
"status TEXT NOT NULL, "
|
|
"reason TEXT NOT NULL DEFAULT '', "
|
|
"active INTEGER NOT NULL DEFAULT 0, "
|
|
"created_at INTEGER NOT NULL, "
|
|
"decided_at INTEGER, "
|
|
"review_message INTEGER)"
|
|
)
|
|
db.execute("CREATE INDEX IF NOT EXISTS profile_music_uid ON profile_music(uid, created_at)")
|
|
db.execute("CREATE INDEX IF NOT EXISTS profile_music_handle ON profile_music(unique_id, status, active)")
|
|
|
|
def _row_dict(self, row) -> dict | None:
|
|
if row is None:
|
|
return None
|
|
return {
|
|
"id": row[0],
|
|
"uid": row[1],
|
|
"unique_id": row[2],
|
|
"title": row[3],
|
|
"artist": row[4],
|
|
"duration": row[5],
|
|
"sha256": row[6],
|
|
"status": row[7],
|
|
"reason": row[8],
|
|
"active": bool(row[9]),
|
|
"created_at": row[10],
|
|
"decided_at": row[11],
|
|
"review_message": row[12],
|
|
}
|
|
|
|
def track(self, track_id: str) -> dict | None:
|
|
if not isinstance(track_id, str) or not ID_RE.fullmatch(track_id):
|
|
return None
|
|
with self.r.connect() as db:
|
|
row = db.execute(
|
|
"SELECT id,uid,unique_id,title,artist,duration,sha256,status,reason,active,created_at,decided_at,review_message "
|
|
"FROM profile_music WHERE id=?",
|
|
(track_id,),
|
|
).fetchone()
|
|
return self._row_dict(row)
|
|
|
|
def bytes(self, track_id: str, approved_only: bool = True) -> bytes | None:
|
|
t = self.track(track_id)
|
|
if t is None or (approved_only and t["status"] != "approved"):
|
|
return None
|
|
try:
|
|
return (self.dir / (t["sha256"] + ".mp3")).read_bytes()
|
|
except OSError:
|
|
return None
|
|
|
|
def in_state(self, status: str, limit: int = 5) -> list[dict]:
|
|
with self.r.connect() as db:
|
|
rows = db.execute(
|
|
"SELECT id FROM profile_music WHERE status=? ORDER BY created_at LIMIT ?",
|
|
(status, limit),
|
|
).fetchall()
|
|
return [t for r in rows if (t := self.track(r[0])) is not None]
|
|
|
|
def counts(self) -> dict:
|
|
with self.r.connect() as db:
|
|
return dict(db.execute("SELECT status, COUNT(*) FROM profile_music GROUP BY status").fetchall())
|
|
|
|
def decide(self, track_id: str, status: str, reason: str = "", review_message=None):
|
|
if status not in MUSIC_STATES:
|
|
raise ValueError("Unknown state")
|
|
t = self.track(track_id)
|
|
if t is None:
|
|
return
|
|
now = int(self.r.clock())
|
|
with self.r.connect() as db:
|
|
if status == "approved":
|
|
# Automatically activate newly approved track for its owner and deactivate older ones.
|
|
db.execute("UPDATE profile_music SET active=0 WHERE uid=?", (t["uid"],))
|
|
db.execute(
|
|
"UPDATE profile_music SET status=?, reason=?, decided_at=?, active=1, review_message=COALESCE(?, review_message) WHERE id=?",
|
|
(status, str(reason)[:120], now, review_message, track_id),
|
|
)
|
|
else:
|
|
db.execute(
|
|
"UPDATE profile_music SET status=?, reason=?, decided_at=?, review_message=COALESCE(?, review_message) WHERE id=?",
|
|
(status, str(reason)[:120], now, review_message, track_id),
|
|
)
|
|
|
|
def _proven_owner(self, uid: str, installation: str, unique_id: str | None = None):
|
|
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
|
|
raise ValueError("Invalid account ID or installation code")
|
|
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
|
|
with self.r.connect() as db:
|
|
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
|
raise ValueError("Account excluded")
|
|
owner = db.execute("SELECT installation, unique_id FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
|
if owner is not None and hmac.compare_digest(owner[0], digest):
|
|
handle = clean_handle(unique_id) or clean_handle(owner[1])
|
|
if handle and handle != owner[1]:
|
|
with self.r.connect() as db:
|
|
db.execute("UPDATE shape_owner SET unique_id=? WHERE uid=?", (handle, uid))
|
|
db.execute("UPDATE profile_music SET unique_id=? WHERE uid=?", (handle, uid))
|
|
return None, handle
|
|
reply = self.r._prove(uid, digest, unique_id.lstrip("@") if isinstance(unique_id, str) else unique_id)
|
|
if reply is not None:
|
|
return reply, ""
|
|
return None, clean_handle(unique_id)
|
|
|
|
def upload(self, uid, installation, unique_id, title, artist, data):
|
|
reply, handle = self._proven_owner(uid, installation, unique_id)
|
|
if reply is not None:
|
|
return reply
|
|
now = int(self.r.clock())
|
|
with self.r.connect() as db:
|
|
waiting = db.execute("SELECT COUNT(*) FROM profile_music WHERE uid=? AND status IN ('new','review')", (uid,)).fetchone()[0]
|
|
today = db.execute("SELECT COUNT(*) FROM profile_music WHERE uid=? AND created_at>?", (uid, now - 86400)).fetchone()[0]
|
|
try:
|
|
raw = base64.b64decode(data, validate=True) if isinstance(data, str) else b""
|
|
except (ValueError, TypeError):
|
|
raise ValueError("Not an MP3 file")
|
|
mp3, duration = self.normalize(raw)
|
|
sha = hashlib.sha256(mp3).hexdigest()
|
|
track_id = sha[:24]
|
|
clean_title = clean_meta(title, "Трек профиля", 48)
|
|
clean_artist = clean_meta(artist, "@" + handle if handle else "LihonT", 40)
|
|
known = self.track(track_id)
|
|
if known is not None:
|
|
if known["uid"] != uid:
|
|
raise ValueError("This audio is already registered")
|
|
if known["status"] == "approved":
|
|
with self.r.connect() as db:
|
|
db.execute("UPDATE profile_music SET active=0 WHERE uid=?", (uid,))
|
|
db.execute(
|
|
"UPDATE profile_music SET title=?, artist=?, unique_id=?, active=1 WHERE id=?",
|
|
(clean_title, clean_artist, handle or known["unique_id"], track_id),
|
|
)
|
|
return {"ok": True, "published": True, "track": self.track(track_id)}
|
|
return {"ok": True, "published": True, "track": known}
|
|
if waiting >= 2 or today >= 5:
|
|
raise ValueError("Too many tracks waiting, try again later")
|
|
self.dir.mkdir(parents=True, exist_ok=True)
|
|
target = self.dir / (sha + ".mp3")
|
|
part = self.dir / (sha + ".part")
|
|
part.write_bytes(mp3)
|
|
part.replace(target)
|
|
with self.r.connect() as db:
|
|
db.execute(
|
|
"INSERT INTO profile_music(id,uid,unique_id,title,artist,duration,sha256,status,created_at,active) "
|
|
"VALUES(?,?,?,?,?,?,?,?,?,0)",
|
|
(track_id, uid, handle, clean_title, clean_artist, duration, sha, "new", now),
|
|
)
|
|
return {"ok": True, "published": True, "track": self.track(track_id)}
|
|
|
|
def lookup(self, uid=None, unique_id=None):
|
|
u_id = uid if valid_uid(uid) else ""
|
|
handle = clean_handle(unique_id)
|
|
if not u_id and not handle:
|
|
raise ValueError("Account id or handle required")
|
|
with self.r.connect() as db:
|
|
if u_id:
|
|
row = db.execute(
|
|
"SELECT id,uid,unique_id,title,artist,duration FROM profile_music "
|
|
"WHERE uid=? AND status='approved' AND active=1 "
|
|
"AND NOT EXISTS (SELECT 1 FROM active_blocked b WHERE b.uid=profile_music.uid) "
|
|
"ORDER BY COALESCE(decided_at, created_at) DESC LIMIT 1",
|
|
(u_id,),
|
|
).fetchone()
|
|
else:
|
|
row = db.execute(
|
|
"SELECT id,uid,unique_id,title,artist,duration FROM profile_music "
|
|
"WHERE LOWER(unique_id)=? AND status='approved' AND active=1 "
|
|
"AND NOT EXISTS (SELECT 1 FROM active_blocked b WHERE b.uid=profile_music.uid) "
|
|
"ORDER BY COALESCE(decided_at, created_at) DESC LIMIT 1",
|
|
(handle,),
|
|
).fetchone()
|
|
if row is None:
|
|
return {"track": None}
|
|
return {
|
|
"track": {
|
|
"id": row[0],
|
|
"uid": row[1],
|
|
"unique_id": row[2],
|
|
"title": row[3],
|
|
"artist": row[4],
|
|
"duration": row[5],
|
|
"path": "music/" + row[0] + ".mp3",
|
|
}
|
|
}
|
|
|
|
def mine(self, uid, installation):
|
|
if not self.r._proven(uid, installation):
|
|
return {"tracks": []}
|
|
with self.r.connect() as db:
|
|
rows = db.execute(
|
|
"SELECT id,title,artist,duration,status,reason,active,created_at FROM profile_music "
|
|
"WHERE uid=? ORDER BY created_at DESC LIMIT 10",
|
|
(uid,),
|
|
).fetchall()
|
|
return {
|
|
"tracks": [
|
|
{
|
|
"id": r[0],
|
|
"title": r[1],
|
|
"artist": r[2],
|
|
"duration": r[3],
|
|
"status": r[4],
|
|
"reason": r[5],
|
|
"active": bool(r[6]),
|
|
"path": "music/" + r[0] + ".mp3" if r[4] == "approved" else "",
|
|
}
|
|
for r in rows
|
|
]
|
|
}
|
|
|
|
def select(self, uid, installation, track_id):
|
|
if not self.r._proven(uid, installation):
|
|
raise ValueError("Prove the account first")
|
|
t = self.track(track_id)
|
|
if t is None or t["uid"] != uid or t["status"] != "approved":
|
|
raise ValueError("Track is not available")
|
|
with self.r.connect() as db:
|
|
db.execute("UPDATE profile_music SET active=0 WHERE uid=?", (uid,))
|
|
db.execute("UPDATE profile_music SET active=1 WHERE id=? AND uid=?", (track_id, uid))
|
|
return {"ok": True}
|
|
|
|
def clear(self, uid, installation):
|
|
if not self.r._proven(uid, installation):
|
|
raise ValueError("Prove the account first")
|
|
with self.r.connect() as db:
|
|
db.execute("UPDATE profile_music SET active=0 WHERE uid=?", (uid,))
|
|
return {"ok": True}
|