diff --git a/.gitignore b/.gitignore index 8f1f12a..a8a1986 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,8 @@ # Per-app and per-plugin build output /LihonB/build/ /LihonB/gen/ +/apps/lihon-chat-android/build/ +/apps/lihon-chat-android/gen/ /sample_plugin/*/build/ # Built plugins at the repo root (sources live in sample_plugin/) diff --git a/docs/plugins-guide.md b/docs/plugins-guide.md index 11f597e..f5fe680 100644 --- a/docs/plugins-guide.md +++ b/docs/plugins-guide.md @@ -11,7 +11,9 @@ Что могут плагины сейчас: -- скрывать видео в ленте по хэштегам, словам, автору, времени суток; +- скрывать видео в ленте по хэштегам, словам, автору, времени суток, длительности, лайкам, свежести, музыке и другим + свойствам видео; +- оставлять в ленте только выбранное — белый список поверх других правил; - дописывать или менять имена, которые видите вы (в чужих профилях имя при этом не меняется); - показывать короткие подсказки; - показывать свою картинку поверх приложения (её можно двигать, на неё можно нажимать: анимация, звук, лайк); diff --git a/docs/plugins.md b/docs/plugins.md index 8cf9a18..36cd150 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -18,8 +18,8 @@ - **Откат.** После обновления плагина прошлая версия лежит рядом, её можно вернуть одним нажатием. - **Безопасный режим.** Если приложение несколько раз подряд закрылось сразу после запуска с включёнными плагинами, следующий запуск идёт без них, а в настройках есть кнопка «Включить плагины снова». -- **Не привязан к внутренностям TikTok.** Правила описывают видео и имена (текст, хештеги, автор, время), а не классы - TikTok. Когда TikTok обновится, обновляется мод, а плагины остаются прежними. +- **Не привязан к внутренностям TikTok.** Правила описывают видео и имена (текст, хештеги, автор, длительность, + лайки, музыка, время), а не классы TikTok. Когда TikTok обновится, обновляется мод, а плагины остаются прежними. ## Файл @@ -107,9 +107,21 @@ python scripts/make_ltp.py plugins/my.plugin | `{"account": ["имя", ...]}` | Правило работает, только пока вы вошли под одним из этих аккаунтов. | | `{"time": "22:00-07:00"}` | Местное время в промежутке (можно через полночь). | | `{"weekday": [6, 7]}` | День недели: 1 понедельник … 7 воскресенье. | +| `{"duration": [10, 60]}` | Длительность видео от 10 до 60 секунд; `null` вместо границы — без неё. | +| `{"likes": [1000, null]}` | Не меньше 1000 лайков. Так же `comments`, `shares`, `plays`. | +| `{"age": [null, 7]}` | Видео не старше 7 дней (возраст в днях). | +| `{"followers": [100000, null]}` | У автора не меньше 100 000 подписчиков. | +| `{"verified": true}` | У автора есть галочка. | +| `{"photo": true}` | Это фото, а не видео. | +| `{"liked": true}` | Вы уже лайкнули это видео. | +| `{"music": ["phonk"]}` | В названии или у автора музыки есть любое из слов. | +| `{"chance": 10}` | Правило срабатывает с вероятностью 10% (целое от 1 до 100). | | `{"all": [...]}`, `{"any": [...]}`, `{"not": ...}` | Сочетания. Вложенность до 4, всего до 40 условий в правиле. | -Списки слов: до 64 значений, до 80 знаков в каждом. +Списки слов: до 64 значений, до 80 знаков в каждом. Границы чисел: от 0 до 2 000 000 000 (для +длительности — до 86 400 секунд, для возраста — до 36 500 дней), хотя бы одна граница нужна. +Если TikTok не сообщил число (например, у видео нет счётчика), условие считается ложным; `not` +переворачивает и это. ### Действия @@ -118,6 +130,7 @@ python scripts/make_ltp.py plugins/my.plugin | Действие | Право | Где | Что делает | | --- | --- | --- | --- | | `{"feed.hide": true}` | `feed.hide` | `feed.item` | Видео не попадает в ленту. | +| `{"feed.keep": true}` | `feed.hide` | `feed.item` | Оставить видео, даже если другое правило его скрывает (белый список). | | `{"name.prefix": "текст"}` | `names` | `name.show` | Текст перед именем. | | `{"name.suffix": "текст"}` | `names` | `name.show` | Текст после имени. | | `{"name.replace": "текст"}` | `names` | `name.show` | Другое имя. | diff --git a/lihont/flags_patch.py b/lihont/flags_patch.py new file mode 100644 index 0000000..049f42a --- /dev/null +++ b/lihont/flags_patch.py @@ -0,0 +1,83 @@ +"""Let the settings screen override TikTok's server-side AB settings. + +TikTok reads every server flag through six static getters of +com.bytedance.ies.abmock.SettingsManager. Each getter still resolves TikTok's own value first; +the result is then passed to lihont.two.flags.Flags, which returns the value from the editor when +the key is there and the original value otherwise. Object getters are left alone: they are rare +and their types are not safe to rebuild from a text field. +""" + +from __future__ import annotations + +import re + +OWNER = "Lcom/bytedance/ies/abmock/SettingsManager;" +DEX = "classes4.dex" +HOOK = "Llihont/two/flags/Flags;" +MARKER = HOOK + +# signature -> (runtime method, parameter list, return type, move-result, return prefix) +METHODS = { + "LIZ(Ljava/lang/String;Z)Z": ("bool", "Ljava/lang/String;Z", "Z", "move-result", "return"), + "LIZIZ(Ljava/lang/String;D)D": ("precise", "Ljava/lang/String;D", "D", "move-result-wide", "return-wide"), + "LIZJ(Ljava/lang/String;F)F": ("decimal", "Ljava/lang/String;F", "F", "move-result", "return"), + "LJ(Ljava/lang/String;I)I": ("number", "Ljava/lang/String;I", "I", "move-result", "return"), + "LJFF(Ljava/lang/String;J)J": ("longer", "Ljava/lang/String;J", "J", "move-result-wide", "return-wide"), + "LJI(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;": ( + "text", "Ljava/lang/String;Ljava/lang/String;", "Ljava/lang/String;", "move-result-object", "return-object"), +} + +_METHOD = re.compile( + r"(?P
^\.method public static (?P[^\n]+)\n)(?P.*?)(?P^\.end method)", + re.M | re.S, +) +_RETURN = re.compile(r"(?m)^(?P\s*)return(?P-wide|-object)? (?P[vp]\d+)\s*$") + + +def _next(register: str) -> str: + return register[0] + str(int(register[1:]) + 1) + + +def rewrite(text: str) -> str: + if not re.search(r"^\.class [^\n]*" + re.escape(OWNER) + r"$", text, re.M): + raise ValueError("Not " + OWNER) + patched = 0 + + def method(match: re.Match) -> str: + nonlocal patched + signature = match.group("signature") + spec = METHODS.get(signature) + if spec is None: + return match.group(0) + helper, params, result, move, prefix = spec + body = match.group("body") + if HOOK in body: + raise ValueError("AB flag hook is already present in " + signature) + + def result_of(return_match: re.Match) -> str: + nonlocal patched + register = return_match.group("reg") + kind = return_match.group("kind") or "" + if kind == "-wide": + arguments = "{p0, %s, %s}" % (register, _next(register)) + else: + arguments = "{p0, %s}" % register + patched += 1 + return ( + "%sinvoke-static %s, %s->%s(%s)%s\n\n" + "%s%s %s\n" + "%s%s %s\n" + % (return_match.group("indent"), arguments, HOOK, helper, params, result, + return_match.group("indent"), move, register, + return_match.group("indent"), prefix, register) + ) + + new_body = _RETURN.sub(result_of, body) + if new_body == body: + raise ValueError("No return in " + signature) + return match.group("header") + new_body + match.group("end") + + rewritten = _METHOD.sub(method, text) + if not patched: + raise ValueError("No AB getter was patched") + return rewritten diff --git a/lihont/ghost_patch.py b/lihont/ghost_patch.py index 384174a..0f30a4b 100644 --- a/lihont/ghost_patch.py +++ b/lihont/ghost_patch.py @@ -20,6 +20,22 @@ HOOK = "Llihont/two/ghost/Ghost;->stories()Z" MARK_READ_CLASS = "LX/13pM;" MARK_READ_HOOK = "Llihont/two/ghost/Ghost;->messages()Z" +# Keep recalled chat messages visible: LX/13m4 is TikTok 47.1.3's IM Message model. +MESSAGE_CLASS = "LX/13m4;" +KEEP_RECALLED_HOOK = "Llihont/two/ghost/Ghost;->keepRecalled()Z" + +_IS_RECALLED = re.compile( + r"^\.method public isRecalled\(\)Z\n.*?^\.end method", + re.M | re.S) +_IS_RECALLED_FIRST = re.compile(r"^ invoke-virtual \{p0\}, LX/13m4;->getExt\(\)Ljava/util/Map;\n", re.M) +_RECALLED_LABEL = "lihont_keep_recalled" + +_MSG_STATUS = re.compile( + r"^\.method public getMessageStatus\(\)LX/13mT;\n.*?^\.end method", + re.M | re.S) +_MSG_STATUS_FIRST = re.compile(r"^ iget-object v0, p0, LX/13m4;->messageStatus:LX/13mT;\n", re.M) +_STATUS_LABEL = "lihont_status_avail" + _MARK_READ = re.compile( r"^\.method public final LIZIZ\(Ljava/lang/Long;Ljava/lang/String;LX/01h3;\)Ljava/lang/Object;\n.*?^\.end method", re.M | re.S) @@ -35,7 +51,51 @@ _LABEL = "lihont_story_view" def runtime_targets(): """Runtime methods the rewrites call, as they appear in a method table.""" - return [HOOK, MARK_READ_HOOK] + return [HOOK, MARK_READ_HOOK, KEEP_RECALLED_HOOK] + + +def rewrite_keep_recalled(text: str) -> str: + """Keep recalled messages visible by returning false from isRecalled() and AVAILABLE from getMessageStatus().""" + m_rec = _IS_RECALLED.search(text) + if m_rec is None: + raise ValueError("LX/13m4;->isRecalled()Z not found") + rec = m_rec.group() + if "Ghost;" in rec: + raise ValueError("Ghost hook already present in LX/13m4;->isRecalled") + if "s:is_recalled" not in rec or "s:recalled" not in rec: + raise ValueError("LX/13m4;->isRecalled has an unexpected shape") + first_rec = _IS_RECALLED_FIRST.search(rec) + if first_rec is None: + raise ValueError("LX/13m4;->isRecalled does not start with getExt()") + inj_rec = ( + " invoke-static {}, %s\n\n move-result v0\n\n if-eqz v0, :%s\n\n" + " const/4 v0, 0x0\n\n return v0\n\n :%s\n\n" + % (KEEP_RECALLED_HOOK, _RECALLED_LABEL, _RECALLED_LABEL) + ) + patched_rec = rec[:first_rec.start()] + inj_rec + rec[first_rec.start():] + out = text[:m_rec.start()] + patched_rec + text[m_rec.end():] + + m_st = _MSG_STATUS.search(out) + if m_st is not None: + st = m_st.group() + first_st = _MSG_STATUS_FIRST.search(st) + if first_st is not None and "LX/13mT;->RECALLED:LX/13mT;" in st and "Ghost;" not in st: + inj_st = ( + " sget-object v0, LX/13mT;->RECALLED:LX/13mT;\n\n" + " iget-object v1, p0, LX/13m4;->messageStatus:LX/13mT;\n\n" + " if-ne v1, v0, :%s\n\n" + " invoke-static {}, %s\n\n move-result v0\n\n if-eqz v0, :%s\n\n" + " sget-object v0, LX/13mT;->AVAILABLE:LX/13mT;\n\n return-object v0\n\n :%s\n\n" + % (_STATUS_LABEL, KEEP_RECALLED_HOOK, _STATUS_LABEL, _STATUS_LABEL) + ) + # Ensure .registers >= 3 in getMessageStatus so v1 never aliases p0 (this) + st_fixed, n_sub = re.subn(r"^([ \t]*)\.registers 2\b", r"\1.registers 3", st, count=1, flags=re.M) + if n_sub != 1: + raise ValueError("LX/13m4;->getMessageStatus expected indented .registers 2") + first_st = _MSG_STATUS_FIRST.search(st_fixed) + patched_st = st_fixed[:first_st.start()] + inj_st + st_fixed[first_st.start():] + out = out[:m_st.start()] + patched_st + out[m_st.end():] + return out def rewrite_mark_read(text: str) -> str: diff --git a/lihont/long_comments_patch.py b/lihont/long_comments_patch.py new file mode 100644 index 0000000..9e0ece9 --- /dev/null +++ b/lihont/long_comments_patch.py @@ -0,0 +1,42 @@ +"""Let the person raise TikTok's comment limit from 2200 to 10000 with a switch. + +TikTok 47.1.3 keeps the comment length in CommentCharLimitConfig.charLimit (2200 by default). The whole comment +UI reads it through one static method, LX/0sJH;->LIZIZ()I, which is used by the input, the publish view model and +the length checks. Its result passes through lihont.two.comments.LongComments.limit(I)I, which returns at least +10000 when the switch is on and TikTok's own value when it is off. The server still decides whether a long +comment is accepted; nothing here sends or claims anything. +""" + +from __future__ import annotations + +import re + +OWNER = "LX/0sJH;" +DEX = "classes25.dex" +HOOK = "Llihont/two/comments/LongComments;->limit(I)I" + +_METHOD = re.compile(r"^\.method public static final LIZIZ\(\)I\n.*?^\.end method", re.M | re.S) +_RETURN = re.compile(r"^ return v0\n", re.M) + + +def runtime_targets(): + """Runtime methods the rewrite calls, as they appear in a method table.""" + return [HOOK] + + +def rewrite_limit(text: str) -> str: + """Pass TikTok's own comment char limit through LongComments.limit just before it is returned.""" + match = _METHOD.search(text) + if match is None: + raise ValueError("LX/0sJH;->LIZIZ()I not found") + method = match.group() + if "LongComments" in method: + raise ValueError("Long comment hook already present in LX/0sJH;->LIZIZ") + # The shape that identifies the limit: the config object, its charLimit field, and one return of v0. + if "CommentCharLimitConfig;->charLimit:I" not in method or ".registers 1" not in method: + raise ValueError("LX/0sJH;->LIZIZ()I has an unexpected shape") + if len(_RETURN.findall(method)) != 1: + raise ValueError("LX/0sJH;->LIZIZ()I must return v0 exactly once") + patched = _RETURN.sub( + " invoke-static {v0}, %s\n\n move-result v0\n\n return v0\n" % HOOK, method, count=1) + return text[:match.start()] + patched + text[match.end():] diff --git a/lihont/play_patch.py b/lihont/play_patch.py new file mode 100644 index 0000000..08479f5 --- /dev/null +++ b/lihont/play_patch.py @@ -0,0 +1,114 @@ +"""Unlock PiP (picture-in-picture) and background playback in TikTok 47.1.3.""" + +from __future__ import annotations + +import re + +BG_OWNER = "LX/08LC;" +BG_DEX = "classes4.dex" +BG_IMPL_OWNER = "Lcom/ss/android/ugc/aweme/backgroundplay/service/BackgroundPlayServiceImpl;" +BG_IMPL_DEX = "classes37.dex" +BG_MANAGER_OWNER = "LX/1HoD;" +BG_MANAGER_DEX = "classes37.dex" + +PIP_GATE_OWNER = "LX/116m;" +PIP_GATE_DEX = "classes30.dex" +PIP_MGR_OWNER = "Lcom/ss/android/ugc/aweme/pipfeed/PipFeedManager;" +PIP_MGR_DEX = "classes37.dex" + +MAIN_OWNER = "Lcom/ss/android/ugc/aweme/main/MainActivity;" +MAIN_DEX = "classes25.dex" + +HOOK_BG_BOOL = "Llihont/two/play/PlayControl;->backgroundPlay(Z)Z" +HOOK_BG_MODE = "Llihont/two/play/PlayControl;->backgroundPlayMode(I)I" +HOOK_PIP = "Llihont/two/play/PlayControl;->pipGate(Z)Z" +HOOK_LEAVE = "Llihont/two/play/PlayControl;->onUserLeaveHint(Landroid/app/Activity;)V" +HOOK_PIP_CHANGED = "Llihont/two/play/PlayControl;->onPipChanged(Landroid/app/Activity;Z)V" + +_RETURN_Z = re.compile(r"(?m)^(?P\s*)return (?P[vp]\d+)\s*$") + + +def runtime_targets(): + return [HOOK_BG_BOOL, HOOK_BG_MODE, HOOK_PIP, HOOK_LEAVE, HOOK_PIP_CHANGED] + + +def _wrap_bool_method(text: str, sig: str, hook: str, owner: str) -> str: + pat = re.compile(r"(^\.method [^\n]*" + re.escape(sig) + r"\n)(.*?)(^\.end method)", re.M | re.S) + m = pat.search(text) + if m is None: + raise ValueError(f"{owner}->{sig} not found") + body = m.group(2) + if hook in body: + raise ValueError(f"{hook} already present in {owner}->{sig}") + new_body = _RETURN_Z.sub( + lambda r: ( + f"{r.group('indent')}invoke-static {{{r.group('reg')}}}, {hook}\n\n" + f"{r.group('indent')}move-result {r.group('reg')}\n" + f"{r.group('indent')}return {r.group('reg')}\n" + ), + body, + ) + if new_body == body: + raise ValueError(f"No return in {owner}->{sig}") + return text[:m.start(2)] + new_body + text[m.end(2):] + + +def rewrite_bg_gate(text: str) -> str: + text = _wrap_bool_method(text, "LIZ()I", HOOK_BG_MODE, BG_OWNER) + return _wrap_bool_method(text, "LIZIZ()Z", HOOK_BG_BOOL, BG_OWNER) + + +def rewrite_bg_impl(text: str) -> str: + return _wrap_bool_method( + text, + "LJIILIIL(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/ss/android/ugc/aweme/feed/model/Aweme;)Z", + HOOK_BG_BOOL, + BG_IMPL_OWNER, + ) + + +def rewrite_bg_manager(text: str) -> str: + text = _wrap_bool_method( + text, + "LIZIZ(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/ss/android/ugc/aweme/feed/model/Aweme;)Z", + HOOK_BG_BOOL, + BG_MANAGER_OWNER, + ) + return _wrap_bool_method( + text, + "LIZJ(Lcom/ss/android/ugc/aweme/feed/model/Aweme;Ljava/lang/String;Ljava/lang/String;)Z", + HOOK_BG_BOOL, + BG_MANAGER_OWNER, + ) + + +def rewrite_pip_gate(text: str) -> str: + return _wrap_bool_method(text, "LIZ()Z", HOOK_PIP, PIP_GATE_OWNER) + + +def rewrite_pip_manager(text: str) -> str: + return _wrap_bool_method(text, "isPipEnabled$pipfeed_release()Z", HOOK_PIP, PIP_MGR_OWNER) + + +def rewrite_main_leave(text: str) -> str: + if HOOK_LEAVE in text or HOOK_PIP_CHANGED in text or ".method protected onUserLeaveHint()V" in text: + raise ValueError("PiP lifecycle methods already present in MainActivity") + super_m = re.search(r"^\.super (L[^\n]+;)$", text, re.M) + if super_m is None: + raise ValueError("MainActivity .super not found") + parent = super_m.group(1) + methods = ( + "\n.method protected onUserLeaveHint()V\n" + " .registers 1\n\n" + f" invoke-super {{p0}}, {parent}->onUserLeaveHint()V\n\n" + f" invoke-static {{p0}}, {HOOK_LEAVE}\n\n" + " return-void\n" + ".end method\n\n" + ".method public onPictureInPictureModeChanged(ZLandroid/content/res/Configuration;)V\n" + " .registers 3\n\n" + f" invoke-super {{p0, p1, p2}}, {parent}->onPictureInPictureModeChanged(ZLandroid/content/res/Configuration;)V\n\n" + f" invoke-static {{p0, p1}}, {HOOK_PIP_CHANGED}\n\n" + " return-void\n" + ".end method\n" + ) + return text.rstrip() + "\n" + methods diff --git a/lihont/portmaps/47.7.2.json b/lihont/portmaps/47.7.2.json index 55415c2..ba2f562 100644 --- a/lihont/portmaps/47.7.2.json +++ b/lihont/portmaps/47.7.2.json @@ -382,7 +382,26 @@ "LX/0kmK;": "LX/06cu;", "LX/0kmL;": "LX/0BwL;", "LX/0L1b;": "LX/06n3;", - "LX/0NPd;": "LX/03zH;" + "LX/0NPd;": "LX/03zH;", + "LX/0M8l;": "LX/0mVA;", + "LX/0Kz4;": "LX/0lei;", + "LX/0KzQ;": "LX/0leH;", + "LX/0KzR;": "LX/0leJ;", + "LX/0LS4;": "LX/008B;", + "LX/0qkC;": "LX/0Ca9;", + "LX/0UVO;": "LX/0CrI;", + "LX/0Un7;": "LX/0hOI;", + "LX/04my;": "LX/0hGV;", + "LX/04mz;": "LX/0hGS;", + "LX/0Tus;": "LX/0hGW;", + "LX/0Tuu;": "LX/0hGR;", + "LX/13bW;": "LX/0ChX;", + "LX/0q1P;": "LX/0hFq;", + "LX/0Unf;": "LX/0hLE;", + "LX/0Unh;": "LX/0hLL;", + "LX/13k5;": "LX/0hFw;", + "LX/13uU;": "LX/0CaH;", + "LX/1D0u;": "LX/0CoT;" }, "doubtful": { "LX/09Pr;": [ @@ -803,11 +822,70 @@ "LX/0kmL;": "LX/0BwL;", "LX/0qvX;": "LX/1795;", "LX/0L1b;": "LX/06n3;", - "LX/0NPd;": "LX/03zH;" + "LX/0NPd;": "LX/03zH;", + "LX/0M8l;": "LX/0mVA; (found 2026-11-15 by method signatures: settings groups / padding)", + "LX/0Kz4;": "LX/0lei; (found 2026-11-15 by method signatures: settings groups / padding)", + "LX/0KzQ;": "LX/0leH; (found 2026-11-15 by method signatures: settings groups / padding)", + "LX/0KzR;": "LX/0leJ; (found 2026-11-15 by method signatures: settings groups / padding)", + "LX/0LS4;": "LX/008B; (found 2026-11-15 by method signatures: settings groups / padding)", + "LX/0qkC;": "LX/0Ca9; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/0UVO;": "LX/0CrI; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/0Un7;": "LX/0hOI; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/04my;": "LX/0hGV; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/04mz;": "LX/0hGS; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/0Tus;": "LX/0hGW; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/0Tuu;": "LX/0hGR; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/13bW;": "LX/0ChX; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/0q1P;": "LX/0hFq; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/0Unf;": "LX/0hLE; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/0Unh;": "LX/0hLL; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/13k5;": "LX/0hFw; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/13uU;": "LX/0CaH; (2026-11-15: IM send chain of FlameSender, by structure + propagation)", + "LX/1D0u;": "LX/0CoT; (2026-11-15: IM send chain of FlameSender, by structure + propagation)" }, "notes": { "LX/09Pr;": "comment_multi_photo_group experiment holder: same code (intValue == 2), found by the experiment string", "LX/0kmK;": "region lambda: Function1 over TelephonyManager returning getNetworkOperator()", - "LX/0kmL;": "region lambda: Function1 over TelephonyManager returning getSimOperator()" + "LX/0kmL;": "region lambda: Function1 over TelephonyManager returning getSimOperator()", + "literals": "2026-11-15: resource id names mapped by the code that loads them (scripts/port_idmap.py); t91, pyg, t_4, wqh have no twin -> fallbacks in code." + }, + "literals": { + "\"opq\"": "\"opn\"", + "\"gsa\"": "\"gud\"", + "\"ll8\"": "\"lk8\"", + "\"v29\"": "\"v43\"", + "\"dui\"": "\"dvf\"", + "\"klg\"": "\"klm\"", + "\"zkj\"": "\"zrf\"", + "\"u8p\"": "\"uac\"", + "\"eko\"": "\"el7\"", + "\"wnz\"": "\"wqo\"", + "\"l7j\"": "\"l70\"", + "\"bsd\"": "\"btm\"", + "\"k2b\"": "\"k2i\"", + "\"mu6\"": "\"mt3\"", + "\"kgv\"": "\"kh2\"", + "\"n2b\"": "\"n13\"", + "\"kl3\"": "\"kl9\"", + "\"f36\"": "\"f3o\"", + "\"f67\"": "\"f6n\"", + "\"ep_\"": "\"eps\"", + "\"eo1\"": "\"eog\"", + "\"l8_\"": "\"l7q\"", + "\"ejn\"": "\"ek4\"", + "\"iaw\"": "\"icu\"", + "\"m1s\"": "\"m0i\"", + "\"m36\"": "\"m1v\"", + "\"t6g\"": "\"t92\"", + "\"t_h\"": "\"tc9\"", + "\"t_k\"": "\"tcb\"", + "\"t_r\"": "\"td1\"", + "\"t_s\"": "\"td2\"", + "\"u8m\"": "\"ua_\"", + "\"bnr\"": "\"bpn\"", + "\"t91\"": "\"lihont_none_t91\"", + "\"pyg\"": "\"lihont_none_pyg\"", + "\"t_4\"": "\"lihont_none_t_4\"", + "\"wqh\"": "\"lihont_none_wqh\"" } } \ No newline at end of file diff --git a/lihont/sound_patch.py b/lihont/sound_patch.py new file mode 100644 index 0000000..6b0953d --- /dev/null +++ b/lihont/sound_patch.py @@ -0,0 +1,43 @@ +"""Restore audio that TikTok muted for a region or a copyright claim. + +The server puts the flag into `AwemeStatus.VideoMuteInfo.isMute`. PlayerController reads the +getter, and calls mute() or unmute() on the player. The rewrite sends the getter's value through +lihont.two.sound.Sound.unmute(Z)Z, which returns false while the switch is on, so the normal +unmute path runs. Nothing else in the model changes, and the switch can turn it off again. +""" + +from __future__ import annotations + +import re + +OWNER = "Lcom/ss/android/ugc/aweme/feed/model/AwemeStatus$VideoMuteInfo;" +DEX = "classes10.dex" +HOOK = "Llihont/two/sound/Sound;->unmute(Z)Z" +MARKER = "# lihont: sound" + +_METHOD = re.compile( + r"(?P
^\.method public final isMute\(\)Z\n)(?P.*?)(?P^\.end method)", + re.M | re.S, +) +_FIELD = OWNER + "->isMute:Z" + + +def rewrite(text: str) -> str: + match = _METHOD.search(text) + if match is None: + raise ValueError("VideoMuteInfo.isMute is missing") + body = match.group("body") + if MARKER in body: + raise ValueError("Sound hook is already present") + if _FIELD not in body: + raise ValueError("VideoMuteInfo.isMute no longer reads its own field") + body = ( + " .registers 2\n\n" + " .prologue\n" + " " + MARKER + "\n" + " iget-boolean v0, p0, " + _FIELD + "\n\n" + " invoke-static {v0}, " + HOOK + "\n\n" + " move-result v0\n\n" + " return v0\n" + ) + return text[:match.start("body")] + body + text[match.end("body"):] diff --git a/lihont/upgrade.py b/lihont/upgrade.py index e089b77..7838016 100644 --- a/lihont/upgrade.py +++ b/lihont/upgrade.py @@ -14,7 +14,7 @@ import subprocess from collections import defaultdict from pathlib import Path -from . import avatar_patch, badge_patch, bar_patch, comment_photos_patch, dexpatch, feed_patch, ghost_patch, media_patch, seekbar_patch, region, profile_features, settings_patch, theme_patch +from . import avatar_patch, badge_patch, bar_patch, comment_photos_patch, dexpatch, feed_patch, flags_patch, ghost_patch, long_comments_patch, media_patch, play_patch, seekbar_patch, region, profile_features, settings_patch, sound_patch, theme_patch from . import portmap from .apkzip import Apk from .axml import Axml @@ -335,6 +335,15 @@ def patch_comment_photos(apk: Apk, tools: Toolchain, room: Path, api: int) -> di return report +def patch_long_comments(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let a switch raise TikTok's 2200-character comment limit to 10000.""" + report = patch_class(apk, tools, room, api, long_comments_patch.DEX, long_comments_patch.OWNER, + "long-comments", long_comments_patch.rewrite_limit, + b"Llihont/two/comments/LongComments;") + report["hook"] = long_comments_patch.HOOK + return report + + def patch_ghost_stories(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: """Let a switch stop TikTok from reporting that a story was viewed.""" report = patch_class(apk, tools, room, api, "classes12.dex", ghost_patch.STORY_VIEW_CLASS, @@ -359,6 +368,14 @@ def patch_ghost_messages(apk: Apk, tools: Toolchain, room: Path, api: int) -> di return report +def patch_keep_recalled(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Keep recalled chat messages visible locally when keepRecalled is on.""" + report = patch_class(apk, tools, room, api, "classes31.dex", ghost_patch.MESSAGE_CLASS, + "keep-recalled", ghost_patch.rewrite_keep_recalled, b"Llihont/two/ghost/Ghost;") + report["hook"] = ghost_patch.KEEP_RECALLED_HOOK + return report + + def patch_language_card(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: """Let NativeTheme drop the language row's own card inside TikTok settings.""" report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.LANGUAGE_CLASS, @@ -419,6 +436,42 @@ def patch_feed(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: return report +def patch_sound(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let lihont.two.sound.Sound take the server's mute flag off region/copyright videos.""" + report = {"sound": patch_class(apk, tools, room, api, sound_patch.DEX, sound_patch.OWNER, "sound", + sound_patch.rewrite, b"Llihont/two/sound/Sound;")} + report["hook"] = sound_patch.HOOK + return report + + +def patch_flags(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let the A/B editor override TikTok's server settings reads.""" + report = {"settings": patch_class(apk, tools, room, api, flags_patch.DEX, flags_patch.OWNER, "ab-flags", + flags_patch.rewrite, b"Llihont/two/flags/Flags;")} + report["hook"] = flags_patch.HOOK + return report + + +def patch_play(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Unlock background playback and Picture-in-Picture (PiP) in TikTok.""" + marker = b"Llihont/two/play/PlayControl;" + return { + "bg_gate": patch_class(apk, tools, room, api, play_patch.BG_DEX, play_patch.BG_OWNER, + "play-bg-gate", play_patch.rewrite_bg_gate, marker), + "bg_impl": patch_class(apk, tools, room, api, play_patch.BG_IMPL_DEX, play_patch.BG_IMPL_OWNER, + "play-bg-impl", play_patch.rewrite_bg_impl, marker), + "bg_mgr": patch_class(apk, tools, room, api, play_patch.BG_MANAGER_DEX, play_patch.BG_MANAGER_OWNER, + "play-bg-mgr", play_patch.rewrite_bg_manager, marker), + "pip_gate": patch_class(apk, tools, room, api, play_patch.PIP_GATE_DEX, play_patch.PIP_GATE_OWNER, + "play-pip-gate", play_patch.rewrite_pip_gate, marker), + "pip_mgr": patch_class(apk, tools, room, api, play_patch.PIP_MGR_DEX, play_patch.PIP_MGR_OWNER, + "play-pip-mgr", play_patch.rewrite_pip_manager, marker), + "main_leave": patch_class(apk, tools, room, api, play_patch.MAIN_DEX, play_patch.MAIN_OWNER, + "play-leave", play_patch.rewrite_main_leave, marker), + "hooks": play_patch.runtime_targets(), + } + + def patch_avatars(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: """Let lihont.two.avatar.AvatarShapes cut every avatar to the shape chosen in the settings.""" marker = b"Llihont/two/avatar/AvatarShapes;" @@ -636,12 +689,17 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict: report["language_card"] = step("language_card", patch_language_card, apk, tools, room, api) report["settings_groups"] = step("settings_groups", patch_settings_groups, apk, tools, room, api) report["comment_photos"] = step("comment_photos", patch_comment_photos, apk, tools, room, api) + report["long_comments"] = step("long_comments", patch_long_comments, apk, tools, room, api) report["ghost_stories"] = step("ghost_stories", patch_ghost_stories, apk, tools, room, api) report["ghost_messages"] = step("ghost_messages", patch_ghost_messages, apk, tools, room, api) + report["keep_recalled"] = step("keep_recalled", patch_keep_recalled, apk, tools, room, api) report["seek_bar"] = step("seek_bar", patch_seek_bar, apk, tools, room, api) report["main_activity"] = step("main_activity", patch_main_activity, apk, tools, room, api) report["downloads"] = step("downloads", patch_downloads, apk, tools, room, api) report["feed"] = step("feed", patch_feed, apk, tools, room, api) + report["sound"] = step("sound", patch_sound, apk, tools, room, api) + report["ab_flags"] = step("ab_flags", patch_flags, apk, tools, room, api) + report["play"] = step("play", patch_play, apk, tools, room, api) report["badges"] = step("badges", patch_badges, apk, tools, room, api) report["avatars"] = step("avatars", patch_avatars, apk, tools, room, api) report["feature_flags"] = step("feature_flags", patch_feature_flags, apk, tools, room, api) @@ -664,7 +722,9 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict: + theme_patch.card_targets() + theme_patch.group_targets() + bar_patch.runtime_targets() + media_patch.runtime_targets() + feed_patch.runtime_targets() + badge_patch.runtime_targets() + avatar_patch.runtime_targets() - + comment_photos_patch.runtime_targets() + ghost_patch.runtime_targets() + + comment_photos_patch.runtime_targets() + long_comments_patch.runtime_targets() + + ghost_patch.runtime_targets() + play_patch.runtime_targets() + + [sound_patch.HOOK, "Llihont/two/flags/Flags;->bool(Ljava/lang/String;Z)Z"] + seekbar_patch.runtime_targets() if t not in merged] if absent: raise ValueError("Hooks have no runtime target: " + ", ".join(absent)) diff --git a/scripts/deploy_members.py b/scripts/deploy_members.py index 6b96ac0..f427e06 100644 --- a/scripts/deploy_members.py +++ b/scripts/deploy_members.py @@ -30,7 +30,7 @@ SERVICE = "lihont-members" HEALTH = "http://127.0.0.1:18746/members/v1/health" SOURCE = Path(__file__).resolve().parents[1] / "services" / "members" # every python file of the service that exists here (the moderation bot is not part of the public source, so it is simply absent there) -FILES = tuple(name for name in ("server.py", "ai.py", "community.py", "moderation.py", "modbot.py", "catalog.py", "report.py", "accounts.py", "authbot.py") if (SOURCE / name).is_file()) +FILES = tuple(name for name in ("server.py", "ai.py", "community.py", "moderation.py", "modbot.py", "catalog.py", "report.py", "accounts.py", "authbot.py", "lihonc.py", "codegate.py", "music.py", "dub.py") if (SOURCE / name).is_file()) SSH = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", HOST] diff --git a/sdk/lihont-ltp/README.md b/sdk/lihont-ltp/README.md index 1782e4f..c9b594d 100644 --- a/sdk/lihont-ltp/README.md +++ b/sdk/lihont-ltp/README.md @@ -63,6 +63,13 @@ ltp new "Мой плагин" --author "Твой ник" | `weekday("fri")`, `weekday("sat", "sun")` | день недели (`mon tue wed thu fri sat sun` или `пн вт ср чт пт сб вс`) | | `morning`, `day`, `evening`, `night` | готовые части суток (6–12, 12–18, 18–23, 23–6) | | `friday`, `weekend` | пятница, выходные | +| `shorter(15)`, `longer(60)` | видео короче / длиннее N секунд | +| `likes(min=1000)`, `comments(min=10)`, `shares(min=5)`, `plays(min=10000)` | числа видео; можно `max=...` или обе границы | +| `fresh(7)`, `older(30)` | видео не старше / не моложе N дней | +| `followers(min=100000)` | у автора не меньше N подписчиков | +| `verified`, `photo`, `liked` | автор с галочкой / это фото / вы уже лайкнули | +| `music("phonk", "jazz")` | в названии или у автора музыки есть слово | +| `chance(10)` | правило срабатывает с вероятностью 10% | | `a & b` | и то, и другое | | `a \| b` | или то, или другое | | `~a` | наоборот («не») | @@ -74,6 +81,7 @@ ltp new "Мой плагин" --author "Твой ник" | пишешь | значит | где работает | |---|---|---| | `hide` | скрыть видео | `video` | +| `keep` | оставить видео, даже если другое правило его скрывает | `video` | | `say("текст")` | показать подсказку (по умолчанию не чаще 3 раз в день: `limit=1`) | везде | | `before("⭐ ")` | дописать перед именем | `name` | | `after(" ☀️")` | дописать после имени | `name` | @@ -85,6 +93,24 @@ ltp new "Мой плагин" --author "Твой ник" Файл кладёшь рядом со скриптом (или в папку `files`). Размер файла до 400 КБ, всего до 8 файлов. `like` ставит лайк видео по нажатию на картинку: защитник это подсветит красным. +## Умная лента: числа, музыка и белый список + +```python +plugin.video(shorter(7), hide) # короче 7 секунд — мимо +plugin.video(older(90) & likes(max=100), hide) # старше 90 дней и меньше 100 лайков +plugin.video(followers(max=50), hide) # у автора меньше 50 подписчиков +plugin.video(music("phonk"), hide) # в музыке есть «phonk» + +plugin.video(always, hide) # всё скрыть... +plugin.video(hashtag("cats", "коты"), keep) # ...кроме котов +``` + +`keep` сильнее `hide`: если видео подходит хотя бы под одно правило с `keep`, оно останется, даже когда другое +правило просит его скрыть. Так делают белый список. + +Числа — это `duration` (секунды), `likes`, `comments`, `shares`, `plays`, `age` (дни с публикации) и `followers` +(у автора). Границы включительные. Если TikTok не сообщил число, условие считается ложным. + ## Скачать файл из интернета ```python diff --git a/sdk/lihont-ltp/examples/10_smart_feed.py b/sdk/lihont-ltp/examples/10_smart_feed.py new file mode 100644 index 0000000..5008025 --- /dev/null +++ b/sdk/lihont-ltp/examples/10_smart_feed.py @@ -0,0 +1,10 @@ +from lihont_ltp import * + +plugin = Plugin("Умная лента", author="Вася", description="Убирает короткие, старые и тихие видео") + +plugin.video(shorter(7), hide) # короче 7 секунд +plugin.video(older(90) & likes(max=100), hide) # старше 90 дней и меньше 100 лайков +plugin.video(followers(max=50), hide) # у автора меньше 50 подписчиков +plugin.video(music("phonk"), hide) # музыка — фонк + +plugin.save() diff --git a/sdk/lihont-ltp/examples/11_white_list.py b/sdk/lihont-ltp/examples/11_white_list.py new file mode 100644 index 0000000..35afaca --- /dev/null +++ b/sdk/lihont-ltp/examples/11_white_list.py @@ -0,0 +1,8 @@ +from lihont_ltp import * + +plugin = Plugin("Только коты", author="Вася", description="Прячет всё, кроме видео про котов") + +plugin.video(always, hide) # всё скрыть... +plugin.video(hashtag("cats", "коты") | author("catlover"), keep) # ...кроме котов + +plugin.save() diff --git a/sdk/lihont-ltp/lihont_ltp/__init__.py b/sdk/lihont-ltp/lihont_ltp/__init__.py index 4b1163f..774ce66 100644 --- a/sdk/lihont-ltp/lihont_ltp/__init__.py +++ b/sdk/lihont-ltp/lihont_ltp/__init__.py @@ -7,17 +7,20 @@ plugin.save() """ -from .core import (Plugin, account, after, all_of, always, any_of, author, before, between, bounce, day, download, evening, - friday, hashtag, hide, like, me, morning, night, person, picture, rename, say, sound, wander, weekday, - weekend, wiggle, word, style, confetti, buzz) +from .core import (Plugin, account, after, all_of, always, any_of, author, before, between, bounce, chance, comments, day, + download, evening, followers, fresh, friday, hashtag, hide, keep, like, liked, likes, longer, me, + morning, music, night, older, person, photo, picture, plays, rename, say, shares, shorter, sound, + wander, weekday, weekend, verified, wiggle, word, style, confetti, buzz) from .errors import LtpError -__version__ = "0.1.0" +__version__ = "0.2.0" __all__ = [ "Plugin", "LtpError", "word", "hashtag", "author", "person", "account", "between", "weekday", "all_of", "any_of", "me", "always", "morning", "day", "evening", "night", "friday", "weekend", - "hide", "say", "before", "after", "rename", "style", "picture", "sound", "like", "wiggle", "confetti", "buzz", - "download", "bounce", "wander", + "shorter", "longer", "likes", "comments", "shares", "plays", "followers", "fresh", "older", "music", "chance", + "verified", "photo", "liked", + "hide", "keep", "say", "before", "after", "rename", "style", "picture", "sound", "like", "wiggle", "confetti", + "buzz", "download", "bounce", "wander", ] diff --git a/sdk/lihont-ltp/lihont_ltp/core.py b/sdk/lihont-ltp/lihont_ltp/core.py index 425c307..19c9527 100644 --- a/sdk/lihont-ltp/lihont_ltp/core.py +++ b/sdk/lihont-ltp/lihont_ltp/core.py @@ -146,6 +146,86 @@ def account(*names): return _Leaf("account", _strings(names, "account")) +def _bounds(name, low, high, min_value, max_value): + if min_value is None and max_value is None: + raise LtpError("%s(...): назови хотя бы одну границу, например %s(min=10)" % (name, name)) + bounds = [] + for value in (min_value, max_value): + if value is None: + bounds.append(None) + continue + if isinstance(value, bool) or not isinstance(value, int): + raise LtpError("%s(...): граница — целое число" % name) + if not low <= value <= high: + raise LtpError("%s(...): от %d до %d" % (name, low, high)) + bounds.append(value) + if bounds[0] is not None and bounds[1] is not None and bounds[0] > bounds[1]: + raise LtpError("%s(...): «от» больше, чем «до»" % name) + return _Leaf(name, bounds) + + +def shorter(seconds): + """Видео короче N секунд: shorter(15).""" + return _bounds("duration", 0, 86400, None, seconds) + + +def longer(seconds): + """Видео длиннее N секунд: longer(60).""" + return _bounds("duration", 0, 86400, seconds, None) + + +def likes(min=None, max=None): + """Лайков на видео: likes(min=1000), likes(max=5) или likes(min=100, max=1000).""" + return _bounds("likes", 0, 2000000000, min, max) + + +def comments(min=None, max=None): + """Комментариев на видео: comments(min=100).""" + return _bounds("comments", 0, 2000000000, min, max) + + +def shares(min=None, max=None): + """Репостов видео: shares(min=10).""" + return _bounds("shares", 0, 2000000000, min, max) + + +def plays(min=None, max=None): + """Просмотров видео: plays(min=10000).""" + return _bounds("plays", 0, 2000000000, min, max) + + +def followers(min=None, max=None): + """Подписчиков у автора: followers(min=100000).""" + return _bounds("followers", 0, 2000000000, min, max) + + +def fresh(days): + """Видео не старше N дней: fresh(7).""" + return _bounds("age", 0, 36500, None, days) + + +def older(days): + """Видео не моложе N дней: older(30).""" + return _bounds("age", 0, 36500, days, None) + + +def music(*words): + """В названии или у автора музыки есть любое из слов: music("phonk", "jazz").""" + return _Leaf("music", _strings(words, "music")) + + +def chance(percent): + """Правило срабатывает с вероятностью N процентов: chance(10).""" + if isinstance(percent, bool) or not isinstance(percent, int) or not 1 <= percent <= 100: + raise LtpError("chance(...): целое число от 1 до 100") + return _Leaf("chance", percent) + + +verified = _Leaf("verified", True) +photo = _Leaf("photo", True) +liked = _Leaf("liked", True) + + def between(start, end): """Время суток: between("22:00", "07:00") (можно через полночь).""" return _Leaf("time", "%s-%s" % (start, end)) @@ -217,6 +297,7 @@ class Tap: hide = Action("feed.hide", True, "hide") +keep = Action("feed.keep", True, "keep") wiggle = Tap("animate") like = Tap("like") confetti = Tap("confetti") diff --git a/sdk/lihont-ltp/lihont_ltp/guard.py b/sdk/lihont-ltp/lihont_ltp/guard.py index 1474559..aabad20 100644 --- a/sdk/lihont-ltp/lihont_ltp/guard.py +++ b/sdk/lihont-ltp/lihont_ltp/guard.py @@ -48,6 +48,33 @@ def _nested(node): return "(" + text + ")" if next(iter(node)) in ("all", "any") else text +def _bounds_says(key, value): + start, end = value + if key == "age": + if start is not None and end is not None: + return "видео возрастом от %d до %d дней" % (start, end) + if start is not None: + return "видео не моложе %d дней" % start + return "видео не старше %d дней" % end + if start is not None and end is not None: + span = "от %d до %d" % (start, end) + elif start is not None: + span = "не меньше %d" % start + else: + span = "не больше %d" % end + if key == "duration": + return "видео длительностью %s секунд" % span + if key == "likes": + return "лайков %s" % span + if key == "comments": + return "комментариев %s" % span + if key == "shares": + return "репостов %s" % span + if key == "plays": + return "просмотров %s" % span + return "подписчиков у автора %s" % span + + def says_condition(node): key, value = next(iter(node.items())) if key == "text": @@ -67,6 +94,18 @@ def says_condition(node): return "время с %s до %s" % (_clock(start), _clock(end)) if key == "weekday": return "в дни: " + ", ".join(DAYS[d] for d in sorted(set(int(d) for d in value))) + if key in ("duration", "likes", "comments", "shares", "plays", "age", "followers"): + return _bounds_says(key, value) + if key == "verified": + return "автор с галочкой" + if key == "photo": + return "это фото, а не видео" + if key == "liked": + return "вы уже лайкнули это видео" + if key == "music": + return "в музыке есть " + _items(_words(value), "«", "»") + if key == "chance": + return "с вероятностью %d%%" % value if key in ("all", "any"): return (" и " if key == "all" else " или ").join(_nested(part) for part in value) return "не " + _nested(value) # not @@ -75,7 +114,8 @@ def says_condition(node): def selects(node): """Выбирает ли условие видео или людей по тому, что они такое, а не только по времени.""" key, value = next(iter(node.items())) - if key in ("text", "hashtag", "author", "uid"): + if key in ("text", "hashtag", "author", "uid", "duration", "likes", "comments", "shares", "plays", "age", + "followers", "verified", "photo", "liked", "music"): return True if key == "all": return any(selects(part) for part in value) @@ -88,6 +128,8 @@ def says_action(action): key, value = next(iter(action.items())) if key == "feed.hide": return "скрыть видео" + if key == "feed.keep": + return "оставить видео, даже если другие правила его скрывают" if key == "name.prefix": return "дописать «%s» перед именем" % value if key == "name.suffix": @@ -209,6 +251,9 @@ def check(manifest, asset_names=()): elif once("hide"): watch.append("Скрывает видео из ленты по условиям правил. " "Что и когда скрыто, видно в журнале плагина.") + elif key == "feed.keep": + if once("keep"): + calm.append("Оставляет видео, даже если другие правила просят его скрыть.") elif key == "name.replace": if not picks: careful.append("Правило «%s» подменяет все имена на экране на «%s»." % (title, value)) diff --git a/sdk/lihont-ltp/lihont_ltp/ru.py b/sdk/lihont-ltp/lihont_ltp/ru.py index ac7d40c..af6f2a5 100644 --- a/sdk/lihont-ltp/lihont_ltp/ru.py +++ b/sdk/lihont-ltp/lihont_ltp/ru.py @@ -8,10 +8,14 @@ from . import core from .core import (account as аккаунт, after as после, all_of as все_условия, always as всегда, any_of as любое_условие, author as автор, before as перед, between as между, bounce as туда_сюда, wander as бродит, - day as день, download as скачать, evening as вечер, - friday as пятница, style as вид_имени, confetti as конфетти, buzz as вибро, hashtag as хэштег, hide as скрыть, like as лайк, me as я, morning as утро, - night as ночь, person as человек, picture as картинка, rename as переименовать, say as сказать, - sound as звук, weekday as день_недели, weekend as выходные, wiggle as качнуться, word as слово) + chance as шанс, comments as комментарии, day as день, download as скачать, evening as вечер, + followers as подписчики, fresh as свежее, friday as пятница, style as вид_имени, confetti as конфетти, + buzz as вибро, hashtag as хэштег, hide as скрыть, keep as оставить, like as лайк, liked as лайкнутое, + likes as лайки, longer as дольше, me as я, morning as утро, music as музыка, night as ночь, + older as старше, person as человек, photo as фото, picture as картинка, plays as просмотры, + rename as переименовать, say as сказать, shares as репосты, shorter as короче, sound as звук, + verified as проверенный, weekday as день_недели, weekend as выходные, wiggle as качнуться, + word as слово) class Плагин(core.Plugin): diff --git a/sdk/lihont-ltp/lihont_ltp/validate.py b/sdk/lihont-ltp/lihont_ltp/validate.py index 9ce4e02..30a6457 100644 --- a/sdk/lihont-ltp/lihont_ltp/validate.py +++ b/sdk/lihont-ltp/lihont_ltp/validate.py @@ -25,8 +25,12 @@ MAX_FILE = 1024 * 1024 TRIGGERS = ("feed.item", "name.show", "screen.show") RIGHTS = ("feed.hide", "names", "ui.notice", "ui.overlay", "ui.sound", "feed.like", "net.download", "ui.theme", "ui.icons") -ACTIONS = ("feed.hide", "name.prefix", "name.suffix", "name.replace", "name.style", "notice", "overlay", "download") +ACTIONS = ("feed.hide", "feed.keep", "name.prefix", "name.suffix", "name.replace", "name.style", "notice", "overlay", + "download") NAME_STYLES = ("upper", "lower", "reverse", "wave", "spaced") +NUMBERS = {"duration": 86400, "likes": 2000000000, "comments": 2000000000, "shares": 2000000000, + "plays": 2000000000, "age": 36500, "followers": 2000000000} +FLAGS = ("verified", "photo", "liked") TAPS = ("animate", "sound", "like", "confetti", "buzz") OVERLAY_KEYS = ("image", "size", "alpha", "right", "bottom", "movable", "tap", "sound", "pet", "animate_ms", "walk") WALK_MODES = ("bounce", "wander") @@ -82,6 +86,20 @@ def _integer(value, low, high, where): return int(value) +def _bounds(value, high, where): + """Пара [от, до]; вместо границы можно null, хотя бы одна граница нужна.""" + if not isinstance(value, list) or len(value) != 2: + raise LtpError("%s: нужно [от, до], вместо границы можно null" % where) + out = [] + for item in value: + out.append(None if item is None else _integer(item, 0, high, where)) + if out[0] is None and out[1] is None: + raise LtpError("%s: назови хотя бы одну границу" % where) + if out[0] is not None and out[1] is not None and out[0] > out[1]: + raise LtpError("%s: «от» больше, чем «до»" % where) + return out + + def _words(value, max_items, max_len, where): if not isinstance(value, list) or not value: raise LtpError("%s: нужен непустой список" % where) @@ -127,6 +145,15 @@ def check_condition(node, where, depth=0, counter=None): raise LtpError("%s: от 1 до 7 дней" % here) for day in value: _integer(day, 1, 7, here) + elif key in NUMBERS: + _bounds(value, NUMBERS[key], here) + elif key in FLAGS: + if value is not True: + raise LtpError("%s: нужно true (для «не» поставь ~ перед условием)" % here) + elif key == "music": + _words(value, 64, 80, here) + elif key == "chance": + _integer(value, 1, 100, here) elif key in ("all", "any"): if not isinstance(value, list) or not 1 <= len(value) <= 16: raise LtpError("%s: внутри от 1 до 16 условий" % here) @@ -145,9 +172,9 @@ def check_action(node, trigger, where): here = "%s, действие «%s»" % (where, key) if key not in ACTIONS: raise LtpError("%s: такого действия нет" % here) - if key == "feed.hide": + if key in ("feed.hide", "feed.keep"): if trigger != "feed.item": - raise LtpError("«скрыть» работает только в правилах про видео: %s" % where) + raise LtpError("«скрыть» и «оставить» работают только в правилах про видео: %s" % where) if value is not True: raise LtpError("%s: нужно true" % here) elif key == "name.style": @@ -281,7 +308,7 @@ def check_download(node, where): def rights_of(action): key = next(iter(action)) - if key == "feed.hide": + if key in ("feed.hide", "feed.keep"): return ["feed.hide"] if key == "download": return ["net.download"] diff --git a/sdk/lihont-ltp/pyproject.toml b/sdk/lihont-ltp/pyproject.toml index 2ade063..2985cd7 100644 --- a/sdk/lihont-ltp/pyproject.toml +++ b/sdk/lihont-ltp/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "lihont-ltp" -version = "0.1.0" +version = "0.2.0" description = "Пиши плагины для LihonT обычным Python: просто, с проверкой и защитником" readme = "README.md" requires-python = ">=3.8" diff --git a/services/members/codegate.py b/services/members/codegate.py new file mode 100644 index 0000000..7bd09ea --- /dev/null +++ b/services/members/codegate.py @@ -0,0 +1,407 @@ +"""The gate of LihonC, the coding agent (LihonC IDE, код.нейронка.рус): the program on a person's computer sends one turn of its talk +here, this service asks the free models through the LihonC router (lihonc.py) and sends the answer back. + +There is no sign-in (Russian law allows sign-in only through Russian services, and a free tool does not need it). Instead every call +carries two things the program makes itself: the installation (a random secret made at the first start) and the device (a hash of +stable facts of the computer: the raw facts never leave it). The address the call came from is the third. Each of the three has a +budget of tokens a day (the address a bigger one, many people share an address of a mobile operator), and the whole server has one too. + +Going around the budget: a device that has used up its day and then comes from another address or with a new installation is warned +once ("the budget belongs to the device, another network does not help"); the second time the device, its installations and the +addresses it used that day are shut out (the device and installations for a week, the addresses for a day, so that neighbours behind +the same operator are not punished for long). + +What is kept: counters and these hashes only (the address is kept as a salted hash), never the talk. The arena model (DeepSeek +through Coarena, which keeps what is sent to it) needs consent first, remembered per device. The keys of the providers live in this +service's environment. +""" +from __future__ import annotations + +import hashlib +import json +import os +import re +import secrets +import time + +try: + import lihonc +except ImportError: # imported as part of a package + from . import lihonc + +MOSCOW = 3 * 3600 +DEVICE_TOKENS = int(os.environ.get("CODE_DAILY_TOKENS", "500000")) # per device (and per installation) a day +ADDRESS_TOKENS = int(os.environ.get("CODE_ADDRESS_TOKENS", "2000000")) # per address a day: many people may share one +SERVER_TOKENS = int(os.environ.get("CODE_SERVER_TOKENS", "20000000")) # for everybody together a day +OWNER_TOKENS = 20_000_000 +WEIGHT = {"low": 1.0, "medium": 1.5, "high": 3.0} # thinking harder costs more of the budget +BAN_DEVICE = 7 * 86400 +BAN_ADDRESS = 86400 +BODY = 2_500_000 # one turn with the whole talk so far and up to three small pictures +MAX_MESSAGES = 400 +ROLES = ("system", "user", "assistant", "tool") +PASSED = ("messages", "tools", "tool_choice", "temperature", "max_tokens") +HEX64 = re.compile(r"[a-f0-9]{64}\Z") + + +class Who: + """The three hashed names of one call.""" + + def __init__(self, installation: str, device: str, address: str): + self.installation = installation + self.device = device + self.address = address + + def subjects(self): + return tuple(subject for subject in (self.installation, self.device, self.address) if subject) + + +class Stream: + """An answer that is still being written: the server sends each event as it comes (server-sent events).""" + + def __init__(self, events): + self.events = events + + def __iter__(self): + return iter(self.events) + + def close(self): + self.events.close() + + +class CodeGate: + def __init__(self, registry, keys: dict | None = None, router=None): + self.r = registry + self.router = router or lihonc.Router(keys if keys is not None else lihonc.load_keys(os.environ.get("LIHONC_KEYS_FILE"))) + self.operations = {"code_status": self.status, "code_chat": self.chat, "code_consent": self.consent} + with self.r.connect() as db: + db.execute("CREATE TABLE IF NOT EXISTS code_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)") + db.execute("CREATE TABLE IF NOT EXISTS code_use (subject TEXT NOT NULL, day TEXT NOT NULL, kind TEXT NOT NULL, " + "used INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(subject, day, kind))") + db.execute("CREATE TABLE IF NOT EXISTS code_seen (device TEXT NOT NULL, day TEXT NOT NULL, subject TEXT NOT NULL, " + "after_limit INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(device, day, subject))") + db.execute("CREATE TABLE IF NOT EXISTS code_strikes (device TEXT NOT NULL, day TEXT NOT NULL, strikes INTEGER NOT NULL, " + "PRIMARY KEY(device, day))") + db.execute("CREATE TABLE IF NOT EXISTS code_bans (subject TEXT PRIMARY KEY, until INTEGER NOT NULL, reason TEXT NOT NULL)") + db.execute("CREATE TABLE IF NOT EXISTS code_consents (device TEXT PRIMARY KEY, accepted_at INTEGER NOT NULL)") + row = db.execute("SELECT value FROM code_meta WHERE key='salt'").fetchone() + if row is None: + db.execute("INSERT INTO code_meta(key, value) VALUES('salt', ?)", (secrets.token_hex(16),)) + row = db.execute("SELECT value FROM code_meta WHERE key='salt'").fetchone() + self.salt = row[0] + + def call(self, operation, payload): + return self.operations[operation](payload) + + # ---- who is calling --------------------------------------------------------------------------------------------------- + + def _hash(self, kind: str, value: str) -> str: + return kind + ":" + hashlib.sha256((self.salt + kind + value).encode("utf-8")).hexdigest()[:32] + + def _who(self, p) -> Who: + installation, device = p.get("installation"), p.get("device") + if not isinstance(installation, str) or not HEX64.fullmatch(installation): + raise ValueError("Invalid installation code") + if not isinstance(device, str) or not HEX64.fullmatch(device): + raise ValueError("Invalid device") + address = str(p.get("_ip") or "").strip() + # behind a proxy that hides the address every caller looks like this computer: then the address is not counted or banned, + # or one person could shut everybody out + local = not address or address in ("-", "::1", "localhost") or address.startswith("127.") + return Who(self._hash("i", installation), self._hash("d", device), None if local else self._hash("a", address)) + + def _owner(self, who: Who) -> bool: + owners = [value.strip() for value in os.environ.get("CODE_OWNER_DEVICES", "").split(",") if value.strip()] + return any(self._hash("d", value) == who.device for value in owners) + + # ---- counters --------------------------------------------------------------------------------------------------------- + + def _day(self) -> str: + return time.strftime("%Y-%m-%d", time.gmtime(self.r.clock() + MOSCOW)) + + def _now(self) -> int: + return int(self.r.clock()) + + def _used(self, subject: str, kind: str = "tokens") -> int: + with self.r.connect() as db: + row = db.execute("SELECT used FROM code_use WHERE subject=? AND day=? AND kind=?", (subject, self._day(), kind)).fetchone() + return row[0] if row else 0 + + def _server_used(self) -> int: + with self.r.connect() as db: + row = db.execute("SELECT COALESCE(SUM(used), 0) FROM code_use WHERE day=? AND kind='tokens' AND subject LIKE 'd:%'", + (self._day(),)).fetchone() + return row[0] + + def _limit(self, who: Who) -> int: + return OWNER_TOKENS if self._owner(who) else DEVICE_TOKENS + + def _spend(self, who: Who, tokens: int) -> None: + day = self._day() + with self.r.connect() as db: + old = time.strftime("%Y-%m-%d", time.gmtime(self.r.clock() + MOSCOW - 7 * 86400)) + for table in ("code_use", "code_seen", "code_strikes"): + db.execute("DELETE FROM %s WHERE day < ?" % table, (old,)) + for subject in who.subjects(): + for kind, amount in (("tokens", tokens), ("calls", 1)): + db.execute("INSERT INTO code_use(subject, day, kind, used) VALUES(?,?,?,?) " + "ON CONFLICT(subject, day, kind) DO UPDATE SET used = used + excluded.used", (subject, day, kind, amount)) + + @staticmethod + def _tokens(completion: dict, body: dict) -> int: + usage = completion.get("usage") if isinstance(completion.get("usage"), dict) else {} + total = usage.get("total_tokens") + if isinstance(total, int) and total > 0: + return total + size = len(json.dumps(body.get("messages", []), ensure_ascii=False)) + len(json.dumps(completion.get("choices", []), ensure_ascii=False)) + return max(1, size // 3) # a provider that does not say: about three characters a token + + # ---- bans and going around the budget --------------------------------------------------------------------------------- + + def _banned(self, who: Who) -> int: + with self.r.connect() as db: + marks = ",".join("?" * len(who.subjects())) + row = db.execute("SELECT MAX(until) FROM code_bans WHERE subject IN (%s) AND until > ?" % marks, + (*who.subjects(), self._now())).fetchone() + return row[0] or 0 + + def _remember(self, who: Who, over: bool) -> tuple[bool, bool]: + """Notes the installation and the address of the device today. Returns (new installation, new address) among those seen + after the device used up its day, which is what going around looks like.""" + day = self._day() + fresh = [] + with self.r.connect() as db: + for subject in (who.installation, who.address): + if not subject: + fresh.append(False) + continue + row = db.execute("SELECT after_limit FROM code_seen WHERE device=? AND day=? AND subject=?", (who.device, day, subject)).fetchone() + known_after = db.execute("SELECT COUNT(*) FROM code_seen WHERE device=? AND day=? AND after_limit=1 AND subject LIKE ?", + (who.device, day, subject[:2] + "%")).fetchone()[0] + fresh.append(over and known_after > 0 and (row is None or row[0] == 0)) + if row is None: + db.execute("INSERT INTO code_seen(device, day, subject, after_limit) VALUES(?,?,?,?)", (who.device, day, subject, 1 if over else 0)) + elif over and row[0] == 0: + db.execute("UPDATE code_seen SET after_limit=1 WHERE device=? AND day=? AND subject=?", (who.device, day, subject)) + return fresh[0], fresh[1] + + def _strike(self, who: Who) -> int: + day = self._day() + with self.r.connect() as db: + db.execute("INSERT INTO code_strikes(device, day, strikes) VALUES(?,?,1) " + "ON CONFLICT(device, day) DO UPDATE SET strikes = strikes + 1", (who.device, day)) + return db.execute("SELECT strikes FROM code_strikes WHERE device=? AND day=?", (who.device, day)).fetchone()[0] + + def _ban(self, who: Who, reason: str) -> int: + """Shuts out the device, every installation and address it used today. Returns when the device may come back.""" + now, day = self._now(), self._day() + with self.r.connect() as db: + subjects = [row[0] for row in db.execute("SELECT subject FROM code_seen WHERE device=? AND day=?", (who.device, day))] + for subject in (set(subjects) | {who.device, who.installation, who.address}) - {None}: + until = now + (BAN_ADDRESS if subject.startswith("a:") else BAN_DEVICE) + db.execute("INSERT INTO code_bans(subject, until, reason) VALUES(?,?,?) " + "ON CONFLICT(subject) DO UPDATE SET until=MAX(until, excluded.until), reason=excluded.reason", (subject, until, reason)) + return now + BAN_DEVICE + + def unban(self, device_hash_prefix: str) -> int: + """For the owner from the server's command line: lifts the bans of the device whose hash starts with this, and of the + installations and addresses it used. Returns how many devices were let back.""" + if len(device_hash_prefix) < 6: + raise ValueError("Give at least six characters of the device hash") + with self.r.connect() as db: + devices = [row[0] for row in db.execute("SELECT subject FROM code_bans WHERE subject LIKE ?", ("d:" + device_hash_prefix + "%",))] + for device in devices: + linked = [row[0] for row in db.execute("SELECT DISTINCT subject FROM code_seen WHERE device=?", (device,))] + for subject in [device] + linked: + db.execute("DELETE FROM code_bans WHERE subject=?", (subject,)) + return len(devices) + + def _gate(self, who: Who): + """None when the call may go on, else the error to answer with.""" + until = self._banned(who) + if until: + return self._banned_error(who, until) + if self._owner(who): + self._remember(who, False) + return None + limit = self._limit(who) + over = self._used(who.device) >= limit or self._used(who.installation) >= limit + new_installation, new_address = self._remember(who, over) + if over: + if new_installation or new_address: + if self._strike(who) >= 2: + return self._banned_error(who, self._ban(who, "going around the daily budget")) + return self._error("device_limit", "Дневной лимит этого компьютера исчерпан. Он общий для устройства: другая сеть, VPN " + "или переустановка не помогут, а повторная попытка закроет доступ на неделю. Сброс в 00:00 по Москве.") + return self._error("daily_limit", "Дневной лимит (%d тыс. токенов) исчерпан. Сброс в 00:00 по Москве." % (limit // 1000)) + if who.address and self._used(who.address) >= ADDRESS_TOKENS: + return self._error("address_limit", "С этого интернета сегодня уже потрачен общий лимит. Сброс в 00:00 по Москве.") + if self._server_used() >= SERVER_TOKENS: + return self._error("server_limit", "Бесплатный запас LihonC на сегодня закончился у всех. Сброс в 00:00 по Москве.") + return None + + def _banned_error(self, who: Who, until: int) -> dict: + code = who.device[2:10] + return self._error("banned", "Доступ к LihonC закрыт до %s (МСК): обход лимитов. Если это ошибка, напиши в @lihont и пришли код " + "устройства %s." % (time.strftime("%d.%m %H:%M", time.gmtime(until + MOSCOW)), code), device_code=code) + + def _consented(self, who: Who) -> bool: + with self.r.connect() as db: + return db.execute("SELECT 1 FROM code_consents WHERE device=?", (who.device,)).fetchone() is not None + + # ---- operations ------------------------------------------------------------------------------------------------------- + + def status(self, p): + who = self._who(p) + until = self._banned(who) + return {"arena_consent": self._consented(who), "models": [lihonc.NAMES[lihonc.AUTO], lihonc.NAMES[lihonc.ARENA]], + "efforts": list(WEIGHT), "banned_until": until or None, "device_code": who.device[2:10] if until else None, + "today": {"tokens": self._used(who.device), "limit": self._limit(who), "calls": self._used(who.device, "calls")}} + + def consent(self, p): + who = self._who(p) + with self.r.connect() as db: + if p.get("accept") is True: + db.execute("INSERT OR REPLACE INTO code_consents(device, accepted_at) VALUES(?,?)", (who.device, self._now())) + else: + db.execute("DELETE FROM code_consents WHERE device=?", (who.device,)) + return {"arena_consent": p.get("accept") is True} + + def chat(self, p): + who = self._who(p) + model = str(p.get("model") or "").strip().lower() + if model not in lihonc.NAMES: + raise ValueError("Unknown model") + messages = p.get("messages") + if not isinstance(messages, list) or not 0 < len(messages) <= MAX_MESSAGES: + raise ValueError("Bad messages") + for message in messages: + if not isinstance(message, dict) or message.get("role") not in ROLES: + raise ValueError("Bad messages") + if p.get("tools") is not None and not isinstance(p.get("tools"), list): + raise ValueError("Bad tools") + body = {name: p[name] for name in PASSED if name in p} + body["stream"] = False + effort = p.get("effort") if p.get("effort") in WEIGHT else "medium" + body["reasoning_effort"] = effort + stop = self._gate(who) + if stop is not None: + return stop + if model == lihonc.ARENA and not self._consented(who): + return self._error("arena_consent_required", lihonc.CONSENT_TEXT, switch_to=lihonc.NAMES[lihonc.AUTO]) + + fallback = p.get("fallback") == "auto" + target = model + if p.get("stream") is True: + while True: + opened = self._open_stream(target, body) + if opened is not None: + return Stream(self._events(who, target, model, effort, body, *opened)) + if target == lihonc.ARENA and fallback: + target = lihonc.AUTO + continue + if target == lihonc.ARENA: + return self._error("arena_unavailable", lihonc.ARENA_DOWN, switch_to=lihonc.NAMES[lihonc.AUTO]) + return self._error("all_providers_busy", lihonc.ALL_BUSY) + while True: + completion = self._ask(target, body) + if completion is not None: + self._spend(who, int(self._tokens(completion, body) * WEIGHT[effort])) # only answered calls are counted + return {"completion": completion, "model": lihonc.NAMES[target], "switched": target != model, + "left": max(0, self._limit(who) - self._used(who.device))} + if target == lihonc.ARENA: + if fallback: + target = lihonc.AUTO + continue + return self._error("arena_unavailable", lihonc.ARENA_DOWN, switch_to=lihonc.NAMES[lihonc.AUTO]) + return self._error("all_providers_busy", lihonc.ALL_BUSY) + + def _open_stream(self, alias: str, body: dict): + """(response, first chunk) of the first provider of the chain that starts to answer; None when none does. Nothing has been + sent to the person yet, so a provider that fails at once is simply replaced by the next.""" + streaming = dict(body, stream=True, stream_options={"include_usage": True}) + for provider, upstream in self.router.chain(alias, streaming): + if not self.router.available(provider): + continue + try: + response = self.router.open(provider, upstream, streaming) + except lihonc.UpstreamError: + continue + first = None + try: + for raw in response: + line = raw.decode("utf-8", "replace").strip() + if not line.startswith("data:"): + continue + data = line[5:].strip() + if data == "[DONE]": + break + chunk = json.loads(data) + if isinstance(chunk, dict) and not chunk.get("error"): + first = chunk + break + except (ValueError, OSError): + first = None + if first is not None: + return response, first, provider + response.close() + self.router.cool(provider, 20.0) + return None + + def _events(self, who: Who, target: str, asked: str, effort: str, body: dict, response, first: dict, provider: str = ""): + """The events of one streamed answer; the budget is charged at the end, also when the person goes away in the middle.""" + written, usage = 0, None + try: + chunk = first + while chunk is not None: + if isinstance(chunk.get("usage"), dict) and chunk["usage"].get("total_tokens"): + usage = chunk["usage"]["total_tokens"] + for choice in chunk.get("choices") or []: + written += len(json.dumps(choice.get("delta") or {}, ensure_ascii=False)) + yield lihonc.rename(chunk, target) + chunk = None + for raw in response: + line = raw.decode("utf-8", "replace").strip() + if not line.startswith("data:"): + continue + data = line[5:].strip() + if data == "[DONE]": + break + try: + parsed = json.loads(data) + except ValueError: + continue + if isinstance(parsed, dict): + chunk = parsed + break + yield {"lihonc_done": True, "model": lihonc.NAMES[target], "switched": target != asked} + finally: + response.close() + tokens = usage or max(1, (len(json.dumps(body.get("messages", []), ensure_ascii=False)) + written) // 3) + self._spend(who, int(tokens * WEIGHT[effort])) + self.router.charge(provider, tokens) + + def _ask(self, alias: str, body: dict): + """The first answer of the chain of the alias, with our model name; None when every provider failed.""" + for provider, upstream in self.router.chain(alias, body): + if not self.router.available(provider): + continue + try: + response = self.router.open(provider, upstream, body) + except lihonc.UpstreamError: + continue + try: + payload = json.loads(response.read().decode("utf-8")) + except (UnicodeDecodeError, ValueError, OSError): + self.router.cool(provider, 20.0) + continue + finally: + response.close() + if isinstance(payload, dict) and payload.get("choices") and not payload.get("error"): + self.router.charge(provider, self._tokens(payload, body)) + return lihonc.rename(payload, alias) + return None + + @staticmethod + def _error(kind: str, message: str, **extra) -> dict: + return {"error": {"type": kind, "message": message, **extra}} diff --git a/services/members/dub.py b/services/members/dub.py new file mode 100644 index 0000000..bfe7363 --- /dev/null +++ b/services/members/dub.py @@ -0,0 +1,518 @@ +"""AI TikTok video dubbing into Russian for AgentChat. + +Takes a TikTok video URL, downloads the watermark-free video (tikwm), extracts & transcribes speech +with timestamps via Groq Whisper (`whisper-large-v3-turbo`), translates segments into concise natural +Russian via the active LLM gate, synthesizes Russian speech, mixes a ducked original + non-overlapping +Russian TTS WAV track in Python, burns clean .ass subtitles, and renders MP4 via ffmpeg 4.3. +""" +from __future__ import annotations + +import array +import json +import os +import re +import secrets +import shutil +import subprocess +import tempfile +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +import wave +from pathlib import Path + +import ai + +TIKTOK_URL_RE = re.compile( + r"https://(?:vt\.|vm\.|www\.|m\.)?tiktok\.com/[^\s<>\"']{4,220}", + re.IGNORECASE, +) +JOB_ID_RE = re.compile(r"[0-9a-f]{24}\Z") + +MAX_DURATION_SEC = 180 +MAX_VIDEO_BYTES = 26_000_000 +MAX_DUB_TTL_SEC = 2 * 3600 +MAX_CONCURRENT_JOBS = 2 +DAILY_LIMIT = 6 +OWNER_DAILY_LIMIT = 100 +SAMPLE_RATE = 24000 +MAX_SEGMENTS = 32 + +GROQ_TRANSCRIBE_URL = "https://api.groq.com/openai/v1/audio/transcriptions" +TIKWM_API = "https://www.tikwm.com/api/" +GTTS_URL = "https://translate.google.com/translate_tts" + + +class DubError(ValueError): + pass + + +def extract_tiktok_url(text: str) -> str | None: + if not isinstance(text, str): + return None + m = TIKTOK_URL_RE.search(text.strip()) + return m.group(0) if m else None + + +def resolve_tikwm(url: str, opener=urllib.request.urlopen) -> tuple[str, str]: + """Resolves a TikTok URL via tikwm.com into (mp4_url, title).""" + body = urllib.parse.urlencode({"url": url, "hd": "1"}).encode("utf-8") + req = urllib.request.Request( + TIKWM_API, + data=body, + headers={ + "Content-Type": "application/x-www-form-urlencoded", + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", + }, + ) + with opener(req, timeout=20) as resp: + payload = json.loads(resp.read(1_000_000).decode("utf-8", "replace")) + if payload.get("code") != 0: + raise DubError("Не удалось получить видео по этой ссылке") + data = payload.get("data") or {} + dur = float(data.get("duration") or 0) + if dur > MAX_DURATION_SEC: + raise DubError("Видео длиннее 3 минут — выберите ролик покороче") + video_url = data.get("hdplay") or data.get("play") or data.get("wmplay") or "" + if not isinstance(video_url, str) or not video_url.startswith("https://"): + raise DubError("Не удалось найти видеопоток") + title = " ".join(str(data.get("title") or "").split())[:120] + return video_url, title + + +def download_file(url: str, dest: Path, max_bytes: int = MAX_VIDEO_BYTES, opener=urllib.request.urlopen) -> int: + req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) + total = 0 + with opener(req, timeout=45) as resp, dest.open("wb") as out: + while True: + chunk = resp.read(65536) + if not chunk: + break + total += len(chunk) + if total > max_bytes: + raise DubError("Видео слишком большое (макс. 25 МБ)") + out.write(chunk) + if total < 1024: + raise DubError("Скачался пустой видеофайл") + return total + + +def probe_video(video_path: Path) -> tuple[int, int, float, bool]: + """Returns (width, height, duration_sec, has_audio).""" + out = subprocess.run( + ["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", str(video_path)], + capture_output=True, timeout=15, check=False, + ) + if out.returncode != 0: + raise DubError("Не удалось прочитать видео") + info = json.loads(out.stdout.decode("utf-8", "replace")) + streams = info.get("streams") or [] + v = next((s for s in streams if s.get("codec_type") == "video"), None) + if v is None: + raise DubError("В файле нет видеодорожки") + w = int(v.get("width") or 720) + h = int(v.get("height") or 1280) + dur = float((info.get("format") or {}).get("duration") or v.get("duration") or 0) + if dur > MAX_DURATION_SEC: + raise DubError("Видео длиннее 3 минут — выберите ролик покороче") + has_audio = any(s.get("codec_type") == "audio" for s in streams) + return w, h, max(1.0, dur), has_audio + + +def extract_audio_mp3(video_path: Path, mp3_path: Path) -> None: + res = subprocess.run( + ["ffmpeg", "-y", "-v", "error", "-i", str(video_path), "-vn", + "-ac", "1", "-ar", "16000", "-b:a", "48k", str(mp3_path)], + capture_output=True, timeout=45, check=False, + ) + if res.returncode != 0 or not mp3_path.is_file() or mp3_path.stat().st_size < 128: + raise DubError("В видео нет звуковой дорожки") + + +def transcribe_groq(mp3_bytes: bytes, opener=urllib.request.urlopen) -> list[dict]: + key = os.environ.get("GROQ_KEY") or os.environ.get("GROQ_API_KEY") or "" + if not key: + raise DubError("На сервере не настроен ключ распознавания речи") + boundary = uuid.uuid4().hex + parts = [ + f"--{boundary}\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nwhisper-large-v3-turbo\r\n".encode(), + f"--{boundary}\r\nContent-Disposition: form-data; name=\"response_format\"\r\n\r\nverbose_json\r\n".encode(), + f"--{boundary}\r\nContent-Disposition: form-data; name=\"timestamp_granularities[]\"\r\n\r\nsegment\r\n".encode(), + ( + f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"audio.mp3\"\r\n" + "Content-Type: audio/mpeg\r\n\r\n" + ).encode(), + mp3_bytes, + f"\r\n--{boundary}--\r\n".encode(), + ] + req = urllib.request.Request( + GROQ_TRANSCRIBE_URL, + data=b"".join(parts), + headers={ + "Authorization": "Bearer " + key, + "Content-Type": "multipart/form-data; boundary=" + boundary, + "User-Agent": "lihont-dub/1", + }, + ) + with opener(req, timeout=45) as resp: + data = json.loads(resp.read(2_000_000).decode("utf-8", "replace")) + raw_segments = data.get("segments") or [] + segments = [] + for seg in raw_segments: + text = " ".join(str(seg.get("text") or "").split()).strip() + if not text: + continue + start = max(0.0, float(seg.get("start") or 0.0)) + end = max(start + 0.3, float(seg.get("end") or start + 1.0)) + segments.append({"start": start, "end": end, "text": text}) + if not segments and data.get("text"): + full = " ".join(str(data["text"]).split()).strip() + if full: + segments.append({"start": 0.0, "end": float(data.get("duration") or 5.0), "text": full}) + if not segments: + raise DubError("В видео не удалось распознать речь") + return segments[:MAX_SEGMENTS] + + +def parse_translation_json(reply_text: str, count: int) -> list[str]: + cleaned = reply_text.strip() + fence = re.search(r"```(?:json)?\s*([\s\S]*?)```", cleaned) + if fence: + cleaned = fence.group(1).strip() + m = re.search(r"\[[\s\S]*\]", cleaned) + if not m: + raise DubError("Модель вернула неверный формат перевода") + arr = json.loads(m.group(0)) + out = [""] * count + if isinstance(arr, list): + for idx, item in enumerate(arr): + if isinstance(item, dict): + pos = int(item.get("i", idx)) + if 0 <= pos < count: + out[pos] = " ".join(str(item.get("ru") or item.get("text") or "").split()).strip() + elif isinstance(item, str) and idx < count: + out[idx] = " ".join(item.split()).strip() + if not any(out): + raise DubError("Не удалось перевести реплики") + return out + + +def translate_segments(ai_gate, segments: list[dict]) -> list[dict]: + items = [ + {"i": i, "sec": round(max(0.5, s["end"] - s["start"]), 1), "text": s["text"]} + for i, s in enumerate(segments) + ] + prompt = ( + "Ты переводчик озвучки (дубляжа) коротких видео TikTok на живой естественный русский язык. " + "Переведи каждую реплику из JSON ниже. Делай фразы короткими и ёмкими, чтобы диктор успел прочитать за указанное время `sec`. " + "Верни ТОЛЬКО JSON-массив объектов вида [{\"i\":0,\"ru\":\"...\"}] без пояснений.\n\n" + + json.dumps(items, ensure_ascii=False) + ) + reply = ai_gate._ask([{"role": "user", "content": prompt}]) + lines = parse_translation_json(reply, len(segments)) + result = [] + for seg, ru in zip(segments, lines): + result.append({ + "start": seg["start"], + "end": seg["end"], + "src": seg["text"], + "ru": ru or seg["text"], + }) + return result + + +def split_tts_chunks(text: str, limit: int = 180) -> list[str]: + text = " ".join(text.split()).strip() + if len(text) <= limit: + return [text] if text else [] + chunks = [] + while len(text) > limit: + cut = max(text.rfind(". ", 0, limit), text.rfind(", ", 0, limit), text.rfind(" ", 0, limit)) + if cut < limit // 3: + cut = limit + chunks.append(text[:cut].strip()) + text = text[cut:].strip(" ,") + if text: + chunks.append(text) + return chunks + + +def fetch_tts_mp3(text: str, opener=urllib.request.urlopen) -> bytes: + chunks = split_tts_chunks(text) + out = [] + for chunk in chunks: + qs = urllib.parse.urlencode({"ie": "UTF-8", "client": "tw-ob", "tl": "ru", "q": chunk}) + req = urllib.request.Request(GTTS_URL + "?" + qs, headers={"User-Agent": "Mozilla/5.0"}) + with opener(req, timeout=15) as resp: + out.append(resp.read(500_000)) + return b"".join(out) + + +def decode_tts_pcm(mp3_bytes: bytes, tmpdir: Path, idx: int, target_max_sec: float) -> array.array: + mp3_path = tmpdir / f"seg_{idx}.mp3" + pcm_path = tmpdir / f"seg_{idx}.pcm" + mp3_path.write_bytes(mp3_bytes) + probe = subprocess.run( + ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "json", str(mp3_path)], + capture_output=True, timeout=10, check=False, + ) + dur = 0.0 + if probe.returncode == 0: + try: + dur = float((json.loads(probe.stdout.decode("utf-8", "replace")).get("format") or {}).get("duration") or 0) + except (ValueError, TypeError): + dur = 0.0 + filters = [] + if dur > 0.4 and target_max_sec >= 0.7 and dur > target_max_sec: + speed = min(1.38, max(1.0, dur / target_max_sec)) + if speed > 1.04: + filters.append(f"atempo={speed:.3f}") + cmd = ["ffmpeg", "-y", "-v", "error", "-i", str(mp3_path)] + if filters: + cmd.extend(["-af", ",".join(filters)]) + cmd.extend(["-f", "s16le", "-ac", "1", "-ar", str(SAMPLE_RATE), str(pcm_path)]) + res = subprocess.run(cmd, capture_output=True, timeout=20, check=False) + if res.returncode != 0 or not pcm_path.is_file(): + return array.array("h") + arr = array.array("h") + arr.frombytes(pcm_path.read_bytes()) + return arr + + +def build_tts_track(segments: list[dict], total_duration: float, tmpdir: Path, tts_fn=fetch_tts_mp3) -> Path: + """Synthesizes each translated segment and places samples sequentially onto a 24kHz mono WAV track.""" + total_samples = max(SAMPLE_RATE, int((total_duration + 0.5) * SAMPLE_RATE)) + buf = array.array("h", [0]) * total_samples + cursor = 0 + for idx, seg in enumerate(segments): + ru = seg.get("ru") or "" + if not ru: + continue + mp3 = tts_fn(ru) + if not mp3: + continue + next_start = segments[idx + 1]["start"] if idx + 1 < len(segments) else total_duration + slot = max(0.8, next_start - seg["start"] - 0.05) + pcm = decode_tts_pcm(mp3, tmpdir, idx, slot) + if not pcm: + continue + start_sample = max(cursor, int(seg["start"] * SAMPLE_RATE)) + if start_sample >= total_samples: + break + usable = min(len(pcm), total_samples - start_sample) + for j in range(usable): + buf[start_sample + j] = pcm[j] + cursor = start_sample + usable + int(0.05 * SAMPLE_RATE) + + wav_path = tmpdir / "dub_ru.wav" + with wave.open(str(wav_path), "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) + wf.setframerate(SAMPLE_RATE) + wf.writeframes(buf.tobytes()) + return wav_path + + +def _ass_time(sec: float) -> str: + sec = max(0.0, sec) + h = int(sec // 3600) + m = int((sec % 3600) // 60) + s = int(sec % 60) + cs = int(round((sec - int(sec)) * 100)) % 100 + return f"{h}:{m:02d}:{s:02d}.{cs:02d}" + + +def build_ass(segments: list[dict], width: int, height: int) -> str: + font_size = max(24, round(min(width, height) * 0.052)) + margin_v = max(48, round(height * 0.14)) + margin_lr = max(24, round(width * 0.06)) + lines = [ + "[Script Info]", + "ScriptType: v4.00+", + f"PlayResX: {width}", + f"PlayResY: {height}", + "WrapStyle: 1", + "", + "[V4+ Styles]", + "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, " + "Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, " + "Alignment, MarginL, MarginR, MarginV, Encoding", + f"Style: Default,DejaVu Sans,{font_size},&H00FFFFFF,&H00FFFFFF,&H00121218,&HA0121218," + f"1,0,0,0,100,100,0,0,3,6,0,2,{margin_lr},{margin_lr},{margin_v},204", + "", + "[Events]", + "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text", + ] + for seg in segments: + ru = (seg.get("ru") or "").replace("\\", " ").replace("{", "(").replace("}", ")") + if not ru: + continue + lines.append(f"Dialogue: 0,{_ass_time(seg['start'])},{_ass_time(seg['end'])},Default,,0,0,0,,{ru}") + return "\n".join(lines) + "\n" + + +def render_dubbed_video(video_path: Path, tts_wav: Path, ass_path: Path, out_path: Path, has_audio: bool) -> None: + escaped_ass = str(ass_path).replace("\\", "/").replace(":", "\\:") + if has_audio: + audio_graph = ( + "[0:a]volume=0.22[orig];[1:a]volume=1.35[ru];" + "[orig][ru]amix=inputs=2:duration=first:dropout_transition=0,volume=2.0,alimiter=limit=0.95[aout]" + ) + else: + audio_graph = "[1:a]volume=1.2,alimiter=limit=0.95[aout]" + filter_complex = f"[0:v]ass='{escaped_ass}'[vout];{audio_graph}" + cmd = [ + "ffmpeg", "-y", "-v", "error", + "-i", str(video_path), + "-i", str(tts_wav), + "-filter_complex", filter_complex, + "-map", "[vout]", + "-map", "[aout]", + "-c:v", "libx264", "-preset", "veryfast", "-crf", "24", "-pix_fmt", "yuv420p", + "-c:a", "aac", "-b:a", "128k", + "-shortest", + "-movflags", "+faststart", + str(out_path), + ] + res = subprocess.run(cmd, capture_output=True, timeout=180, check=False) + if res.returncode != 0 or not out_path.is_file() or out_path.stat().st_size < 2048: + err = res.stderr.decode("utf-8", "replace")[:200] + raise DubError("Не получилось собрать видео: " + (err or "ошибка ffmpeg")) + + +class DubManager: + def __init__(self, registry, run_async=True): + self.r = registry + self.dir = Path(registry.art_dir).parent / "dubs" + self.run_async = run_async + self._lock = threading.Lock() + self._sem = threading.Semaphore(MAX_CONCURRENT_JOBS) + self._jobs: dict[str, dict] = {} + self.operations = {"dub_start": self.start, "dub_status": self.status} + + def call(self, operation: str, payload: dict) -> dict: + return self.operations[operation](payload) + + def _cleanup_old(self): + now = time.time() + try: + if self.dir.is_dir(): + for f in self.dir.glob("*.mp4"): + if now - f.stat().st_mtime > MAX_DUB_TTL_SEC: + f.unlink(missing_ok=True) + except OSError: + pass + with self._lock: + stale = [k for k, v in self._jobs.items() if now - v["created_at"] > MAX_DUB_TTL_SEC] + for k in stale: + del self._jobs[k] + + def file_path(self, job_id: str) -> Path | None: + if not isinstance(job_id, str) or not JOB_ID_RE.fullmatch(job_id): + return None + p = self.dir / f"{job_id}.mp4" + return p if p.is_file() else None + + def start(self, p: dict) -> dict: + tg_id, _ = self.r.accounts._member(p) + url = extract_tiktok_url(str(p.get("url") or "")) + if not url: + raise ValueError("Нужна ссылка на видео TikTok") + day = self.r.ai._day() + cap = OWNER_DAILY_LIMIT if self.r.ai._owner(tg_id) else DAILY_LIMIT + usage_key = day + "#dub" + if not self.r.ai._take(tg_id, usage_key, cap): + raise ValueError("Daily limit reached (%d). Try again tomorrow" % cap) + self._cleanup_old() + job_id = secrets.token_hex(12) + with self._lock: + self._jobs[job_id] = { + "id": job_id, + "tg_id": tg_id, + "url": url, + "status": "queued", + "stage": "В очереди на озвучку…", + "summary": "", + "error": "", + "path": "", + "created_at": time.time(), + "usage_key": usage_key, + } + if self.run_async: + threading.Thread(target=self._run_job, args=(job_id,), name="lihont-dub-" + job_id[:6], daemon=True).start() + return {"job_id": job_id, "status": "queued", "stage": "В очереди на озвучку…"} + + def status(self, p: dict) -> dict: + tg_id, _ = self.r.accounts._member(p) + job_id = str(p.get("job_id") or "") + if not JOB_ID_RE.fullmatch(job_id): + raise ValueError("Bad job id") + with self._lock: + job = self._jobs.get(job_id) + if job is None or job["tg_id"] != tg_id: + raise ValueError("Задача не найдена") + return { + "job_id": job_id, + "status": job["status"], + "stage": job["stage"], + "summary": job["summary"], + "error": job["error"], + "path": job["path"], + } + + def _set(self, job_id: str, **updates): + with self._lock: + if job_id in self._jobs: + self._jobs[job_id].update(updates) + + def _run_job(self, job_id: str): + job = self._jobs.get(job_id) + if job is None: + return + with self._sem: + try: + self._execute(job_id, job["url"]) + except DubError as exc: + self.r.ai._give_back(job["tg_id"], job["usage_key"]) + self._set(job_id, status="error", stage="Ошибка", error=str(exc)) + except Exception as exc: + self.r.ai._give_back(job["tg_id"], job["usage_key"]) + self._set(job_id, status="error", stage="Ошибка", error="Не удалось озвучить видео: " + str(exc)[:100]) + + def _execute(self, job_id: str, url: str): + self.dir.mkdir(parents=True, exist_ok=True) + out_path = self.dir / f"{job_id}.mp4" + with tempfile.TemporaryDirectory(prefix="lihont-dub-") as td: + tmp = Path(td) + self._set(job_id, status="downloading", stage="Скачиваю видео…") + video_url, _title = resolve_tikwm(url) + in_mp4 = tmp / "in.mp4" + download_file(video_url, in_mp4) + w, h, dur, has_audio = probe_video(in_mp4) + + self._set(job_id, status="transcribing", stage="Распознаю речь и тайминги…") + src_mp3 = tmp / "src.mp3" + extract_audio_mp3(in_mp4, src_mp3) + segments = transcribe_groq(src_mp3.read_bytes()) + + self._set(job_id, status="translating", stage="Перевожу на русский…") + translated = translate_segments(self.r.ai, segments) + + self._set(job_id, status="synthesizing", stage="Озвучиваю переведённые фразы…") + tts_wav = build_tts_track(translated, dur, tmp) + ass_path = tmp / "subs.ass" + ass_path.write_text(build_ass(translated, w, h), encoding="utf-8") + + self._set(job_id, status="rendering", stage="Склеиваю видео с озвучкой и субтитрами…") + part = self.dir / f"{job_id}.part.mp4" + render_dubbed_video(in_mp4, tts_wav, ass_path, part, has_audio) + os.replace(part, out_path) + + preview_lines = [seg["ru"] for seg in translated if seg.get("ru")] + summary = " · ".join(preview_lines[:3]) + if len(summary) > 180: + summary = summary[:177] + "…" + self._set(job_id, status="done", stage="Готово", summary=summary, path="dub/" + job_id + ".mp4") diff --git a/services/members/lihonc.py b/services/members/lihonc.py new file mode 100644 index 0000000..4cab33a --- /dev/null +++ b/services/members/lihonc.py @@ -0,0 +1,638 @@ +"""LihonC: one OpenAI-compatible endpoint with two "models" that are really routes over free providers. + +LihonC-1-auto tries free providers in turn (Groq, Gemini, Cohere, Zhipu, OpenRouter's free models); when one is out of its + limit or down, the next one answers. Short talks go to the fastest first, long ones and tool calls to the + strongest. The owner's paid reserves (apinet, nordrouter) are switched off by default: LIHONC_ALLOW_PAID=1 + brings them back at the end of both chains. +LihonC-1-deepseek:arena + DeepSeek V4.1 Flash through Coarena. Coarena keeps every prompt and answer and may sell them in datasets, so a key + has to accept that once (POST /v1/arena/consent) before the first request. When the arena is out of its free + quota the answer is an error that offers LihonC-1-auto, or, with the header "X-LihonC-Fallback: auto", the request + simply goes there. + +Who may ask: only holders of a LihonC key (sha256 of it is stored, never the key). How much: a daily number of requests per key and +model kind (the day is the Moscow one) and a per-minute cap. What is kept: counters only; prompts and answers are never written. +The providers' keys are read from an env file outside the repository and never leave this process. + +Plain standard library: http.server, sqlite3, urllib. Run: py lihonc.py serve --port 8787; keys: py lihonc.py issue --name bob. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import secrets +import socket +import sqlite3 +import sys +import threading +import time +import urllib.error +import urllib.request +from collections import defaultdict, deque +from contextlib import contextmanager +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +AUTO = "lihonc-1-auto" +ARENA = "lihonc-1-deepseek:arena" +NAMES = {AUTO: "LihonC-1-auto", ARENA: "LihonC-1-deepseek:arena"} + +MOSCOW = 3 * 3600 +DAILY_AUTO = int(os.environ.get("LIHONC_DAILY", "200")) +DAILY_ARENA = int(os.environ.get("LIHONC_ARENA_DAILY", "50")) +OWNER_FACTOR = 20 +PER_MINUTE = int(os.environ.get("LIHONC_PER_MINUTE", "20")) +TIMEOUT = 120.0 # until the first byte of an answer; a stream may then run longer +MAX_BODY = 4_000_000 +MAX_TOKENS = 16_000 +COOL = 60.0 # seconds a provider is skipped after it said "too many" +HEAVY_CHARS = 12_000 # a talk longer than this (or with tools) goes to the strongest provider first + +PROVIDERS = { + "groq": {"base": "https://api.groq.com/openai/v1", "key": "GROQ_API_KEY"}, + "gemini": {"base": "https://generativelanguage.googleapis.com/v1beta/openai", "key": "GEMINI_API_KEY", + "drop": ("stream_options", "parallel_tool_calls", "seed", "presence_penalty", "frequency_penalty")}, + "openrouter": {"base": "https://openrouter.ai/api/v1", "key": "OPENROUTER_API_KEY"}, + "cohere": {"base": "https://api.cohere.ai/compatibility/v1", "key": "COHERE_API_KEY", + "drop": ("stream_options", "parallel_tool_calls", "n")}, + "coarena": {"base": "https://coarena.ai/api/v1", "key": "COARENA_API_KEY"}, + # paid reserves with the owner's own small balances: last in the chains, each with a ceiling of tokens a day + "apinet": {"base": "https://apinet.cloud/v1", "key": "APINET_API_KEY", "paid": True, "effort": False, + "daily_tokens": int(os.environ.get("APINET_DAILY_TOKENS", "3000000")), "drop": ("stream_options",)}, + "nordrouter": {"base": "https://nordrouter.com/v1", "key": "NORDROUTER_API_KEY", "paid": True, "effort": False, + "daily_tokens": int(os.environ.get("NORDROUTER_DAILY_TOKENS", "300000"))}, + # Zhipu's GLM on the Chinese platform: glm-4.5-flash is free there (the international z.ai asks for a balance). + # Its queue times out now and then, so it gets a shorter timeout than everyone else. + "zhipu": {"base": "https://open.bigmodel.cn/api/paas/v4", "key": "ZHIPU_API_KEY", "timeout": 45.0, + "drop": ("stream_options", "parallel_tool_calls", "seed", "presence_penalty", "frequency_penalty", "n")}, +} + +FAST = [("groq", "openai/gpt-oss-120b"), ("gemini", "gemini-2.5-flash"), ("cohere", "command-a-03-2025"), + ("zhipu", "glm-4.5-flash"), + ("apinet", "deepseek-v4.1-flash"), ("nordrouter", "deepseek/deepseek-v4.1-flash:fjord"), + ("openrouter", "nvidia/nemotron-3-ultra-550b-a55b:free")] +HEAVY = [("gemini", "gemini-2.5-flash"), ("groq", "openai/gpt-oss-120b"), ("cohere", "command-a-03-2025"), + ("zhipu", "glm-4.5-flash"), + ("apinet", "deepseek-v4.1-flash"), ("nordrouter", "deepseek/deepseek-v4.1-flash:fjord"), + ("openrouter", "nvidia/nemotron-3-ultra-550b-a55b:free")] # nemotron thinks long: the last one +ARENA_CHAIN = [("coarena", "deepseek-v4-1-flash-1017")] + +# The owner's paid reserves (apinet, nordrouter) are off unless asked for: LIHONC_ALLOW_PAID=1 brings them back at the +# end of both chains. The check is made per request, so a test or a shell can switch them on without a restart. +PAID = {"apinet", "nordrouter"} + + +def allow_paid() -> bool: + return os.environ.get("LIHONC_ALLOW_PAID", "0") == "1" + + +def chain_entries(entries): + return entries if allow_paid() else [entry for entry in entries if entry[0] not in PAID] + +ALLOWED = ("messages", "tools", "tool_choice", "temperature", "top_p", "max_tokens", "stream", "stop", "response_format", "n", + "seed", "presence_penalty", "frequency_penalty", "parallel_tool_calls", "stream_options") + +CONSENT_TEXT = ( + "LihonC-1-deepseek:arena работает через Coarena. Всё, что ты отправишь этой модели, и её ответы Coarena сохраняет у себя " + "и может продавать в датасетах ИИ-компаниям, удалить это нельзя. Не отправляй сюда личное, пароли, ключи и переписки. " + "Согласен: POST /v1/arena/consent с телом {\"accept\": true}. Не согласен: пользуйся LihonC-1-auto, он ничего не сохраняет." +) +ARENA_DOWN = "Арена пока недоступна. Переключить на LihonC-1-auto?" +ALL_BUSY = "Все бесплатные модели сейчас заняты или упёрлись в лимит. Попробуй через минуту." + + +class UpstreamError(Exception): + def __init__(self, provider: str, status: int, detail: str): + super().__init__(f"{provider}: {status} {detail}") + self.provider = provider + self.status = status + self.detail = detail + + +def load_keys(path: str | os.PathLike | None) -> dict: + """Provider keys from an env file (KEY=value lines); the process environment fills what the file lacks.""" + keys = {} + if path and Path(path).is_file(): + for line in Path(path).read_text(encoding="utf-8").splitlines(): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + name, value = line.split("=", 1) + if value.strip(): + keys[name.strip()] = value.strip() + for provider in PROVIDERS.values(): + if provider["key"] not in keys and os.environ.get(provider["key"]): + keys[provider["key"]] = os.environ[provider["key"]] + return keys + + +def sha(key: str) -> str: + return hashlib.sha256(key.encode("utf-8")).hexdigest() + + +class Store: + """Keys (hashed) and daily counters in sqlite. Nothing of what people ask is ever written here.""" + + def __init__(self, path, clock=time.time): + self.path = str(path) + self.clock = clock + self.lock = threading.Lock() + with self.db() as db: + db.execute("CREATE TABLE IF NOT EXISTS keys (hash TEXT PRIMARY KEY, name TEXT NOT NULL, created INTEGER NOT NULL, " + "banned INTEGER NOT NULL DEFAULT 0, owner INTEGER NOT NULL DEFAULT 0, daily INTEGER, " + "arena_consent INTEGER NOT NULL DEFAULT 0)") + db.execute("CREATE TABLE IF NOT EXISTS usage (day TEXT NOT NULL, hash TEXT NOT NULL, kind TEXT NOT NULL, " + "requests INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day, hash, kind))") + + @contextmanager + def db(self): + db = sqlite3.connect(self.path, timeout=10) + db.row_factory = sqlite3.Row + try: + with db: + yield db + finally: + db.close() + + def day(self) -> str: + return time.strftime("%Y-%m-%d", time.gmtime(self.clock() + MOSCOW)) + + def issue(self, name: str, owner: bool = False, daily: int | None = None) -> str: + key = "lhc-" + secrets.token_urlsafe(32) + with self.lock, self.db() as db: + db.execute("INSERT INTO keys (hash, name, created, owner, daily) VALUES (?, ?, ?, ?, ?)", + (sha(key), name, int(self.clock()), 1 if owner else 0, daily)) + return key + + def find(self, key: str): + if not key: + return None + with self.db() as db: + return db.execute("SELECT * FROM keys WHERE hash = ?", (sha(key),)).fetchone() + + def ban(self, name: str, banned: bool = True) -> int: + with self.lock, self.db() as db: + return db.execute("UPDATE keys SET banned = ? WHERE name = ?", (1 if banned else 0, name)).rowcount + + def consent(self, key_hash: str, accept: bool) -> None: + with self.lock, self.db() as db: + db.execute("UPDATE keys SET arena_consent = ? WHERE hash = ?", (int(self.clock()) if accept else 0, key_hash)) + + def used(self, key_hash: str, kind: str) -> int: + with self.db() as db: + row = db.execute("SELECT requests FROM usage WHERE day = ? AND hash = ? AND kind = ?", + (self.day(), key_hash, kind)).fetchone() + return row["requests"] if row else 0 + + def count(self, key_hash: str, kind: str) -> None: + with self.lock, self.db() as db: + db.execute("INSERT INTO usage (day, hash, kind, requests) VALUES (?, ?, ?, 1) " + "ON CONFLICT(day, hash, kind) DO UPDATE SET requests = requests + 1", (self.day(), key_hash, kind)) + + def limit(self, row, kind: str) -> int: + base = DAILY_ARENA if kind == "arena" else (row["daily"] or DAILY_AUTO) + return base * OWNER_FACTOR if row["owner"] else base + + def report(self): + with self.db() as db: + return db.execute("SELECT k.name, u.kind, u.requests FROM usage u JOIN keys k ON k.hash = u.hash " + "WHERE u.day = ? ORDER BY u.requests DESC", (self.day(),)).fetchall() + + +EFFORTS = ("low", "medium", "high") +# How hard to think, in each provider's words: Groq and Gemini take reasoning_effort, OpenRouter a reasoning object, Coarena's DeepSeek +# knows none/high/max, Cohere's command model does not think at all. +EFFORT_WORDS = {"coarena": {"low": "none", "medium": "high", "high": "max"}} + + +def clean_body(body: dict, provider: str, model: str) -> dict: + """Only the fields every provider understands, with the provider's own model id.""" + out = {name: body[name] for name in ALLOWED if name in body} + effort = body.get("reasoning_effort") + if PROVIDERS[provider].get("effort") is False: + pass # this provider is not told how hard to think + elif effort in EFFORTS and provider == "zhipu": + out["thinking"] = {"type": "disabled" if effort == "low" else "enabled"} # GLM only thinks or does not + elif effort in EFFORTS and provider != "cohere": + word = EFFORT_WORDS.get(provider, {}).get(effort, effort) + if provider == "openrouter": + out["reasoning"] = {"effort": word} + else: + out["reasoning_effort"] = word + if "max_tokens" not in out and isinstance(body.get("max_completion_tokens"), int): + out["max_tokens"] = body["max_completion_tokens"] + if isinstance(out.get("max_tokens"), int): + out["max_tokens"] = max(1, min(out["max_tokens"], MAX_TOKENS)) + for name in PROVIDERS[provider].get("drop", ()): + out.pop(name, None) + out["model"] = model + return out + + +def has_images(body: dict) -> bool: + for message in body.get("messages", []) or []: + content = message.get("content") if isinstance(message, dict) else None + if isinstance(content, list) and any(isinstance(part, dict) and part.get("type") == "image_url" for part in content): + return True + return False + + +def heavy(body: dict) -> bool: + if body.get("tools") or has_images(body): + return True + try: + return len(json.dumps(body.get("messages", []), ensure_ascii=False)) > HEAVY_CHARS + except (TypeError, ValueError): + return True + + +class Router: + def __init__(self, keys: dict, providers: dict | None = None, clock=time.time, timeout: float = TIMEOUT): + self.keys = keys + self.providers = providers or PROVIDERS + self.clock = clock + self.timeout = timeout + self.cooling = {} + self.spent = {} + self.lock = threading.Lock() + + def chain(self, model: str, body: dict): + if model == ARENA: + return ARENA_CHAIN + return chain_entries(HEAVY if heavy(body) else FAST) + + def available(self, provider: str) -> bool: + spec = self.providers[provider] + if spec["key"] not in self.keys: + return False + with self.lock: + if spec.get("paid") and self.spent.get((provider, self.day()), 0) >= spec.get("daily_tokens", 0): + return False # a paid reserve has spent its share of today + return self.cooling.get(provider, 0) <= self.clock() + + def day(self) -> str: + return time.strftime("%Y-%m-%d", time.gmtime(self.clock() + MOSCOW)) + + def charge(self, provider: str, tokens: int) -> None: + """Counts what a paid reserve spent today (kept in memory: a restart forgets today's sum, which only errs by one day).""" + if not self.providers.get(provider, {}).get("paid"): + return + with self.lock: + key = (provider, self.day()) + self.spent = {k: v for k, v in self.spent.items() if k[1] == key[1]} + self.spent[key] = self.spent.get(key, 0) + max(0, int(tokens)) + + def cool(self, provider: str, seconds: float = COOL) -> None: + with self.lock: + self.cooling[provider] = self.clock() + seconds + + def open(self, provider: str, model: str, body: dict): + """Starts one upstream request; returns the response object or raises UpstreamError.""" + spec = self.providers[provider] + data = json.dumps(clean_body(body, provider, model), ensure_ascii=False).encode("utf-8") + request = urllib.request.Request(spec["base"].rstrip("/") + "/chat/completions", data=data, headers={ + "Authorization": "Bearer " + self.keys[spec["key"]], + "Content-Type": "application/json", + "Accept": "text/event-stream" if body.get("stream") else "application/json", + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) LihonC/1", + }) + try: + return urllib.request.urlopen(request, timeout=self.providers[provider].get("timeout", self.timeout)) + except urllib.error.HTTPError as error: + try: + detail = error.read(400).decode("utf-8", "replace") + except Exception: + detail = "" + if error.code in (402, 429): + retry = error.headers.get("Retry-After") if error.headers else None + try: + self.cool(provider, max(5.0, min(float(retry), 3600.0)) if retry else COOL) + except ValueError: + self.cool(provider) + elif error.code >= 500: + self.cool(provider, 20.0) + raise UpstreamError(provider, error.code, detail) + except (urllib.error.URLError, socket.timeout, TimeoutError, ConnectionError, OSError) as error: + self.cool(provider, 20.0) + raise UpstreamError(provider, 0, str(error)[:200]) + + +def rename(payload: dict, alias: str) -> dict: + payload["model"] = NAMES.get(alias, alias) + return payload + + +class Handler(BaseHTTPRequestHandler): + server_version = "LihonC/1" + protocol_version = "HTTP/1.0" + + # ---- plumbing ----------------------------------------------------------------------------------------------------------- + + @property + def app(self) -> "App": + return self.server.app # type: ignore[attr-defined] + + def log_message(self, fmt, *args): # the default one prints addresses and paths of every request; ours prints counters only + pass + + def send_json(self, status: int, payload: dict, headers: dict | None = None) -> None: + data = json.dumps(payload, ensure_ascii=False).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + for name, value in (headers or {}).items(): + self.send_header(name, value) + self.end_headers() + self.wfile.write(data) + + def fail(self, status: int, kind: str, message: str, **extra) -> None: + error = {"message": message, "type": kind, "code": kind} + error.update(extra) + self.send_json(status, {"error": error}) + + def key_row(self): + auth = self.headers.get("Authorization", "") + key = auth[7:].strip() if auth.lower().startswith("bearer ") else "" + row = self.app.store.find(key) + if row is None: + self.fail(401, "invalid_api_key", "Нет ключа LihonC или он неверный.") + return None + if row["banned"]: + self.fail(403, "key_banned", "Этот ключ LihonC заблокирован.") + return None + return row + + def read_json(self): + try: + size = int(self.headers.get("Content-Length") or 0) + except ValueError: + size = -1 + if size <= 0 or size > MAX_BODY: + self.fail(400, "invalid_request_error", "Пустой или слишком большой запрос.") + return None + try: + body = json.loads(self.rfile.read(size).decode("utf-8")) + except (UnicodeDecodeError, ValueError): + self.fail(400, "invalid_request_error", "Тело запроса — не JSON.") + return None + if not isinstance(body, dict): + self.fail(400, "invalid_request_error", "Тело запроса должно быть объектом JSON.") + return None + return body + + # ---- routes ------------------------------------------------------------------------------------------------------------- + + def do_GET(self): + path = self.path.split("?", 1)[0].rstrip("/") + if path == "/health": + return self.send_json(200, {"ok": True}) + if path == "/v1/models": + return self.send_json(200, {"object": "list", "data": [ + {"id": NAMES[AUTO], "object": "model", "owned_by": "lihonc", + "description": "Бесплатные модели по очереди: Groq, Gemini, Cohere, Zhipu, OpenRouter. Ничего не сохраняет."}, + {"id": NAMES[ARENA], "object": "model", "owned_by": "lihonc", + "description": "DeepSeek V4.1 Flash через Coarena. Coarena сохраняет запросы и ответы. Нужно согласие."}, + ]}) + if path == "/v1/arena/consent": + return self.send_json(200, {"text": CONSENT_TEXT}) + if path == "/v1/me": + row = self.key_row() + if row is None: + return + return self.send_json(200, { + "name": row["name"], + "arena_consent": bool(row["arena_consent"]), + "today": {NAMES[AUTO]: {"used": self.app.store.used(row["hash"], "auto"), "limit": self.app.store.limit(row, "auto")}, + NAMES[ARENA]: {"used": self.app.store.used(row["hash"], "arena"), "limit": self.app.store.limit(row, "arena")}}, + }) + self.fail(404, "not_found", "Нет такого адреса.") + + def do_POST(self): + path = self.path.split("?", 1)[0].rstrip("/") + if path == "/v1/arena/consent": + row = self.key_row() + if row is None: + return + body = self.read_json() + if body is None: + return + accept = body.get("accept") is True + self.app.store.consent(row["hash"], accept) + return self.send_json(200, {"arena_consent": accept, + "text": "Согласие принято." if accept else "Согласие отозвано."}) + if path == "/v1/chat/completions": + return self.chat() + self.fail(404, "not_found", "Нет такого адреса.") + + def chat(self): + started = time.time() + row = self.key_row() + if row is None: + return + body = self.read_json() + if body is None: + return + model = str(body.get("model") or "").strip().lower() + if model not in NAMES: + return self.fail(404, "model_not_found", f"Модели «{body.get('model')}» нет. Есть: {NAMES[AUTO]}, {NAMES[ARENA]}.") + if not isinstance(body.get("messages"), list) or not body["messages"]: + return self.fail(400, "invalid_request_error", "Нет сообщений (messages).") + if not self.app.minute_ok(row["hash"]): + return self.fail(429, "rate_limit", f"Не больше {PER_MINUTE} запросов в минуту.") + if model == ARENA and not row["arena_consent"]: + return self.fail(403, "arena_consent_required", CONSENT_TEXT, consent_url="/v1/arena/consent", switch_to=NAMES[AUTO]) + + fallback = (self.headers.get("X-LihonC-Fallback", "") or str(body.get("lihonc_fallback", ""))).strip().lower() == "auto" + target = model + while True: + kind = "arena" if target == ARENA else "auto" + limit = self.app.store.limit(row, kind) + if self.app.store.used(row["hash"], kind) >= limit: + if target == ARENA and fallback: + target = AUTO + continue + return self.fail(429, "daily_limit", f"Лимит {NAMES[target]} на сегодня ({limit}) исчерпан. Сброс в 00:00 по Москве.", + **({"switch_to": NAMES[AUTO]} if target == ARENA else {})) + served = self.serve(target, body, row, switched=target != model) + if served: + self.app.log(row["name"], NAMES[target], served, 200, time.time() - started) + return + if target == ARENA: + if fallback: + target = AUTO + continue + self.app.log(row["name"], NAMES[target], "-", 429, time.time() - started) + return self.fail(429, "arena_unavailable", ARENA_DOWN, switch_to=NAMES[AUTO]) + self.app.log(row["name"], NAMES[target], "-", 503, time.time() - started) + return self.fail(503, "all_providers_busy", ALL_BUSY) + + def serve(self, alias: str, body: dict, row, switched: bool) -> str | None: + """Tries the chain of the alias; returns the provider that answered, or None when none did.""" + router = self.app.router + kind = "arena" if alias == ARENA else "auto" + for provider, upstream in router.chain(alias, body): + if not router.available(provider): + continue + try: + response = router.open(provider, upstream, body) + except UpstreamError as error: + self.app.note(f"{provider} {error.status} {error.detail[:120]!r}") + continue + headers = {"X-LihonC-Model": NAMES[alias], "X-LihonC-Upstream": provider} + if switched: + headers["X-LihonC-Switched"] = NAMES[alias] + try: + if body.get("stream"): + if not self.stream(response, alias, headers): + router.cool(provider, 20.0) + continue + else: + raw = response.read() + try: + payload = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + router.cool(provider, 20.0) + continue + if not isinstance(payload, dict) or payload.get("error") or not payload.get("choices"): + continue + self.send_json(200, rename(payload, alias), headers) + finally: + response.close() + self.app.store.count(row["hash"], kind) + return provider + return None + + def stream(self, response, alias: str, headers: dict) -> bool: + """Passes server-sent events through with our model name. Nothing is sent until the upstream has said something real, + so a provider that fails at once can still be swapped for the next one.""" + first = [] + for raw in response: + line = raw.decode("utf-8", "replace").rstrip("\r\n") + if not line: + continue + if line.startswith("data:") and line[5:].strip() != "[DONE]": + try: + chunk = json.loads(line[5:].strip()) + except ValueError: + return False + if isinstance(chunk, dict) and chunk.get("error"): + return False + first.append(chunk) + break + if line.startswith(":") or line.startswith("event:"): + continue + return False + if not first: + return False + self.send_response(200) + self.send_header("Content-Type", "text/event-stream; charset=utf-8") + self.send_header("Cache-Control", "no-cache") + self.send_header("Connection", "close") + for name, value in headers.items(): + self.send_header(name, value) + self.end_headers() + try: + self.write_event(rename(first[0], alias)) + for raw in response: + line = raw.decode("utf-8", "replace").rstrip("\r\n") + if not line.startswith("data:"): + continue + data = line[5:].strip() + if data == "[DONE]": + break + try: + chunk = json.loads(data) + except ValueError: + continue + if isinstance(chunk, dict): + self.write_event(rename(chunk, alias)) + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError, socket.timeout, OSError): + pass # the person closed the connection or the upstream broke mid-answer: nothing more to send + return True + + def write_event(self, chunk: dict) -> None: + self.wfile.write(b"data: " + json.dumps(chunk, ensure_ascii=False).encode("utf-8") + b"\n\n") + self.wfile.flush() + + +class App: + def __init__(self, store: Store, router: Router, quiet: bool = False): + self.store = store + self.router = router + self.quiet = quiet + self.minutes = defaultdict(deque) + self.lock = threading.Lock() + + def minute_ok(self, key_hash: str) -> bool: + now = time.time() + with self.lock: + window = self.minutes[key_hash] + while window and window[0] < now - 60: + window.popleft() + if len(window) >= PER_MINUTE: + return False + window.append(now) + return True + + def log(self, name, model, provider, status, seconds) -> None: + self.note(f"{name} {model} via {provider}: {status} in {seconds:.1f}s") + + def note(self, text: str) -> None: + if not self.quiet: + print(time.strftime("%H:%M:%S"), text, flush=True) + + +def make_server(app: App, host: str, port: int) -> ThreadingHTTPServer: + server = ThreadingHTTPServer((host, port), Handler) + server.daemon_threads = True + server.app = app # type: ignore[attr-defined] + return server + + +def main(argv=None) -> int: + default_keys = os.environ.get("LIHONC_KEYS_FILE") or str(Path.home() / ".lihont" / "free_keys.env") + default_db = os.environ.get("LIHONC_DB") or str(Path.home() / ".lihont" / "lihonc.sqlite3") + parser = argparse.ArgumentParser(description="LihonC: free models behind one OpenAI-compatible endpoint") + parser.add_argument("--db", default=default_db) + sub = parser.add_subparsers(dest="command", required=True) + serve = sub.add_parser("serve") + serve.add_argument("--host", default="127.0.0.1") + serve.add_argument("--port", type=int, default=8787) + serve.add_argument("--keys", default=default_keys) + issue = sub.add_parser("issue") + issue.add_argument("--name", required=True) + issue.add_argument("--owner", action="store_true") + issue.add_argument("--daily", type=int) + ban = sub.add_parser("ban") + ban.add_argument("--name", required=True) + ban.add_argument("--undo", action="store_true") + sub.add_parser("usage") + args = parser.parse_args(argv) + + store = Store(args.db) + if args.command == "issue": + print(store.issue(args.name, owner=args.owner, daily=args.daily)) + return 0 + if args.command == "ban": + print("ключей изменено:", store.ban(args.name, banned=not args.undo)) + return 0 + if args.command == "usage": + for row in store.report(): + print(f"{row['name']:20} {row['kind']:6} {row['requests']}") + return 0 + keys = load_keys(args.keys) + ready = [name for name, spec in PROVIDERS.items() if spec["key"] in keys] + print("LihonC слушает", f"http://{args.host}:{args.port}/v1", "· провайдеры:", ", ".join(ready) or "нет ключей", flush=True) + server = make_server(App(store, Router(keys)), args.host, args.port) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/services/members/music.py b/services/members/music.py new file mode 100644 index 0000000..d299b08 --- /dev/null +++ b/services/members/music.py @@ -0,0 +1,323 @@ +"""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} diff --git a/services/members/server.py b/services/members/server.py index 2efc7a5..e374efe 100644 --- a/services/members/server.py +++ b/services/members/server.py @@ -32,7 +32,10 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) import accounts import ai import catalog +import codegate import community +import dub +import music from community import INSTALL, UID, valid_uid LIFETIME = 30 * 86400 @@ -72,15 +75,18 @@ CHAT_BODY = 400_000 # a talk with the model: the last turns and up to two small ACCOUNTS = ("tg_start", "tg_poll", "tg_register", "tg_me", "tg_link_tiktok", "tg_logout", "tg_delete", "tg_notify", "follow", "unfollow", "following", "followers", "follow_info", "inbox", "inbox_seen") AI = ("ai_status", "ai_chat") -READS = ("ai_status", "lookup", "pair_lookup", "pet_lookup", "species_lookup", "catalog", "item", "profile", "library", "tg_poll", "tg_me", "following", "followers", "follow_info", "inbox") -WRITES = ("ai_chat", "species_offer", "species_answer", "pet_revert", "pet_clear", "tg_start", "tg_register", "tg_link_tiktok", "tg_logout", "tg_delete", "tg_notify", "follow", "unfollow", "inbox_seen", - "shape", "avatar_frame", "mine", "report", "unpublish", "bubble_choose", "prove", "library_add", "library_remove") -UPLOADS = ("frame_upload", "bubble_upload", "pet_upload", "publish") +DUB = ("dub_start", "dub_status") +CODE = ("code_status", "code_chat", "code_consent") # LihonC, the coding agent +READS = ("ai_status", "dub_status", "code_status", "lookup", "pair_lookup", "pet_lookup", "species_lookup", "catalog", "item", "profile", "library", "tg_poll", "tg_me", "following", "followers", "follow_info", "inbox", "music_lookup", "music_mine") +WRITES = ("ai_chat", "dub_start", "code_chat", "code_consent", "species_offer", "species_answer", "pet_revert", "pet_clear", "tg_start", "tg_register", "tg_link_tiktok", "tg_logout", "tg_delete", "tg_notify", "follow", "unfollow", "inbox_seen", + "shape", "avatar_frame", "mine", "report", "unpublish", "bubble_choose", "prove", "library_add", "library_remove", "music_select", "music_clear") +UPLOADS = ("frame_upload", "bubble_upload", "pet_upload", "publish", "music_upload") CATALOG = ("publish", "catalog", "item", "profile", "mine", "report", "unpublish", "install", "bubble_choose", "prove", "library_add", "library_remove", "library") OPERATIONS = ("presence", "lookup", "withdraw", "code", "claim", "shape", "avatar_frame", "frame_upload", "bubble_upload", "pair_lookup", "pair_clear", "pet_upload", "pet_lookup", "pet_revert", "pet_clear", - "species_offer", "species_lookup", "species_answer") + CATALOG + ACCOUNTS + AI + "species_offer", "species_lookup", "species_answer", + "music_upload", "music_lookup", "music_mine", "music_select", "music_clear") + CATALOG + ACCOUNTS + AI + DUB + CODE # The niche-mod badge can be claimed until this moment (Moscow time). CLAIM_DEADLINE = 1794735240 # 2026-11-15 12:34:00 +03:00 @@ -158,6 +164,9 @@ class Registry: db.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('code_secret',?)", (secrets.token_hex(32),)) self.accounts = accounts.Accounts(self) self.ai = ai.AiGate(self) + self.dub = dub.DubManager(self) + self.codegate = codegate.CodeGate(self) + self.music = music.MusicStore(self) @contextmanager def connect(self): @@ -722,6 +731,7 @@ class Limits: key = ip, operation window, count = ((60, 120) if operation in READS else (3600, 10) if operation == "claim" else (3600, 90) if operation == "ai_chat" + else (3600, 1200) if operation == "code_chat" else (3600, 30) if operation in WRITES else (3600, 12) if operation in UPLOADS else (3600, 60) if operation == "install" else (3600, 40)) now = time.monotonic() @@ -757,6 +767,99 @@ class Handler(BaseHTTPRequestHandler): self.end_headers() self.wfile.write(raw) + def send_events(self, stream): + """A streamed answer of LihonC: one server-sent event per piece, then the connection closes.""" + self.send_response(200) + self.send_header("Content-Type", "text/event-stream; charset=utf-8") + self.send_header("Cache-Control", "no-store") + self.send_header("X-Accel-Buffering", "no") # nginx must pass the pieces on at once + self.send_header("Connection", "close") + self.end_headers() + try: + self.connection.settimeout(60) + for event in stream: + self.wfile.write(b"data: " + json.dumps(event, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n\n") + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError, OSError): + pass # the person stopped or went away; the gate still charges what was written + finally: + stream.close() + self.close_connection = True + + def _send_range_bytes(self, data: bytes, content_type: str, cache_control: str = "public, max-age=86400, immutable"): + total = len(data) + rng = self.headers.get("Range") + if rng and rng.startswith("bytes="): + spec = rng[6:].split(",", 1)[0].strip() + if "-" in spec: + start_s, end_s = spec.split("-", 1) + try: + if start_s == "": + suffix = int(end_s) + start = max(0, total - suffix) + end = total - 1 + else: + start = int(start_s) + end = int(end_s) if end_s else total - 1 + if 0 <= start <= end < total: + chunk = data[start:end + 1] + self.send_response(206) + self.send_header("Content-Type", content_type) + self.send_header("Accept-Ranges", "bytes") + self.send_header("Content-Range", "bytes %d-%d/%d" % (start, end, total)) + self.send_header("Cache-Control", cache_control) + self.send_header("Content-Length", str(len(chunk))) + self.end_headers() + self.wfile.write(chunk) + return + except ValueError: + pass + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Accept-Ranges", "bytes") + self.send_header("Cache-Control", cache_control) + self.send_header("Content-Length", str(total)) + self.end_headers() + self.wfile.write(data) + + def _send_range_file(self, file_path: Path, content_type: str, cache_control: str = "private, max-age=3600"): + total = file_path.stat().st_size + start, end, partial = 0, total - 1, False + rng = self.headers.get("Range") + if rng and rng.startswith("bytes="): + spec = rng[6:].split(",", 1)[0].strip() + if "-" in spec: + start_s, end_s = spec.split("-", 1) + try: + if start_s == "": + suffix = int(end_s) + start = max(0, total - suffix) + else: + start = int(start_s) + end = int(end_s) if end_s else total - 1 + if 0 <= start <= end < total: + partial = True + except ValueError: + start, end, partial = 0, total - 1, False + length = end - start + 1 + self.send_response(206 if partial else 200) + self.send_header("Content-Type", content_type) + self.send_header("Accept-Ranges", "bytes") + if partial: + self.send_header("Content-Range", "bytes %d-%d/%d" % (start, end, total)) + self.send_header("Cache-Control", cache_control) + self.send_header("Content-Length", str(length)) + self.end_headers() + with file_path.open("rb") as fh: + fh.seek(start) + remaining = length + while remaining > 0: + chunk = fh.read(min(65536, remaining)) + if not chunk: + break + self.wfile.write(chunk) + remaining -= len(chunk) + def do_GET(self): match = re.fullmatch(r"/members/v1/art/([0-9a-f]{24})\.png", self.path) if match: @@ -770,6 +873,20 @@ class Handler(BaseHTTPRequestHandler): self.end_headers() self.wfile.write(data) return + music_match = re.fullmatch(r"/members/v1/music/([0-9a-f]{24})\.mp3", self.path) + if music_match: + data = self.server.registry.music.bytes(music_match.group(1)) + if data is None: + return self.send_json(404, {"error": "Not found"}) + self._send_range_bytes(data, "audio/mpeg") + return + dub_match = re.fullmatch(r"/members/v1/dub/([0-9a-f]{24})\.mp4", self.path) + if dub_match: + fp = self.server.registry.dub.file_path(dub_match.group(1)) + if fp is None: + return self.send_json(404, {"error": "Not found"}) + self._send_range_file(fp, "video/mp4") + return self.send_json(200 if self.path == "/members/v1/health" else 404, {"ok": True} if self.path == "/members/v1/health" else {"error": "Not found"}) @@ -783,7 +900,7 @@ class Handler(BaseHTTPRequestHandler): return self.send_json(429, {"error": "Try again later"}) try: length = int(self.headers.get("Content-Length", "0")) - if not 0 < length <= (CHAT_BODY if operation == "ai_chat" else UPLOAD_BODY if operation in UPLOADS else 8192): + if not 0 < length <= (CHAT_BODY if operation == "ai_chat" else codegate.BODY if operation == "code_chat" else music.UPLOAD_BODY if operation == "music_upload" else UPLOAD_BODY if operation in UPLOADS else 8192): return self.send_json(413, {"error": "Invalid payload size"}) self.connection.settimeout(10) payload = json.loads(self.rfile.read(length)) @@ -795,6 +912,13 @@ class Handler(BaseHTTPRequestHandler): result = self.server.registry.accounts.call(operation, payload) elif operation in AI: result = self.server.registry.ai.call(operation, payload) + elif operation in DUB: + result = self.server.registry.dub.call(operation, payload) + elif operation in CODE: + payload["_ip"] = ip # the gate keeps only a salted hash of it; a "_ip" sent by the client is overwritten here + result = self.server.registry.codegate.call(operation, payload) + if isinstance(result, codegate.Stream): + return self.send_events(result) elif operation == "lookup": result = self.server.registry.lookup(payload.get("uids")) elif operation == "code": @@ -834,6 +958,18 @@ class Handler(BaseHTTPRequestHandler): elif operation == "avatar_frame": result = self.server.registry.avatar_frame(payload.get("uid"), payload.get("installation"), payload.get("frame"), payload.get("unique_id")) + elif operation == "music_upload": + result = self.server.registry.music.upload(payload.get("uid"), payload.get("installation"), + payload.get("unique_id"), payload.get("title"), + payload.get("artist"), payload.get("mp3")) + elif operation == "music_lookup": + result = self.server.registry.music.lookup(payload.get("uid"), payload.get("unique_id")) + elif operation == "music_mine": + result = self.server.registry.music.mine(payload.get("uid"), payload.get("installation")) + elif operation == "music_select": + result = self.server.registry.music.select(payload.get("uid"), payload.get("installation"), payload.get("id")) + elif operation == "music_clear": + result = self.server.registry.music.clear(payload.get("uid"), payload.get("installation")) else: result = self.server.registry.presence(payload.get("uid"), payload.get("installation"), operation == "withdraw", payload.get("frame_color", "green")) self.send_json(200, result) @@ -851,8 +987,12 @@ def main(): parser.add_argument("--revoke-supporter", metavar="UID", help="Revoke the LihonT supporter badge locally") parser.add_argument("--grant-frame", nargs=2, metavar=("UID", "FRAME"), help="Give an account a closed frame (vip.name) or a whole pack (vip.*)") parser.add_argument("--revoke-frame", nargs=2, metavar=("UID", "FRAME"), help="Take a closed frame away from an account") + parser.add_argument("--code-unban", metavar="DEVICE", help="Let a device back into LihonC (the code from its ban message)") args = parser.parse_args() Path(args.database).resolve().parent.mkdir(parents=True, exist_ok=True) + if args.code_unban: + print(json.dumps({"devices": Registry(args.database).codegate.unban(args.code_unban.strip().lower())})) + return if args.grant_frame or args.revoke_frame: registry = Registry(args.database) uid, frame = args.grant_frame or args.revoke_frame diff --git a/skills/lihont-ltp/SKILL.md b/skills/lihont-ltp/SKILL.md index 912af2b..21352df 100644 --- a/skills/lihont-ltp/SKILL.md +++ b/skills/lihont-ltp/SKILL.md @@ -35,10 +35,10 @@ plugin.save() ``` - **Про что**: `plugin.video(...)`, `plugin.name(...)`, `plugin.screen(...)`. -- **Если** (необязательно, без него «всегда»): `word("слово")`, `hashtag("тег")`, `author("ник")`, `person("id")`, `account("ник")`, `me`, `between("22:00","07:00")`, `weekday("fri")`, `morning/day/evening/night`, `friday/weekend`; сочетания `a & b` (и), `a | b` (или), `~a` (не). Несколько слов в одном условии значат «или»: `hashtag("fyp","foryou")`. +- **Если** (необязательно, без него «всегда»): `word("слово")`, `hashtag("тег")`, `author("ник")`, `person("id")`, `account("ник")`, `me`, `between("22:00","07:00")`, `weekday("fri")`, `morning/day/evening/night`, `friday/weekend`; про само видео: `shorter(15)`, `longer(60)`, `likes(min=1000)`, `comments(min=10)`, `shares(min=5)`, `plays(min=10000)`, `fresh(7)`, `older(30)`, `followers(min=100000)`, `verified`, `photo`, `liked`, `music("phonk")`, `chance(10)`; сочетания `a & b` (и), `a | b` (или), `~a` (не). Несколько слов в одном условии значат «или»: `hashtag("fyp","foryou")`. В `likes/...` можно `min=`, `max=` или обе границы. - **Тема оформления**: `plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b", on_accent="#2b1d3a", radius=20)`. Цвета `#rrggbb` маленькими буквами; radius 0–40, outline 0–6, shadow 0–12; `bevel`, `tick_box`, `title_bars` для вида Windows 95. Тема только красит (ничего не прячет и не двигает), правила в таком плагине не нужны. Следи за контрастом: текст на карточках и на акценте не ниже 3.0, иначе защитник предупредит. - **Значки кнопок в ленте**: `plugin.icons(like="heart.png", comment="bubble.png", collect="star.png", share="plane.png")`. Кнопки: like, comment, collect, share; картинки png/gif/webp до 400 КБ лежат рядом со скриптом. Кнопки остаются на месте и работают как раньше, меняется только картинка. Правила в таком плагине не нужны. -- **Что сделать**: `hide` (только в `video`), `say("текст")` (подсказка, `limit=1` чтобы не чаще раза в день), `before("…")`, `after("…")`, `rename("…")` (только в `name`), `picture("файл", size=…, right=…, bottom=…, opacity=…, movable=True, on_tap=[wiggle, sound("x.ogg"), like], pet="…")`, `download("https://…", "имя.png")` (только в `screen`). +- **Что сделать**: `hide` (только в `video`), `keep` (белый список: оставить видео, даже если другое правило его прячет), `say("текст")` (подсказка, `limit=1` чтобы не чаще раза в день), `before("…")`, `after("…")`, `rename("…")` (только в `name`), `picture("файл", size=…, right=…, bottom=…, opacity=…, movable=True, on_tap=[wiggle, sound("x.ogg"), like], pet="…")`, `download("https://…", "имя.png")` (только в `screen`). - В `picture`: `like` ставит лайк по нажатию, поэтому добавляй его, только если человек прямо попросил. - Лицензия и ИИ: всегда ставь `license="MIT"` (или `"VCBFU-2"`) и `ai="<какая модель написала>"`. Без лицензии защитник отметит замечание, а для полки «проверенные» нужна MIT или VCBFU-2. - По-русски то же самое: `from lihont_ltp.ru import *` (`Плагин`, `.видео`, `.имя`, `.экран`, `скрыть`, `сказать`, `после`, `ночь`, `я`…). @@ -49,14 +49,14 @@ plugin.save() | Можно | Нельзя | |---|---| -| Скрыть видео по слову в описании, хэштегу, автору, времени, дню недели, аккаунту | Видеть дату публикации, длину, число лайков или звук видео (пока) | +| Скрыть видео по слову, хэштегу, автору, времени, дню недели, аккаунту, длительности, лайкам, свежести, музыке, галочке, типу; оставить выбранное белым списком (`keep`) | Читать комментарии и сообщения; видеть, что человек делает в других приложениях | | Дописать текст перед именем или после, подменить имя (только у человека на экране) | Менять что-то у других людей | | Короткая подсказка (до 80 знаков, не чаще лимита) | Читать чаты, комментарии, пароли, личные данные | | Картинка поверх приложения с анимацией, звуком, перетаскиванием, лайком по нажатию | Запускать код, вызывать любые функции | | Скачать картинку или звук (https, до 400 КБ, названный сайт, два согласия человека) | Ходить в интернет иначе; скачивать другое; отправлять данные | | Тема оформления: цвета, радиус, контур, тень, объёмные рамки, галочки, полосы заголовков | Прятать, двигать и добавлять элементы экрана | | Значки кнопок ленты (лайк, комментарии, избранное, поделиться): только картинка | Прятать, двигать кнопки и менять, что они делают | -| Лимиты: до 32 правил, до 8 действий в правиле, до 8 файлов по 400 КБ, всего 1 МБ | Темы, виджеты, кнопки: этого вида плагинов пока нет | +| Лимиты: до 32 правил, до 8 действий в правиле, до 8 файлов по 400 КБ, всего 1 МБ | Свои кнопки и виджеты в интерфейсе: этого вида плагинов нет | Если просят то, чего в левой колонке нет, скажи прямо: это пока невозможно. Не изобретай несуществующие функции и не предлагай обходные пути через код. @@ -78,4 +78,4 @@ plugin.save() ## Примеры в репозитории -`sdk/lihont-ltp/examples/` (`01_hide_hashtag.py` … `06_download.py`), готовый плагин `plugins/examples/vasya.bez-fyp.ltp`, полное руководство `docs/plugins-guide.md`, справочник `docs/plugins.md`. +`sdk/lihont-ltp/examples/` (`01_hide_hashtag.py` … `11_white_list.py`), готовый плагин `plugins/examples/vasya.bez-fyp.ltp`, полное руководство `docs/plugins-guide.md`, справочник `docs/plugins.md`. diff --git a/src/lihont/two/account/AccountCleaner.java b/src/lihont/two/account/AccountCleaner.java new file mode 100644 index 0000000..46abedb --- /dev/null +++ b/src/lihont/two/account/AccountCleaner.java @@ -0,0 +1,297 @@ +package lihont.two.account; + +import android.os.Handler; +import android.os.Looper; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Массовая очистка аккаунта TikTok: снятие лайков, удаление репостов и отписка от подписок. + * + * Запросы идут через собственный подписанный стек TikTok ({@code IRetrofitService} -> {@code CommonApi}), + * поэтому к каждому запросу автоматически подставляются текущие куки сессии и подписи TTNet. + * Очистка запускается только вручную с экрана настроек, с паузой между запросами и кнопкой «Стоп». + */ +public final class AccountCleaner { + public enum Kind { + REPOSTS("репосты"), + LIKES("лайки"), + FOLLOWING("подписки"); + + public final String title; + + Kind(String title) { + this.title = title; + } + } + + public interface Progress { + void onStep(int removed, int failed, String detail); + void onDone(boolean stopped, int removed, int failed, String message); + } + + private static final String DEFAULT_HOST = "https://api16-normal-c-useast1a.tiktokv.com"; + private static final long STEP_DELAY_MS = 450L; + private static final int MAX_PAGES = 200; + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + + private AccountCleaner() {} + + /** Запускает очистку выбранной категории в фоне; возвращённый флаг позволяет остановить цикл. */ + public static AtomicBoolean start(final Kind kind, final Progress progress) { + final AtomicBoolean stop = new AtomicBoolean(false); + new Thread(() -> run(kind, stop, progress), "lihont-cleaner-" + kind.name()).start(); + return stop; + } + + private static void run(Kind kind, AtomicBoolean stop, Progress progress) { + int removed = 0; + int failed = 0; + try { + Session s = currentSession(); + if (s == null) { + finish(progress, false, 0, 0, "Сначала войдите в аккаунт TikTok"); + return; + } + Object api = commonApi(); + if (api == null) { + finish(progress, false, 0, 0, "Не удалось получить сетевой клиент TikTok"); + return; + } + + if (kind == Kind.REPOSTS) { + long offset = 0L; + for (int page = 0; page < MAX_PAGES && !stop.get(); page++) { + Map q = new HashMap(); + q.put("user_id", s.uid); + q.put("offset", String.valueOf(offset)); + q.put("count", "20"); + q.put("scene", "0"); + q.put("carrier_type", "0"); + JSONObject json = call(api, false, "tiktok/v1/upvote/item/list", q); + JSONArray list = firstArray(json, "aweme_list", "upvote_list", "items"); + if (list == null || list.length() == 0) break; + for (int i = 0; i < list.length() && !stop.get(); i++) { + JSONObject item = list.optJSONObject(i); + if (item == null) continue; + String awemeId = optAny(item, "aweme_id", "item_id"); + String repostId = optAny(item, "repost_id"); + if (repostId.isEmpty() && item.has("upvote_info")) { + JSONObject info = item.optJSONObject("upvote_info"); + if (info != null) repostId = optAny(info, "repost_id", "upvote_id"); + } + if (awemeId.isEmpty()) continue; + Map body = new HashMap(); + body.put("item_id", awemeId); + body.put("carrier_type", "0"); + if (!repostId.isEmpty()) body.put("repost_id", repostId); + if (isOk(call(api, true, "tiktok/v1/upvote/delete", body))) removed++; + else failed++; + step(progress, removed, failed, "Убрано репостов: " + removed); + pause(stop); + } + if (!hasMore(json)) break; + offset = json.optLong("offset", offset + list.length()); + } + } else if (kind == Kind.LIKES) { + long cursor = 0L; + for (int page = 0; page < MAX_PAGES && !stop.get(); page++) { + Map q = new HashMap(); + q.put("user_id", s.uid); + if (!s.secUid.isEmpty()) q.put("sec_user_id", s.secUid); + q.put("max_cursor", String.valueOf(cursor)); + q.put("count", "20"); + JSONObject json = call(api, false, "/aweme/v1/aweme/favorite/", q); + JSONArray list = firstArray(json, "aweme_list"); + if (list == null || list.length() == 0) break; + for (int i = 0; i < list.length() && !stop.get(); i++) { + JSONObject item = list.optJSONObject(i); + String awemeId = item == null ? "" : optAny(item, "aweme_id", "item_id"); + if (awemeId.isEmpty()) continue; + Map params = new HashMap(); + params.put("aweme_id", awemeId); + params.put("type", "0"); + params.put("channel_id", "0"); + if (isOk(call(api, false, "/aweme/v1/commit/item/digg/", params))) removed++; + else failed++; + step(progress, removed, failed, "Снято лайков: " + removed); + pause(stop); + } + if (!hasMore(json)) break; + cursor = json.optLong("max_cursor", 0L); + if (cursor <= 0L) break; + } + } else if (kind == Kind.FOLLOWING) { + long maxTime = 0L; + int offset = 0; + for (int page = 0; page < MAX_PAGES && !stop.get(); page++) { + Map q = new HashMap(); + q.put("user_id", s.uid); + if (!s.secUid.isEmpty()) q.put("sec_user_id", s.secUid); + q.put("max_time", String.valueOf(maxTime)); + q.put("count", "20"); + q.put("offset", String.valueOf(offset)); + q.put("source_type", "1"); + q.put("address_book_access", "0"); + JSONObject json = call(api, false, "/aweme/v1/user/following/list/", q); + JSONArray list = firstArray(json, "followings", "user_list"); + if (list == null || list.length() == 0) break; + for (int i = 0; i < list.length() && !stop.get(); i++) { + JSONObject u = list.optJSONObject(i); + String targetUid = u == null ? "" : optAny(u, "uid", "user_id"); + String targetSec = u == null ? "" : optAny(u, "sec_uid", "sec_user_id"); + if (targetUid.isEmpty()) continue; + Map params = new HashMap(); + params.put("user_id", targetUid); + if (!targetSec.isEmpty()) params.put("sec_user_id", targetSec); + params.put("type", "0"); + params.put("from", "19"); + if (isOk(call(api, false, "/aweme/v1/commit/follow/user/", params))) removed++; + else failed++; + step(progress, removed, failed, "Отписок: " + removed); + pause(stop); + } + if (!hasMore(json)) break; + long nextTime = json.optLong("min_time", 0L); + if (nextTime > 0L) maxTime = nextTime; + else offset += list.length(); + } + } + + boolean wasStopped = stop.get(); + String msg = (wasStopped ? "Остановлено. " : "Готово. ") + + "Убрано: " + removed + (failed > 0 ? ", не удалось: " + failed : ""); + finish(progress, wasStopped, removed, failed, msg); + } catch (Throwable error) { + finish(progress, stop.get(), removed, failed, + "Ошибка (" + removed + " убрано): " + error.getMessage()); + } + } + + private static final class Session { + final String uid; + final String secUid; + + Session(String uid, String secUid) { + this.uid = uid; + this.secUid = secUid; + } + } + + private static Session currentSession() { + try { + Class sm = Class.forName("com.ss.android.ugc.aweme.framework.services.ServiceManager"); + Object inst = sm.getMethod("get").invoke(null); + Class apiCls = Class.forName("com.ss.android.ugc.aweme.IAccountUserService"); + Object svc = sm.getMethod("getService", Class.class).invoke(inst, apiCls); + if (svc == null || !Boolean.TRUE.equals(apiCls.getMethod("isLogin").invoke(svc))) return null; + String uid = (String) apiCls.getMethod("getCurUserId").invoke(svc); + if (uid == null || uid.trim().isEmpty()) return null; + String secUid = ""; + try { + Object user = apiCls.getMethod("getCurUser").invoke(svc); + if (user != null) { + Object s = user.getClass().getMethod("getSecUid").invoke(user); + if (s != null) secUid = s.toString(); + } + } catch (Throwable ignored) {} + return new Session(uid, secUid); + } catch (Throwable ignored) { + return null; + } + } + + private static Object commonApi() { + try { + String host = DEFAULT_HOST; + try { + Class hosts = Class.forName("X.05nt"); + Field f = hosts.getDeclaredField("LIZJ"); + f.setAccessible(true); + Object v = f.get(null); + if (v instanceof String && ((String) v).startsWith("https://")) host = (String) v; + } catch (Throwable ignored) {} + Class sm = Class.forName("com.ss.android.ugc.aweme.framework.services.ServiceManager"); + Object inst = sm.getMethod("get").invoke(null); + Class retroSvcCls = Class.forName("com.ss.android.ugc.aweme.framework.services.IRetrofitService"); + Object retroSvc = sm.getMethod("getService", Class.class).invoke(inst, retroSvcCls); + Object retrofit = retroSvcCls.getMethod("createNewRetrofit", String.class).invoke(retroSvc, host); + Class commonCls = Class.forName("com.ss.android.ugc.aweme.net.CommonApi"); + return retrofit.getClass().getMethod("create", Class.class).invoke(retrofit, commonCls); + } catch (Throwable ignored) { + return null; + } + } + + private static JSONObject call(Object api, boolean post, String path, Map params) throws Exception { + String name = post ? "doPost" : "doGet"; + Method m = api.getClass().getMethod(name, String.class, Map.class); + Object callObj = m.invoke(api, path, params); + Object resp = callObj.getClass().getMethod("execute").invoke(callObj); + Field bodyField = resp.getClass().getDeclaredField("LIZIZ"); + bodyField.setAccessible(true); + Object raw = bodyField.get(resp); + if (!(raw instanceof String) || ((String) raw).trim().isEmpty()) { + return new JSONObject(); + } + return new JSONObject((String) raw); + } + + static boolean isOk(JSONObject json) { + return json != null && json.optInt("status_code", -1) == 0; + } + + static boolean hasMore(JSONObject json) { + if (json == null) return false; + if (json.has("has_more")) { + Object v = json.opt("has_more"); + if (v instanceof Boolean) return ((Boolean) v).booleanValue(); + if (v instanceof Number) return ((Number) v).intValue() != 0; + } + return false; + } + + static JSONArray firstArray(JSONObject json, String... keys) { + if (json == null) return null; + for (String key : keys) { + JSONArray a = json.optJSONArray(key); + if (a != null && a.length() > 0) return a; + } + return null; + } + + static String optAny(JSONObject obj, String... keys) { + for (String key : keys) { + String v = obj.optString(key, ""); + if (v != null && !v.isEmpty() && !"null".equals(v)) return v; + } + return ""; + } + + private static void pause(AtomicBoolean stop) { + if (stop.get()) return; + try { + Thread.sleep(STEP_DELAY_MS); + } catch (InterruptedException ignored) { + stop.set(true); + } + } + + private static void step(final Progress progress, final int removed, final int failed, final String detail) { + if (progress == null) return; + MAIN.post(() -> progress.onStep(removed, failed, detail)); + } + + private static void finish(final Progress progress, final boolean stopped, + final int removed, final int failed, final String msg) { + if (progress == null) return; + MAIN.post(() -> progress.onDone(stopped, removed, failed, msg)); + } +} diff --git a/src/lihont/two/agent/AgentClient.java b/src/lihont/two/agent/AgentClient.java index f955710..5c45dd3 100644 --- a/src/lihont/two/agent/AgentClient.java +++ b/src/lihont/two/agent/AgentClient.java @@ -17,7 +17,7 @@ public final class AgentClient { public static final class Problem extends Exception { public final boolean needLogin; - Problem(String message, boolean needLogin) { + public Problem(String message, boolean needLogin) { super(message); this.needLogin = needLogin; } @@ -45,6 +45,25 @@ public final class AgentClient { } } + /** Status of a server-side TikTok video dubbing job. */ + public static final class DubState { + public final String jobId; + public final String status; + public final String stage; + public final String summary; + public final String error; + public final String url; + + DubState(String jobId, String status, String stage, String summary, String error, String url) { + this.jobId = jobId; + this.status = status; + this.stage = stage; + this.summary = summary; + this.error = error; + this.url = url; + } + } + private static final String BOT_LINK = "https://t.me/lihonTauthbot"; private AgentClient() { @@ -97,6 +116,42 @@ public final class AgentClient { } } + /** Starts server-side AI translation + Russian dubbing for a TikTok video link. */ + public static DubState dubStart(Context context, String url) throws Problem { + try { + JSONObject reply = MemberClient.post("dub_start", base(context).put("url", url), 15000); + String path = reply.optString("path", ""); + return new DubState( + reply.optString("job_id", ""), + reply.optString("status", "queued"), + reply.optString("stage", "В очереди…"), + reply.optString("summary", ""), + reply.optString("error", ""), + path.isEmpty() ? "" : MemberClient.API + path + ); + } catch (Exception error) { + throw explain(error); + } + } + + /** Polls the current progress/result of a video dubbing job. */ + public static DubState dubStatus(Context context, String jobId) throws Problem { + try { + JSONObject reply = MemberClient.post("dub_status", base(context).put("job_id", jobId), 12000); + String path = reply.optString("path", ""); + return new DubState( + reply.optString("job_id", jobId), + reply.optString("status", ""), + reply.optString("stage", ""), + reply.optString("summary", ""), + reply.optString("error", ""), + path.isEmpty() ? "" : MemberClient.API + path + ); + } catch (Exception error) { + throw explain(error); + } + } + // ---- signing in with Telegram -------------------------------------------------------------------------------- /** A link that opens the bot; the first person to press Start in it is the one the phone is tied to. */ diff --git a/src/lihont/two/badge/MemberClient.java b/src/lihont/two/badge/MemberClient.java index 3d4c68d..f363bb6 100644 --- a/src/lihont/two/badge/MemberClient.java +++ b/src/lihont/two/badge/MemberClient.java @@ -21,7 +21,7 @@ import java.util.Set; * about the user. A failed request never gives anyone a badge. */ public final class MemberClient { - static final String API = "https://lihont.space/members/v1/"; + public static final String API = "https://lihont.space/members/v1/"; private MemberClient() {} diff --git a/src/lihont/two/bar/BarStyle.java b/src/lihont/two/bar/BarStyle.java index 8f9b6e4..a598c35 100644 --- a/src/lihont/two/bar/BarStyle.java +++ b/src/lihont/two/bar/BarStyle.java @@ -205,7 +205,7 @@ final class BarStyle implements ViewTreeObserver.OnPreDrawListener, View.OnAttac } } - /** TikTok 47.1.3's seek bar (X.1AJh): the spec it aims for (X.1AJj) and its track drawable (X.1AJi) hold the line's height. */ + /** TikTok's seek bar (47.1.3 X.1AJh, 47.7.2 X.08Ik): the spec it aims for and its track drawable hold the line's height. */ private static final float SEEK_THIN = 6f; private static final float SEEK_STEADY = 12f; private static java.lang.reflect.Field seekSpec, seekSpecHeight, seekTrackHeight; @@ -219,7 +219,22 @@ final class BarStyle implements ViewTreeObserver.OnPreDrawListener, View.OnAttac try { if (!seekFieldsTried) { seekFieldsTried = true; - seekSpec = bar.getClass().getDeclaredField("LLJJJ"); + // the spec is the field whose class holds the float fields LIZ and LIZIZ and is not a drawable: named LLJJJ on + // TikTok 47.1.3 and LLJJJIL on 47.7.2, so it is found by what it holds, not by its name + for (java.lang.reflect.Field field : bar.getClass().getDeclaredFields()) { + Class type = field.getType(); + if (type.isPrimitive() || android.graphics.drawable.Drawable.class.isAssignableFrom(type) + || !type.getName().startsWith("X.")) continue; + try { + if (type.getDeclaredField("LIZ").getType() == float.class && type.getDeclaredField("LIZIZ").getType() == float.class) { + seekSpec = field; + break; + } + } catch (NoSuchFieldException notIt) { + // another helper object of the seek bar + } + } + if (seekSpec == null) return; seekSpec.setAccessible(true); Object spec = seekSpec.get(bar); if (spec != null) { diff --git a/src/lihont/two/bar/BottomBar.java b/src/lihont/two/bar/BottomBar.java index d135530..3cf4112 100644 --- a/src/lihont/two/bar/BottomBar.java +++ b/src/lihont/two/bar/BottomBar.java @@ -46,6 +46,16 @@ public final class BottomBar { } catch (Throwable ignored) { // The feed tabs are decoration too. } + try { + lihont.two.feed.RestReminder.onResumed(activity); + } catch (Throwable ignored) { + // The break reminder is an extra. + } + try { + lihont.two.look.AntiBurn.onResumed(activity); + } catch (Throwable ignored) { + // The OLED shift is an extra. + } try { ModSettings settings = SettingsHost.active(); if (settings != null && !settings.md3()) return; diff --git a/src/lihont/two/bar/ProfileMenu.java b/src/lihont/two/bar/ProfileMenu.java index d04947e..284d341 100644 --- a/src/lihont/two/bar/ProfileMenu.java +++ b/src/lihont/two/bar/ProfileMenu.java @@ -51,7 +51,8 @@ final class ProfileMenu { static void watch(final Activity activity, final ModSettings.Theme theme) { final View decor = activity.getWindow().getDecorView(); if (WATCHED.containsKey(decor)) return; - final int list = id(activity, LIST); + // the menu's list; where a TikTok version has no such id, the whole panel holds the rows just as well + final int list = id(activity, LIST) != 0 ? id(activity, LIST) : id(activity, PANEL); if (list == 0) return; WATCHED.put(decor, Boolean.TRUE); decor.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { diff --git a/src/lihont/two/comments/CommentPanel.java b/src/lihont/two/comments/CommentPanel.java index 9573162..98de412 100644 --- a/src/lihont/two/comments/CommentPanel.java +++ b/src/lihont/two/comments/CommentPanel.java @@ -137,9 +137,20 @@ final class CommentPanel { String pkg = activity.getPackageName(); int listId = resources.getIdentifier(LIST, "id", pkg); int panelId = resources.getIdentifier(PANEL, "id", pkg); - if (listId == 0 || panelId == 0) return null; + if (listId == 0) return null; View list = findShown(decor, listId); if (list == null) return null; + if (panelId == 0) { + // a TikTok version without the panel's id: the panel is the list's ancestor that spans the whole screen width and + // most of its height, just under the window's content + View best = null; + for (android.view.ViewParent parent = list.getParent(); parent instanceof View; parent = parent.getParent()) { + View view = (View) parent; + if (view.getId() == android.R.id.content) break; + if (view.getWidth() >= decor.getWidth() - 2 && view.getHeight() >= decor.getHeight() * 0.5f) best = view; + } + return best; + } for (android.view.ViewParent parent = list.getParent(); parent instanceof View; parent = parent.getParent()) { if (((View) parent).getId() == panelId) return (View) parent; } @@ -284,6 +295,7 @@ final class CommentPanel { if (text.getCurrentHintTextColor() != palette.onSurfaceVariant) { text.setHintTextColor(palette.onSurfaceVariant); } + QuickReplies.attach(text, palette); } View row = sheetView(ICON_ROW); if (row instanceof ViewGroup && ((ViewGroup) row).getChildCount() == ICONS_IDLE) { diff --git a/src/lihont/two/comments/CommentTranslator.java b/src/lihont/two/comments/CommentTranslator.java new file mode 100644 index 0000000..9347629 --- /dev/null +++ b/src/lihont/two/comments/CommentTranslator.java @@ -0,0 +1,310 @@ +package lihont.two.comments; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.os.Handler; +import android.os.Looper; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.WeakHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import lihont.two.agent.AgentClient; +import lihont.two.store.LoginActivity; + +/** + * Перевод комментариев и описаний видео через встроенного ИИ-агента мода. + * + * Кнопка «Перевести» появляется на карточках комментариев (рядом с «Ответить») и в шапке шторки + * для описания текущего видео. Переводы кэшируются в памяти (до 200 строк), чтобы повторное + * переключение оригинал/перевод не тратило дневной лимит запросов агента. + */ +public final class CommentTranslator { + private static final String PREFS = "lihont_comments"; + private static final String KEY_ON = "translate_ai"; + private static final String TAG_BTN = "lihont_translate_btn"; + private static final String TAG_VIDEO_BTN = "lihont_translate_video_btn"; + private static final int MAX_CACHE = 200; + + private static final ExecutorService POOL = Executors.newCachedThreadPool(); + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + private static final Map CACHE = Collections.synchronizedMap( + new LinkedHashMap(64, 0.75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > MAX_CACHE; + } + }); + private static final WeakHashMap STATES = new WeakHashMap(); + + private static volatile Boolean cachedOn; + + private static final class State { + String source; + String translated; + boolean shown; + boolean busy; + } + + public interface Callback { + void done(boolean ok, String text, String error, boolean needLogin); + } + + private CommentTranslator() {} + + public static boolean enabled(Context context) { + Boolean value = cachedOn; + if (value != null) return value.booleanValue(); + if (context == null) return true; + try { + value = Boolean.valueOf(prefs(context).getBoolean(KEY_ON, true)); + } catch (Throwable ignored) { + value = Boolean.TRUE; + } + cachedOn = value; + return value.booleanValue(); + } + + public static void setEnabled(Context context, boolean on) { + cachedOn = Boolean.valueOf(on); + if (context == null) return; + try { + prefs(context).edit().putBoolean(KEY_ON, on).apply(); + } catch (Throwable ignored) {} + } + + /** Текст запроса для ИИ-агента: короткий точный перевод на русский без пояснений. */ + public static String buildPrompt(String text) { + return "Переведи этот текст на русский язык. Верни ТОЛЬКО готовый перевод, без пояснений и кавычек:\n\n" + text; + } + + /** Асинхронный перевод через встроенного ИИ-агента (с кэшем по исходному тексту). */ + public static void translate(final Context context, final String raw, final Callback callback) { + final String text = raw == null ? "" : raw.trim(); + if (text.isEmpty()) { + MAIN.post(() -> callback.done(false, "", "Нечего переводить", false)); + return; + } + String hit = CACHE.get(text); + if (hit != null) { + MAIN.post(() -> callback.done(true, hit, null, false)); + return; + } + POOL.execute(() -> { + try { + JSONArray history = new JSONArray().put( + new JSONObject().put("role", "user").put("text", buildPrompt(text))); + AgentClient.Answer answer = AgentClient.talk(context, history, Collections.emptyList(), 0); + String translated = answer.text == null ? "" : answer.text.trim(); + if (translated.isEmpty()) { + MAIN.post(() -> callback.done(false, "", "Агент вернул пустой перевод", false)); + return; + } + CACHE.put(text, translated); + MAIN.post(() -> callback.done(true, translated, null, false)); + } catch (AgentClient.Problem problem) { + MAIN.post(() -> callback.done(false, "", problem.getMessage(), problem.needLogin)); + } catch (Throwable error) { + MAIN.post(() -> callback.done(false, "", "Не удалось перевести", false)); + } + }); + } + + /** Прикрепляет кнопку «Перевести» рядом с «Ответить» на карточке комментария. */ + static void attachComment(final Activity activity, View bodyView, View replyView, int accentColor, boolean dark) { + if (!enabled(activity) || !(bodyView instanceof TextView) || replyView == null) return; + if (!(replyView.getParent() instanceof ViewGroup)) return; + final TextView body = (TextView) bodyView; + final ViewGroup bar = (ViewGroup) replyView.getParent(); + + State state = syncState(body); + TextView btn = findByTag(bar, TAG_BTN); + if (btn == null) { + btn = makeChip(activity, TAG_BTN, "Перевести", accentColor, dark); + int idx = bar.indexOfChild(replyView); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + float d = activity.getResources().getDisplayMetrics().density; + lp.leftMargin = Math.round(10 * d); + lp.gravity = Gravity.CENTER_VERTICAL; + bar.addView(btn, idx >= 0 ? idx + 1 : bar.getChildCount(), lp); + } else { + btn.setTextColor(accentColor); + } + updateButtonLabel(btn, state); + final TextView actionBtn = btn; + btn.setOnClickListener(v -> toggleTranslation(activity, body, actionBtn, null)); + } + + /** Кнопка перевода описания текущего видео в шапке шторки комментариев. */ + static void attachVideoCaption(final Activity activity, final View decor, View countView, int accentColor, boolean dark) { + if (!enabled(activity) || countView == null || !(countView.getParent() instanceof ViewGroup)) return; + ViewGroup header = (ViewGroup) countView.getParent(); + TextView btn = findByTag(header, TAG_VIDEO_BTN); + if (btn == null) { + btn = makeChip(activity, TAG_VIDEO_BTN, "🌐 Видео", accentColor, dark); + float d = activity.getResources().getDisplayMetrics().density; + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + lp.leftMargin = Math.round(8 * d); + lp.gravity = Gravity.CENTER_VERTICAL; + header.addView(btn, lp); + } else { + btn.setTextColor(accentColor); + } + final TextView actionBtn = btn; + btn.setOnClickListener(v -> { + TextView desc = findVisibleFeedDesc(activity, decor); + if (desc == null) { + Toast.makeText(activity, "Описание видео на экране не найдено", Toast.LENGTH_SHORT).show(); + return; + } + toggleTranslation(activity, desc, actionBtn, "🌐 Видео"); + }); + } + + private static void toggleTranslation(final Activity activity, final TextView target, + final TextView button, final String baseLabel) { + final State state = syncState(target); + if (state.busy || state.source.isEmpty()) return; + if (state.shown) { + state.shown = false; + target.setText(state.source); + updateButtonLabel(button, state, baseLabel); + return; + } + if (state.translated != null) { + state.shown = true; + target.setText(formatTranslated(state.source, state.translated)); + updateButtonLabel(button, state, baseLabel); + return; + } + final String expectedSource = state.source; + state.busy = true; + button.setText("Перевод…"); + translate(activity, expectedSource, (ok, translated, error, needLogin) -> { + state.busy = false; + if (!target.isAttachedToWindow()) return; + // Защита от переиспользования View в RecyclerView + if (!expectedSource.equals(state.source)) return; + if (!ok) { + updateButtonLabel(button, state, baseLabel); + if (needLogin) { + Toast.makeText(activity, "Нужен вход через Telegram в настройках LihonT → ИИ-помощник", Toast.LENGTH_LONG).show(); + try { + activity.startActivity(new Intent(activity, LoginActivity.class)); + } catch (Throwable ignored) {} + } else { + Toast.makeText(activity, error != null ? error : "Ошибка перевода", Toast.LENGTH_SHORT).show(); + } + return; + } + state.translated = translated; + state.shown = true; + target.setText(formatTranslated(expectedSource, translated)); + updateButtonLabel(button, state, baseLabel); + }); + } + + static String formatTranslated(String original, String translated) { + return original + "\n\n🌐 ИИ: " + translated; + } + + private static State syncState(TextView tv) { + CharSequence cs = tv.getText(); + String current = cs == null ? "" : cs.toString(); + State state = STATES.get(tv); + if (state == null) { + state = new State(); + state.source = current; + STATES.put(tv, state); + return state; + } + String formatted = state.translated == null ? null : formatTranslated(state.source, state.translated); + if (!current.equals(state.source) && !current.equals(formatted)) { + state.source = current; + state.translated = CACHE.get(current.trim()); + state.shown = false; + state.busy = false; + } + return state; + } + + private static void updateButtonLabel(TextView btn, State state) { + updateButtonLabel(btn, state, null); + } + + private static void updateButtonLabel(TextView btn, State state, String baseLabel) { + if (state.busy) btn.setText("Перевод…"); + else if (state.shown) btn.setText("Оригинал"); + else btn.setText(baseLabel != null ? baseLabel : "Перевести"); + } + + private static TextView makeChip(Activity activity, String tag, String text, int color, boolean dark) { + TextView tv = new TextView(activity); + tv.setTag(tag); + tv.setText(text); + tv.setTextColor(color); + tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f); + float d = activity.getResources().getDisplayMetrics().density; + tv.setPadding(Math.round(6 * d), Math.round(2 * d), Math.round(6 * d), Math.round(2 * d)); + tv.setBackgroundColor(dark ? Color.argb(26, 255, 255, 255) : Color.argb(18, 0, 0, 0)); + return tv; + } + + private static TextView findByTag(ViewGroup group, String tag) { + for (int i = 0; i < group.getChildCount(); i++) { + View child = group.getChildAt(i); + if (tag.equals(child.getTag()) && child instanceof TextView) return (TextView) child; + } + return null; + } + + /** Ищет видимый TextView описания видео на текущем экране TikTok. */ + private static TextView findVisibleFeedDesc(Activity activity, View decor) { + String pkg = activity.getPackageName(); + String[] candidates = {"desc", "video_desc", "tv_desc"}; + for (String name : candidates) { + int resId = activity.getResources().getIdentifier(name, "id", pkg); + if (resId == 0) continue; + TextView found = findTextViewById(decor, resId); + if (found != null) return found; + } + return null; + } + + private static TextView findTextViewById(View root, int id) { + if (root == null) return null; + if (root.getId() == id && root.isShown() && root instanceof TextView) { + CharSequence t = ((TextView) root).getText(); + if (t != null && t.toString().trim().length() > 0) return (TextView) root; + } + if (root instanceof ViewGroup) { + ViewGroup g = (ViewGroup) root; + for (int i = 0; i < g.getChildCount(); i++) { + TextView hit = findTextViewById(g.getChildAt(i), id); + if (hit != null) return hit; + } + } + return null; + } + + private static SharedPreferences prefs(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/src/lihont/two/comments/LongComments.java b/src/lihont/two/comments/LongComments.java new file mode 100644 index 0000000..10829be --- /dev/null +++ b/src/lihont/two/comments/LongComments.java @@ -0,0 +1,59 @@ +package lihont.two.comments; + +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; + +import lihont.two.widget.AppContext; + +/** + * The switch for long comments. TikTok's comment box takes its limit from + * {@code CommentCharLimitConfig.charLimit}, which is 2200 by default; its own long-comment experiment knows + * 10000. See lihont/long_comments_patch.py for the one method that reads that limit. With the switch on the + * answer is at least 10000, with it off TikTok's own answer is returned untouched. + * + * The server still decides whether a comment longer than 2200 is accepted; nothing here sends or claims + * anything. The switch is on by default and lives in its own small file of preferences, because it is a + * choice about the app and not about one account. + */ +public final class LongComments { + private static final String TAG = "LIHONT"; + private static final String PREFS = "lihont_long_comments"; + private static final String KEY = "long"; + private static final int LIMIT = 10000; + private static boolean logged; + + private LongComments() {} + + /** Called with TikTok's own char limit; true when the comment box should allow long comments. */ + public static int limit(int original) { + if (!enabled(AppContext.get())) return original; + int result = Math.max(original, LIMIT); + if (!logged) { + logged = true; + try { + Log.i(TAG, "long comments: " + original + " -> " + result); + } catch (Throwable noLogger) { + // diagnostic only + } + } + return result; + } + + public static boolean enabled(Context context) { + if (context == null) return true; + try { + return prefs(context).getBoolean(KEY, true); + } catch (RuntimeException unreadable) { + return true; + } + } + + public static void set(Context context, boolean on) { + prefs(context).edit().putBoolean(KEY, on).apply(); + } + + private static SharedPreferences prefs(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/src/lihont/two/comments/QuickReplies.java b/src/lihont/two/comments/QuickReplies.java new file mode 100644 index 0000000..7ac05dd --- /dev/null +++ b/src/lihont/two/comments/QuickReplies.java @@ -0,0 +1,497 @@ +package lihont.two.comments; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.res.ColorStateList; +import android.graphics.Color; +import android.graphics.Typeface; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.GradientDrawable; +import android.graphics.drawable.RippleDrawable; +import android.os.Build; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.EditText; +import android.widget.HorizontalScrollView; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.TextView; + +import org.json.JSONArray; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.WeakHashMap; + +import lihont.two.settings.Md3; + +/** + * Быстрые заготовленные фразы над полем ввода комментариев в TikTok. + * Показываются в виде горизонтального ряда чипсов через PopupWindow над полем ввода, + * когда поле в фокусе и пустое. Прячутся при появлении текста, потере фокуса или закрытии. + */ +public final class QuickReplies { + + private static final String PREFS_NAME = "lihont_look"; + private static final String KEY_PHRASES = "quick_replies"; + private static final String KEY_ENABLED = "quick_replies_on"; + + public static final List DEFAULT_PHRASES = Collections.unmodifiableList( + Arrays.asList("🔥🔥🔥", "😂", "Жиза", "Красиво", "Где это?", "Песня?") + ); + public static final int MAX_PHRASES = 10; + public static final int MAX_PHRASE_LENGTH = 40; + + private static final WeakHashMap ATTACHED = + new WeakHashMap(); + + private QuickReplies() {} + + /** + * Прикрепляет контроллер быстрых ответов к полю ввода. + * Повторные вызовы для одного и того же EditText безопасны (обновляют палитру оформления). + */ + public static void attach(EditText edit, Md3.Palette palette) { + if (edit == null) return; + try { + synchronized (ATTACHED) { + QuickRepliesController controller = ATTACHED.get(edit); + if (controller != null) { + controller.updatePalette(palette); + return; + } + controller = new QuickRepliesController(edit, palette); + ATTACHED.put(edit, controller); + controller.init(); + } + } catch (Throwable ignored) {} + } + + /** + * Список сохранённых фраз для быстрых ответов (максимум 10 фраз по 40 символов). + */ + public static List phrases(Context context) { + if (context == null) return new ArrayList(DEFAULT_PHRASES); + try { + SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); + String raw = prefs.getString(KEY_PHRASES, null); + if (raw == null) { + return new ArrayList(DEFAULT_PHRASES); + } + JSONArray array = new JSONArray(raw); + List result = new ArrayList(); + for (int i = 0; i < array.length() && result.size() < MAX_PHRASES; i++) { + String item = array.optString(i, null); + if (item != null) { + item = item.trim(); + if (!item.isEmpty()) { + if (item.length() > MAX_PHRASE_LENGTH) { + item = item.substring(0, MAX_PHRASE_LENGTH); + } + result.add(item); + } + } + } + return result; + } catch (Throwable ignored) { + return new ArrayList(DEFAULT_PHRASES); + } + } + + /** + * Сохраняет список фраз (не более 10 фраз, обрезанных до 40 символов). + */ + public static void setPhrases(Context context, List phrases) { + if (context == null) return; + try { + JSONArray array = new JSONArray(); + if (phrases != null) { + int count = 0; + for (String p : phrases) { + if (p == null) continue; + String clean = p.trim(); + if (clean.isEmpty()) continue; + if (clean.length() > MAX_PHRASE_LENGTH) { + clean = clean.substring(0, MAX_PHRASE_LENGTH); + } + array.put(clean); + count++; + if (count >= MAX_PHRASES) break; + } + } + SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); + prefs.edit().putString(KEY_PHRASES, array.toString()).apply(); + } catch (Throwable ignored) {} + } + + /** + * Включена ли функция быстрых ответов (по умолчанию true). + */ + public static boolean enabled(Context context) { + if (context == null) return true; + try { + SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); + return prefs.getBoolean(KEY_ENABLED, true); + } catch (Throwable ignored) { + return true; + } + } + + /** + * Переключает состояние функции быстрых ответов. + */ + public static void setEnabled(Context context, boolean enabled) { + if (context == null) return; + try { + SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); + prefs.edit().putBoolean(KEY_ENABLED, enabled).apply(); + } catch (Throwable ignored) {} + } + + /** + * Управляет жизненным циклом и отображением всплывающего окна над полем ввода. + */ + private static final class QuickRepliesController { + private final EditText edit; + private Md3.Palette palette; + private PopupWindow popup; + private View contentView; + private boolean initialized; + + QuickRepliesController(EditText edit, Md3.Palette palette) { + this.edit = edit; + this.palette = palette; + } + + void updatePalette(Md3.Palette newPalette) { + // CommentPanel calls attach on every pass: rebuild only when the colours really changed + if (newPalette == this.palette) return; + this.palette = newPalette; + try { + if (popup != null && popup.isShowing()) { + buildAndShow(); + } + } catch (Throwable ignored) {} + } + + void init() { + if (initialized) return; + initialized = true; + + try { + Context context = edit.getContext(); + popup = new PopupWindow(context); + popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); + popup.setFocusable(false); + popup.setOutsideTouchable(false); + popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); + if (Build.VERSION.SDK_INT >= 21) { + popup.setElevation(Md3.dp(context, 4f)); + } + + edit.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { + @Override + public void onViewAttachedToWindow(View v) { + check(); + } + + @Override + public void onViewDetachedFromWindow(View v) { + dismiss(); + } + }); + + edit.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { + @Override + public void onLayoutChange(View v, int left, int top, int right, int bottom, + int oldLeft, int oldTop, int oldRight, int oldBottom) { + try { + if (popup != null && popup.isShowing()) { + updatePosition(); + } else { + check(); + } + } catch (Throwable ignored) {} + } + }); + + edit.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + + @Override + public void onTextChanged(CharSequence s, int start, int count, int after) {} + + @Override + public void afterTextChanged(Editable s) { + try { + if (s != null && s.length() > 0) { + dismiss(); + } else { + check(); + } + } catch (Throwable ignored) {} + } + }); + + final View.OnFocusChangeListener existing = edit.getOnFocusChangeListener(); + edit.setOnFocusChangeListener(new View.OnFocusChangeListener() { + @Override + public void onFocusChange(View v, boolean hasFocus) { + if (existing != null) { + try { + existing.onFocusChange(v, hasFocus); + } catch (Throwable ignored) {} + } + try { + if (hasFocus) { + check(); + } else { + dismiss(); + } + } catch (Throwable ignored) {} + } + }); + + edit.post(new Runnable() { + @Override + public void run() { + check(); + } + }); + } catch (Throwable ignored) {} + } + + void check() { + try { + if (edit == null) return; + Context context = edit.getContext(); + if (!QuickReplies.enabled(context)) { + dismiss(); + return; + } + CharSequence text = edit.getText(); + if (text != null && text.length() > 0) { + dismiss(); + return; + } + if (!edit.isFocused()) { + dismiss(); + return; + } + if (!edit.isAttachedToWindow() || !edit.isShown()) { + dismiss(); + return; + } + buildAndShow(); + } catch (Throwable ignored) {} + } + + void buildAndShow() { + try { + if (edit.getWindowToken() == null) { + edit.post(new Runnable() { + @Override + public void run() { + check(); + } + }); + return; + } + + Context context = edit.getContext(); + List items = QuickReplies.phrases(context); + if (items == null || items.isEmpty()) { + dismiss(); + return; + } + + HorizontalScrollView scroll = new HorizontalScrollView(context); + scroll.setHorizontalScrollBarEnabled(false); + scroll.setOverScrollMode(View.OVER_SCROLL_IF_CONTENT_SCROLLS); + scroll.setClipToPadding(false); + + LinearLayout row = new LinearLayout(context); + row.setOrientation(LinearLayout.HORIZONTAL); + row.setGravity(Gravity.CENTER_VERTICAL); + int padH = Md3.dp(context, 12f); + int padV = Md3.dp(context, 4f); + row.setPadding(padH, padV, padH, padV); + + int marginEnd = Md3.dp(context, 8f); + + for (int i = 0; i < items.size(); i++) { + final String phrase = items.get(i); + TextView chip = new TextView(context); + chip.setText(phrase); + chip.setTextSize(Md3.LABEL_LARGE); + chip.setTextColor(palette != null ? palette.onSurface : Color.WHITE); + chip.setTypeface(Typeface.create("sans-serif", Typeface.NORMAL)); + chip.setIncludeFontPadding(false); + chip.setGravity(Gravity.CENTER); + chip.setSingleLine(true); + chip.setClickable(true); + chip.setFocusable(false); + + int chipPadH = Md3.dp(context, 12f); + int chipPadV = Md3.dp(context, 6f); + chip.setPadding(chipPadH, chipPadV, chipPadH, chipPadV); + chip.setMinimumHeight(Md3.dp(context, 32f)); + + int bgColor = palette != null ? palette.surfaceContainerHigh : Color.DKGRAY; + int outlineColor = palette != null ? palette.outlineVariant : Color.GRAY; + int onSurfaceColor = palette != null ? palette.onSurface : Color.WHITE; + + GradientDrawable bg = Md3.shape(bgColor, Md3.SHAPE_SMALL, context); + bg.setStroke(Math.max(1, Md3.dp(context, 1f)), outlineColor); + + Drawable ripple = new RippleDrawable( + ColorStateList.valueOf(Md3.stateLayerColor(onSurfaceColor)), + bg, + Md3.shape(Color.WHITE, Md3.SHAPE_SMALL, context) + ); + chip.setBackground(ripple); + + chip.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + insert(phrase); + } + }); + + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ); + if (i < items.size() - 1) { + lp.rightMargin = marginEnd; + } + row.addView(chip, lp); + } + + scroll.addView(row, new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT + )); + + contentView = scroll; + popup.setContentView(contentView); + + View anchor = findAnchor(edit); + int rootWidth = edit.getRootView() != null ? edit.getRootView().getWidth() : 0; + if (rootWidth <= 0) rootWidth = context.getResources().getDisplayMetrics().widthPixels; + + contentView.measure( + View.MeasureSpec.makeMeasureSpec(rootWidth, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) + ); + int popupHeight = contentView.getMeasuredHeight(); + if (popupHeight <= 0) popupHeight = Md3.dp(context, 40f); + + int[] loc = new int[2]; + anchor.getLocationInWindow(loc); + + if (loc[1] <= 0 && anchor.getHeight() == 0) { + anchor.post(new Runnable() { + @Override + public void run() { + check(); + } + }); + return; + } + + int gap = Md3.dp(context, 4f); + int x = 0; + int y = loc[1] - popupHeight - gap; + if (y < 0) y = 0; + + popup.setWidth(rootWidth); + popup.setHeight(popupHeight); + + if (popup.isShowing()) { + popup.update(x, y, rootWidth, popupHeight); + } else { + popup.showAtLocation(anchor, Gravity.TOP | Gravity.START, x, y); + } + } catch (Throwable ignored) {} + } + + void updatePosition() { + try { + if (popup == null || !popup.isShowing() || contentView == null) return; + View anchor = findAnchor(edit); + Context context = edit.getContext(); + int rootWidth = edit.getRootView() != null ? edit.getRootView().getWidth() : 0; + if (rootWidth <= 0) rootWidth = context.getResources().getDisplayMetrics().widthPixels; + + contentView.measure( + View.MeasureSpec.makeMeasureSpec(rootWidth, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) + ); + int popupHeight = contentView.getMeasuredHeight(); + if (popupHeight <= 0) popupHeight = Md3.dp(context, 40f); + + int[] loc = new int[2]; + anchor.getLocationInWindow(loc); + + int gap = Md3.dp(context, 4f); + int x = 0; + int y = loc[1] - popupHeight - gap; + if (y < 0) y = 0; + + popup.update(x, y, rootWidth, popupHeight); + } catch (Throwable ignored) {} + } + + void insert(String phrase) { + try { + if (phrase == null) return; + Editable editable = edit.getText(); + if (editable != null) { + int start = Math.max(edit.getSelectionStart(), 0); + int end = Math.max(edit.getSelectionEnd(), 0); + int min = Math.min(start, end); + int max = Math.max(start, end); + editable.replace(min, max, phrase); + edit.setSelection(min + phrase.length()); + } else { + edit.setText(phrase); + edit.setSelection(phrase.length()); + } + } catch (Throwable ignored) {} + dismiss(); + } + + void dismiss() { + try { + if (popup != null && popup.isShowing()) { + popup.dismiss(); + } + } catch (Throwable ignored) {} + } + + private static View findAnchor(EditText edit) { + View anchor = edit; + try { + View root = edit.getRootView(); + int rootHeight = root != null ? root.getHeight() : 0; + float maxH = rootHeight > 0 ? rootHeight * 0.35f : Float.MAX_VALUE; + for (android.view.ViewParent p = edit.getParent(); p instanceof View; p = p.getParent()) { + View pv = (View) p; + if (pv.getId() == android.R.id.content) break; + if (pv.getHeight() > 0 && pv.getHeight() < maxH && pv.getWidth() >= edit.getWidth()) { + anchor = pv; + } + } + } catch (Throwable ignored) {} + return anchor; + } + } +} diff --git a/src/lihont/two/feed/Blacklist.java b/src/lihont/two/feed/Blacklist.java new file mode 100644 index 0000000..bd4057f --- /dev/null +++ b/src/lihont/two/feed/Blacklist.java @@ -0,0 +1,119 @@ +package lihont.two.feed; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * Чёрный список ленты: авторы, слова и хэштеги, чьи видео не показываются (см. {@link FeedFilter}). + * + * Одна строка списка — одно правило: + *
    + *
  • {@code @ник} — автор по нику (без учёта регистра, {@code @} необязателен для ника);
  • + *
  • {@code id:...} — автор по uid или secUid TikTok (ник можно сменить, id — нет);
  • + *
  • {@code #тег} — хэштег видео;
  • + *
  • любое другое слово — встречается в описании видео.
  • + *
+ * Пустые строки и пробелы не считаются. Класс без Android: его проверяет тест на обычной Java. + */ +public final class Blacklist { + /** Больше правил человек всё равно не читает, а лента проверяется на каждый элемент. */ + public static final int MAX_RULES = 500; + private static final int MAX_LENGTH = 100; + private static final String ID_PREFIX = "id:"; + + private final String[] nicks; + private final String[] ids; + private final String[] tags; + private final String[] words; + + private Blacklist(String[] nicks, String[] ids, String[] tags, String[] words) { + this.nicks = nicks; + this.ids = ids; + this.tags = tags; + this.words = words; + } + + /** Список правил, каким его хранит {@link BlacklistStore}; неизвестное просто пропускается. */ + public static Blacklist parse(List lines) { + List nicks = new ArrayList(); + List ids = new ArrayList(); + List tags = new ArrayList(); + List words = new ArrayList(); + if (lines != null) { + for (String line : lines) { + if (nicks.size() + ids.size() + tags.size() + words.size() >= MAX_RULES) break; + String rule = normalise(line); + if (rule == null) continue; + if (rule.startsWith(ID_PREFIX)) { + if (rule.length() > ID_PREFIX.length()) ids.add(rule.substring(ID_PREFIX.length())); + } else if (rule.startsWith("@") || rule.startsWith("#")) { + // @ник, #тег; один знак без текста — не правило + if (rule.length() > 1) { + if (rule.charAt(0) == '@') nicks.add(rule.substring(1)); + else tags.add(rule.substring(1)); + } + } else { + words.add(rule); + } + } + } + return new Blacklist(nicks.toArray(new String[0]), ids.toArray(new String[0]), + tags.toArray(new String[0]), words.toArray(new String[0])); + } + + /** Правило без лишних пробелов, в нижнем регистре; null, если оно пустое или слишком длинное. */ + private static String normalise(String line) { + if (line == null) return null; + String rule = line.trim(); + if (rule.isEmpty() || rule.length() > MAX_LENGTH) return null; + return rule.toLowerCase(Locale.ROOT); + } + + /** Нет ни одного правила — ленту трогать нечего. */ + public boolean isEmpty() { + return nicks.length == 0 && ids.length == 0 && tags.length == 0 && words.length == 0; + } + + /** Сколько правил в списке (для строки под полем ввода). */ + public int size() { + return nicks.length + ids.length + tags.length + words.length; + } + + /** + * Попадает ли видео под список. Всё, чего у видео нет, передаётся null; ни один аргумент + * не обязателен, и пустой список никогда ничего не блокирует. + */ + public boolean blocks(String desc, String uniqueId, String uid, String secUid, String[] hashtags) { + if (isEmpty()) return false; + String nick = lower(uniqueId); + for (String rule : nicks) { + if (rule.equals(nick)) return true; + } + String userId = lower(uid); + String secureId = lower(secUid); + for (String rule : ids) { + if (rule.equals(userId) || rule.equals(secureId)) return true; + } + if (tags.length > 0 && hashtags != null) { + for (String tag : hashtags) { + String name = lower(tag); + if (name == null) continue; + for (String rule : tags) { + if (rule.equals(name)) return true; + } + } + } + String text = lower(desc); + if (text != null) { + for (String rule : words) { + if (text.contains(rule)) return true; + } + } + return false; + } + + private static String lower(String value) { + return value == null ? null : value.toLowerCase(Locale.ROOT); + } +} diff --git a/src/lihont/two/feed/BlacklistStore.java b/src/lihont/two/feed/BlacklistStore.java new file mode 100644 index 0000000..fc4da38 --- /dev/null +++ b/src/lihont/two/feed/BlacklistStore.java @@ -0,0 +1,105 @@ +package lihont.two.feed; + +import android.content.Context; +import android.content.SharedPreferences; + +import java.util.ArrayList; +import java.util.List; + +/** + * Хранилище чёрного списка: prefs {@code lihont_feed}, ключ {@code blacklist} (правила по строке), + * переключатель {@code blacklist_on}. Хранится только на телефоне, никуда не отправляется. + * + * Правила читаются один раз и держатся в памяти: лента спрашивает на каждый элемент. После правки + * список нужно перечитать — {@link #reload()}. Ошибки хранилища дают пустой список, чтобы лента + * показывалась как обычно. + */ +public final class BlacklistStore { + private static final String PREFS = "lihont_feed"; + private static final String KEY_RULES = "blacklist"; + private static final String KEY_ON = "blacklist_on"; + + private static volatile Blacklist cached; + private static volatile Boolean cachedOn; + + private BlacklistStore() {} + + /** Список правил как он сохранён (пустые строки выкинуты). */ + public static List rules(Context context) { + List lines = new ArrayList(); + try { + String saved = prefs(context).getString(KEY_RULES, ""); + if (saved != null) { + for (String line : saved.split("\n")) { + if (!line.trim().isEmpty()) lines.add(line.trim()); + } + } + } catch (Throwable ignored) { + // хранилище недоступно — список пуст + } + return lines; + } + + /** Сохраняет правила и перечитывает список. */ + public static boolean save(Context context, List lines) { + try { + StringBuilder joined = new StringBuilder(); + int kept = 0; + for (String line : lines) { + String rule = line == null ? "" : line.trim(); + if (rule.isEmpty()) continue; + if (kept > 0) joined.append('\n'); + joined.append(rule); + kept++; + if (kept >= Blacklist.MAX_RULES) break; + } + prefs(context).edit().putString(KEY_RULES, joined.toString()).apply(); + cached = null; + return true; + } catch (Throwable ignored) { + return false; + } + } + + /** Включён ли фильтр (выключен, пока настройки неизвестны или не читаются). */ + public static boolean enabled(Context context) { + Boolean value = cachedOn; + if (value != null) return value.booleanValue(); + try { + value = Boolean.valueOf(prefs(context).getBoolean(KEY_ON, false)); + } catch (Throwable unavailable) { + value = Boolean.FALSE; + } + cachedOn = value; + return value.booleanValue(); + } + + public static void setEnabled(Context context, boolean on) { + cachedOn = Boolean.valueOf(on); + try { + prefs(context).edit().putBoolean(KEY_ON, on).apply(); + } catch (Throwable ignored) { + // в этом процессе переключатель всё равно уже действует + } + } + + /** Разобранный список для ленты; без контекста — пустой. */ + public static Blacklist current(Context context) { + Blacklist value = cached; + if (value == null) { + value = Blacklist.parse(rules(context)); + cached = value; + } + return value; + } + + /** После правки списка или его чтения с диска. */ + public static void reload() { + cached = null; + cachedOn = null; + } + + private static SharedPreferences prefs(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/src/lihont/two/feed/FeedFilter.java b/src/lihont/two/feed/FeedFilter.java index 35dc833..ce6d1a6 100644 --- a/src/lihont/two/feed/FeedFilter.java +++ b/src/lihont/two/feed/FeedFilter.java @@ -1,5 +1,6 @@ package lihont.two.feed; +import android.content.Context; import android.util.Log; import java.lang.reflect.Field; @@ -32,6 +33,16 @@ public final class FeedFilter { private static volatile Field newRoom; private static volatile Field roomCell; private static volatile Field awemeType; + /** For the black list (see Blacklist): the description, the author and the hashtags of a video. */ + private static volatile Class userClass; + private static volatile Field author; + private static volatile Field desc; + private static volatile Field chaIns; + private static volatile Field userNick; + private static volatile Field userUid; + private static volatile Field userSecUid; + private static volatile Field challengeName; + private static volatile Class challengeClass; private static volatile Class pageClass; private static volatile Field pageItems; @@ -75,6 +86,11 @@ public final class FeedFilter { newRoom = field(owner, "newLiveRoomData"); roomCell = field(owner, "mRoomFeedCellStruct"); awemeType = field(owner, "awemeType"); + author = field(owner, "author"); + desc = field(owner, "desc"); + chaIns = field(owner, "chaIns"); + userClass = null; + challengeClass = null; awemeClass = owner; } @@ -104,6 +120,69 @@ public final class FeedFilter { } } + /** A video of the black list: by its author, a word of its description or one of its hashtags. */ + static boolean isBlacklisted(Object item, Blacklist list) { + if (list == null || list.isEmpty()) return false; + try { + String nick = null; + String uid = null; + String secUid = null; + if (has(author, item)) { + Object user = author.get(item); + if (userClass != user.getClass()) userFields(user.getClass()); + nick = text(userNick, user); + uid = text(userUid, user); + secUid = text(userSecUid, user); + } + String[] hashtags = null; + if (has(chaIns, item) && chaIns.get(item) instanceof List) { + List challenges = (List) chaIns.get(item); + int size = challenges.size(); + if (size > 64) size = 64; + for (int i = 0; i < size; i++) { + String name = null; + Object challenge = challenges.get(i); + if (challenge != null) { + if (challengeClass != challenge.getClass()) challengeFields(challenge.getClass()); + name = text(challengeName, challenge); + } + if (name == null) continue; + if (hashtags == null) hashtags = new String[size]; + hashtags[i] = name; + } + } + return list.blocks(text(desc, item), nick, uid, secUid, hashtags); + } catch (IllegalAccessException | RuntimeException unreadable) { + return false; + } + } + + private static String text(Field field, Object owner) throws IllegalAccessException { + Object value = field == null ? null : field.get(owner); + return value instanceof String ? (String) value : null; + } + + private static synchronized void userFields(Class owner) { + userNick = field(owner, "uniqueId"); + userUid = field(owner, "uid"); + userSecUid = field(owner, "secUid"); + userClass = owner; + } + + private static synchronized void challengeFields(Class owner) { + challengeName = field(owner, "chaName"); + challengeClass = owner; + } + + private static Context context() { + try { + Object app = Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null); + return app instanceof Context ? (Context) app : null; + } catch (Throwable unavailable) { + return null; + } + } + /** * The list without the items the switches remove. The same list comes back when nothing is * removed; a list from the server or a cache is never changed in place. @@ -122,11 +201,15 @@ public final class FeedFilter { boolean ads = SettingsHost.hideAds(); boolean live = SettingsHost.hideLive(); boolean plugins = PluginEngine.feedActive(); - if (!ads && !live && !plugins) return input; + Blacklist blacklist = null; + Context context = context(); + if (context != null && BlacklistStore.enabled(context)) blacklist = BlacklistStore.current(context); + if (!ads && !live && !plugins && blacklist == null) return input; ArrayList kept = null; int removedAds = 0; int removedLive = 0; int removedPlugins = 0; + int removedBlacklist = 0; Map types = new TreeMap(); for (int i = 0, size = input.size(); i < size; i++) { Object item = input.get(i); @@ -143,6 +226,10 @@ public final class FeedFilter { drop = true; removedPlugins++; } + if (!drop && blacklist != null && isBlacklisted(item, blacklist)) { + drop = true; + removedBlacklist++; + } if (!drop) count(types, item); } if (drop) { @@ -154,7 +241,7 @@ public final class FeedFilter { kept.add(item); } } - report(input.size(), removedAds, removedLive + removedPlugins, types); + report(input.size(), removedAds, removedLive + removedPlugins + removedBlacklist, types); return kept == null ? input : kept; } diff --git a/src/lihont/two/feed/PetDiary.java b/src/lihont/two/feed/PetDiary.java new file mode 100644 index 0000000..87addce --- /dev/null +++ b/src/lihont/two/feed/PetDiary.java @@ -0,0 +1,197 @@ +package lihont.two.feed; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.RectF; +import android.graphics.Typeface; +import android.util.TypedValue; +import android.view.View; + +import org.json.JSONObject; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import lihont.two.settings.Md3; + +/** + * «Дневник Серийчика»: сколько минут человек провёл в TikTok за последние дни. + * Данные приходят из {@link RestReminder} ({@code KEY_WATCHED}/{@code KEY_DAY}, + * prefs {@code lihont_look}) и складываются в тот же prefs под ключом + * {@code rest_history} как JSON-объект {"yyyyMMdd": минуты}. Всё хранится + * только на телефоне, никаких сетевых запросов; любая ошибка превращается + * в пустые данные, чтобы TikTok не пострадал. + */ +public final class PetDiary { + private static final String PREFS = "lihont_look"; + private static final String KEY_HISTORY = "rest_history"; + /** Сколько последних дней хранится в истории. */ + private static final int KEEP_DAYS = 30; + + private PetDiary() {} + + /** Сохраняет минуты за день (обычно сегодня) в историю; старше 30 дней забываются. */ + public static void record(Context context, String day, long watchedMs) { + if (context == null || day == null || day.length() != 8) return; + try { + int minutes = (int) (Math.max(0L, watchedMs) / 60_000L); + JSONObject history = read(context); + history.put(day, minutes); + if (history.length() > KEEP_DAYS) { + List days = new ArrayList(); + Iterator keys = history.keys(); + while (keys.hasNext()) days.add(keys.next()); + Collections.sort(days); // "yyyyMMdd" сортируется как дата + int extra = history.length() - KEEP_DAYS; + for (int i = 0; i < extra; i++) history.remove(days.get(i)); + } + prefs(context).edit().putString(KEY_HISTORY, history.toString()).apply(); + } catch (Throwable ignored) { + // дневник не должен уронить TikTok + } + } + + /** Минуты за последние 7 дней, от 6 дней назад до сегодня; 0, если данных нет. */ + public static int[] lastWeek(Context context) { + int[] week = new int[7]; + try { + JSONObject history = read(context); + Calendar now = Calendar.getInstance(); + SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd", Locale.ROOT); + for (int offset = -6; offset <= 0; offset++) { + Calendar day = (Calendar) now.clone(); + day.add(Calendar.DAY_OF_YEAR, offset); + week[offset + 6] = Math.max(0, history.optInt(fmt.format(day.getTime()), 0)); + } + } catch (Throwable ignored) { + } + return week; + } + + /** + * Одна дружелюбная фраза Серийчика по данным недели, без нотаций. + * Выбор детерминированный: те же данные дают ту же фразу. + */ + public static String petLine(int[] week) { + int[] w = week == null || week.length != 7 ? new int[7] : week; + int today = Math.max(0, w[6]); + int sum = 0; + for (int minutes : w) sum += Math.max(0, minutes); + int avg = sum / 7; + List variants = new ArrayList(); + if (sum == 0) { + variants.add("Пока в дневнике пусто. Покажешь мне, как ты листаешь ленту?"); + variants.add("Тишина в дневнике… Отличный повод погладить кота вместо экрана."); + } else if (today > 60) { + variants.add("Ого, " + today + " минут сегодня! Лента точно вкусная, но и миска супа не помешает."); + variants.add(today + " минут за день? Серийчик разрешает, но хвост уже устал махать."); + } else if (avg > 0 && today < avg) { + variants.add("Сегодня всего " + today + " мин — тише обычного. Серийчик гордится тобой!"); + variants.add("Молодец: сегодня " + today + " мин, меньше среднего. Усы одобряют."); + } else { + variants.add("Сегодня " + today + " мин. Спокойный день — так держать!"); + variants.add(today + " минут сегодня. Ровный график, как у кота на солнышке."); + } + int pick = Math.abs(sum * 31 + today * 7 + avg) % variants.size(); + return variants.get(pick); + } + + /** График: 7 столбиков за последнюю неделю, подписи дней недели и минуты над столбиками. */ + public static View chart(Context context, Md3.Palette palette, int[] week) { + try { + return new Chart(context, palette, week); + } catch (Throwable ignored) { + return new View(context); // пустышка вместо упавшего графика + } + } + + private static JSONObject read(Context context) throws Exception { + return new JSONObject(prefs(context).getString(KEY_HISTORY, "{}")); + } + + private static SharedPreferences prefs(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } + + private static final String[] WEEKDAYS = {"", "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"}; + + /** Свой View со столбиками: рисуется на Canvas, без картинок и библиотек. */ + private static final class Chart extends View { + private final Md3.Palette palette; + private final int[] week; + private final Paint bar = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint label = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint value = new Paint(Paint.ANTI_ALIAS_FLAG); + private final RectF rect = new RectF(); + + Chart(Context context, Md3.Palette palette, int[] week) { + super(context); + this.palette = palette; + this.week = week == null || week.length != 7 ? new int[7] : week; + setMinimumHeight(Md3.dp(context, 160)); + float text = sp(context, 11); + label.setTextSize(text); + label.setColor(palette.onSurfaceVariant); + label.setTextAlign(Paint.Align.CENTER); + value.setTextSize(text); + value.setColor(palette.onSurface); + value.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + value.setTextAlign(Paint.Align.CENTER); + } + + @Override protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + int width = getWidth(); + int height = getHeight(); + if (width <= 0 || height <= 0) return; + try { + float gap = dp(2); + float labelH = label.getTextSize() + dp(6); + float valueH = value.getTextSize() + dp(4); + float chartH = height - labelH - valueH - gap; + if (chartH <= 0) return; + int max = 0; + for (int minutes : week) max = Math.max(max, minutes); + max = Math.max(max, 60); // лёгкий день не должен занимать весь график + float colW = width / 7f; + float barW = Math.min(colW * 0.5f, dp(28)); + int dimmed = (palette.primary & 0x00FFFFFF) | 0x66000000; + Calendar now = Calendar.getInstance(); + for (int i = 0; i < 7; i++) { + float cx = colW * i + colW / 2f; + Calendar day = (Calendar) now.clone(); + day.add(Calendar.DAY_OF_YEAR, i - 6); + canvas.drawText(WEEKDAYS[day.get(Calendar.DAY_OF_WEEK)], cx, + height - labelH + label.getTextSize(), label); + int minutes = week[i]; + if (minutes <= 0) continue; + float barH = chartH * minutes / max; + float top = height - labelH - gap - barH; + rect.set(cx - barW / 2f, top, cx + barW / 2f, height - labelH - gap); + bar.setColor(i == 6 ? palette.primary : dimmed); // сегодня ярче + canvas.drawRoundRect(rect, dp(4), dp(4), bar); + canvas.drawText(String.valueOf(minutes), cx, top - dp(3), value); + } + } catch (Throwable ignored) { + // даже если рисование не получилось — вид останется пустым + } + } + + private float dp(float v) { + return v * getResources().getDisplayMetrics().density; + } + + private float sp(Context context, float v) { + return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, v, + context.getResources().getDisplayMetrics()); + } + } +} diff --git a/src/lihont/two/feed/RestReminder.java b/src/lihont/two/feed/RestReminder.java new file mode 100644 index 0000000..9a129cf --- /dev/null +++ b/src/lihont/two/feed/RestReminder.java @@ -0,0 +1,211 @@ +package lihont.two.feed; + +import android.app.Activity; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; + +import java.lang.ref.WeakReference; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +import lihont.two.settings.Md3; +import lihont.two.settings.ModSettings; +import lihont.two.settings.SettingsHost; + +/** + * A soft reminder to take a break: after the chosen number of minutes in TikTok today, Серийчик shows a small card on top + * of the screen. Nothing is blocked or paused; "Ещё 15 минут" moves the next reminder by 15 minutes, "Хорошо" by the whole + * interval. Time is counted only while TikTok's main screen has the focus (also with the reminder off, for the diary), + * kept on the phone and reset every day. + */ +public final class RestReminder { + private static final String PREFS = "lihont_look"; + private static final String KEY_MINUTES = "rest_minutes"; + private static final String KEY_DAY = "rest_day"; + private static final String KEY_WATCHED = "rest_watched_ms"; + private static final String KEY_NEXT = "rest_next_ms"; + /** The choices offered in the settings, in minutes; 0 is off. */ + public static final int[] CHOICES = {0, 15, 30, 45, 60, 90, 120}; + private static final long TICK_MS = 15_000L; + private static final long SNOOZE_MS = 15 * 60_000L; + + private static WeakReference watched = new WeakReference(null); + private static Handler handler; + private static long lastTick; + private static WeakReference card = new WeakReference(null); + + private RestReminder() {} + + public static int minutes(Context context) { + try { + return prefs(context).getInt(KEY_MINUTES, 0); + } catch (RuntimeException unreadable) { + return 0; + } + } + + public static void setMinutes(Context context, int minutes) { + SharedPreferences.Editor edit = prefs(context).edit().putInt(KEY_MINUTES, minutes); + // a new interval starts counting from the time already spent today + edit.putLong(KEY_NEXT, watchedToday(context) + minutes * 60_000L); + edit.apply(); + } + + /** Minutes spent in TikTok today, as counted by the reminder (0 while it has never been on). */ + public static int minutesToday(Context context) { + return (int) (watchedToday(context) / 60_000L); + } + + /** Called whenever TikTok's main screen comes to the front: (re)starts the ticker for it. */ + public static void onResumed(Activity activity) { + View shown = card.get(); + if (shown != null && (minutes(activity) <= 0 || !shown.isAttachedToWindow())) { + if (shown.getParent() instanceof ViewGroup) ((ViewGroup) shown.getParent()).removeView(shown); + card = new WeakReference(null); + } + // the ticker runs even with the reminder off: the diary (PetDiary) counts the time too + if (watched.get() == activity && handler != null) return; + watched = new WeakReference(activity); + if (handler == null) handler = new Handler(Looper.getMainLooper()); + handler.removeCallbacks(TICK); + lastTick = SystemClock.elapsedRealtime(); + handler.postDelayed(TICK, TICK_MS); + } + + private static final Runnable TICK = new Runnable() { + @Override public void run() { + Activity activity = watched.get(); + if (activity == null || activity.isFinishing() || activity.isDestroyed()) { + watched = new WeakReference(null); + return; + } + try { + tick(activity); + } catch (Throwable ignored) { + // a reminder must never take TikTok down + } + handler.postDelayed(this, TICK_MS); + } + }; + + private static void tick(Activity activity) { + long now = SystemClock.elapsedRealtime(); + long step = Math.min(now - lastTick, TICK_MS + 5_000L); + lastTick = now; + int minutes = minutes(activity); + if (!activity.hasWindowFocus()) return; + SharedPreferences prefs = prefs(activity); + long watchedMs = watchedToday(activity) + step; + long next = prefs.getLong(KEY_NEXT, minutes * 60_000L); + prefs.edit().putString(KEY_DAY, today()).putLong(KEY_WATCHED, watchedMs).apply(); + PetDiary.record(activity, today(), watchedMs); + if (minutes <= 0) return; // the reminder itself is off + View shown = card.get(); + if (watchedMs >= next && (shown == null || !shown.isAttachedToWindow())) { + // the next reminder is set now, so leaving TikTok without a tap does not bring this one back at once + prefs.edit().putLong(KEY_NEXT, watchedMs + minutes * 60_000L).apply(); + show(activity, (int) (watchedMs / 60_000L), minutes); + } + } + + private static long watchedToday(Context context) { + SharedPreferences prefs = prefs(context); + if (!today().equals(prefs.getString(KEY_DAY, ""))) { + int minutes = prefs.getInt(KEY_MINUTES, 0); + prefs.edit().putString(KEY_DAY, today()).putLong(KEY_WATCHED, 0L).putLong(KEY_NEXT, minutes * 60_000L).apply(); + return 0L; + } + return prefs.getLong(KEY_WATCHED, 0L); + } + + private static void show(final Activity activity, int spent, final int interval) { + View root = activity.findViewById(android.R.id.content); + if (!(root instanceof FrameLayout)) return; + final FrameLayout host = (FrameLayout) root; + ModSettings settings = SettingsHost.active(); + Md3.Palette palette = Md3.palette(activity, settings != null ? settings.theme() : ModSettings.Theme.SYSTEM); + + LinearLayout box = new LinearLayout(activity); + box.setOrientation(LinearLayout.VERTICAL); + int pad = Md3.dp(activity, 18); + box.setPadding(pad, pad, pad, Md3.dp(activity, 12)); + android.graphics.drawable.GradientDrawable shape = Md3.shape(palette.surfaceContainerHigh, 24f, activity); + shape.setStroke(Math.max(1, Md3.dp(activity, 1)), palette.outlineVariant); + box.setBackground(shape); + box.setElevation(Md3.dp(activity, 8)); + box.setClickable(true); + + box.addView(Md3.text(activity, "🐾 Серийчик", Md3.LABEL_LARGE, true, palette.onSurfaceVariant)); + TextView line = Md3.text(activity, "Ты в TikTok уже " + spent + " мин. Может, сделаешь перерыв?", + Md3.BODY_LARGE, true, palette.onSurface); + line.setPadding(0, Md3.dp(activity, 6), 0, Md3.dp(activity, 10)); + box.addView(line); + + LinearLayout buttons = new LinearLayout(activity); + buttons.setGravity(Gravity.END); + final TextView later = button(activity, palette, "Ещё 15 минут", false); + final TextView ok = button(activity, palette, "Хорошо", true); + buttons.addView(later); + LinearLayout.LayoutParams gap = new LinearLayout.LayoutParams(-2, -2); + gap.leftMargin = Md3.dp(activity, 8); + buttons.addView(ok, gap); + box.addView(buttons); + + FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP); + int side = Md3.dp(activity, 14); + int top = Md3.dp(activity, 48); + int status = activity.getResources().getIdentifier("status_bar_height", "dimen", "android"); + if (status != 0) top += activity.getResources().getDimensionPixelSize(status); + params.setMargins(side, top, side, 0); + host.addView(box, params); + box.setAlpha(0f); + box.setTranslationY(-Md3.dp(activity, 20)); + box.animate().alpha(1f).translationY(0f).setDuration(220).start(); + card = new WeakReference(box); + + later.setOnClickListener(v -> close(activity, host, box, SNOOZE_MS)); + ok.setOnClickListener(v -> close(activity, host, box, interval * 60_000L)); + // it goes away by itself after half a minute; the next reminder is already set + box.postDelayed(() -> { + if (box.isAttachedToWindow() && card.get() == box) close(activity, host, box, -1L); + }, 30_000L); + } + + /** Removes the card; with more >= 0 the next reminder comes after that much more time in TikTok. */ + private static void close(Context context, final FrameLayout host, final View box, long more) { + if (more >= 0) prefs(context).edit().putLong(KEY_NEXT, watchedToday(context) + more).apply(); + box.animate().alpha(0f).translationY(-Md3.dp(context, 20)).setDuration(180) + .withEndAction(() -> host.removeView(box)).start(); + card = new WeakReference(null); + } + + private static TextView button(Context context, Md3.Palette palette, String label, boolean filled) { + TextView button = Md3.text(context, label, Md3.LABEL_LARGE, true, filled ? palette.onPrimary : palette.primary); + int h = Md3.dp(context, 10); + int w = Md3.dp(context, 16); + button.setPadding(w, h, w, h); + button.setBackground(filled ? Md3.shape(palette.primary, 20f, context) : null); + button.setClickable(true); + button.setFocusable(true); + return button; + } + + private static String today() { + return new SimpleDateFormat("yyyyMMdd", Locale.ROOT).format(new Date()); + } + + private static SharedPreferences prefs(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/src/lihont/two/flags/Flags.java b/src/lihont/two/flags/Flags.java new file mode 100644 index 0000000..98a05f5 --- /dev/null +++ b/src/lihont/two/flags/Flags.java @@ -0,0 +1,191 @@ +package lihont.two.flags; + +import android.content.Context; +import android.content.SharedPreferences; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Overrides for TikTok's server-side AB settings. + * + *

The patched {@code SettingsManager} getters call these methods after TikTok has resolved a + * value. The key is the same string the app sent to the server; the value is whatever the person + * wrote in the editor, one {@code key=value} per line. The map is read once and kept in memory, + * so the extra lookup is a hash map hit rather than a preferences read on every flag. + */ +public final class Flags { + private static final String PREFS = "lihont_flags"; + private static final String KEY_ON = "on"; + private static final String KEY_DATA = "data"; + private static final int MAX_LINES = 500; + + private static volatile Map values; + private static volatile Boolean switchedOn; + + private Flags() { + } + + /** The editor's switch; off until the person turns it on. */ + public static boolean enabled(Context context) { + Boolean value = switchedOn; + if (value == null) { + value = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY_ON, false); + switchedOn = value; + } + return value; + } + + /** The lines shown in the editor, in the order they were saved. */ + public static List lines(Context context) { + String data = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_DATA, ""); + List lines = new ArrayList(); + if (data != null) { + for (String line : data.split("\n")) { + String trimmed = line.trim(); + if (!trimmed.isEmpty()) lines.add(trimmed); + } + } + return lines; + } + + public static void save(Context context, List lines, boolean on) { + List kept = new ArrayList(); + for (String line : lines) { + String trimmed = line == null ? "" : line.trim(); + if (trimmed.isEmpty() || trimmed.startsWith("#")) continue; + if (kept.size() >= MAX_LINES) break; + kept.add(trimmed); + } + String data = join(kept); + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putBoolean(KEY_ON, on) + .putString(KEY_DATA, data) + .apply(); + values = parse(kept); + switchedOn = on; + } + + public static void reload() { + values = null; + switchedOn = null; + } + + public static boolean bool(String key, boolean original) { + String value = value(key); + if (value == null) return original; + if ("true".equalsIgnoreCase(value) || "1".equals(value)) return true; + if ("false".equalsIgnoreCase(value) || "0".equals(value)) return false; + return original; + } + + public static int number(String key, int original) { + String value = value(key); + if (value == null) return original; + try { + return Integer.parseInt(value); + } catch (NumberFormatException ignored) { + return original; + } + } + + public static long longer(String key, long original) { + String value = value(key); + if (value == null) return original; + try { + return Long.parseLong(value); + } catch (NumberFormatException ignored) { + return original; + } + } + + public static float decimal(String key, float original) { + String value = value(key); + if (value == null) return original; + try { + return Float.parseFloat(value); + } catch (NumberFormatException ignored) { + return original; + } + } + + public static double precise(String key, double original) { + String value = value(key); + if (value == null) return original; + try { + return Double.parseDouble(value); + } catch (NumberFormatException ignored) { + return original; + } + } + + public static String text(String key, String original) { + String value = value(key); + return value == null ? original : value; + } + + private static String value(String key) { + ensure(); + Map map = values; + if (map == null || key == null) return null; + return map.get(key); + } + + private static void ensure() { + if (values != null) return; + synchronized (Flags.class) { + if (values != null) return; + Context context = application(); + if (context == null) return; + SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + boolean on = prefs.getBoolean(KEY_ON, false); + List lines = new ArrayList(); + String data = prefs.getString(KEY_DATA, ""); + if (data != null) { + for (String line : data.split("\n")) { + if (!line.trim().isEmpty()) lines.add(line); + } + } + values = parse(on ? lines : Collections.emptyList()); + switchedOn = on; + } + } + + private static Map parse(List lines) { + Map parsed = new HashMap(); + for (String line : lines) { + int at = line.indexOf('='); + if (at <= 0) continue; + String key = line.substring(0, at).trim(); + String value = line.substring(at + 1).trim(); + if (key.isEmpty()) continue; + if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { + value = value.substring(1, value.length() - 1); + } + parsed.put(key, value); + } + return parsed; + } + + private static String join(List lines) { + StringBuilder out = new StringBuilder(); + for (String line : lines) { + if (out.length() > 0) out.append('\n'); + out.append(line); + } + return out.toString(); + } + + private static Context application() { + try { + Class thread = Class.forName("android.app.ActivityThread"); + Object app = thread.getMethod("currentApplication").invoke(null); + return app instanceof Context ? (Context) app : null; + } catch (Throwable ignored) { + return null; + } + } +} diff --git a/src/lihont/two/ghost/Ghost.java b/src/lihont/two/ghost/Ghost.java index 5c56f9d..54068a8 100644 --- a/src/lihont/two/ghost/Ghost.java +++ b/src/lihont/two/ghost/Ghost.java @@ -18,8 +18,10 @@ public final class Ghost { private static final String PREFS = "lihont_ghost"; private static final String STORIES = "stories"; private static final String MESSAGES = "messages"; + private static final String KEEP_RECALLED = "keep_recalled"; private static boolean logged; private static boolean loggedMessages; + private static boolean loggedRecalled; private Ghost() {} @@ -41,12 +43,7 @@ public final class Ghost { } public static boolean messagesOn(Context context) { - if (context == null) return false; - try { - return prefs(context).getBoolean(MESSAGES, false); - } catch (RuntimeException unreadable) { - return false; - } + return readFlag(context, MESSAGES); } public static void setMessages(Context context, boolean on) { @@ -68,18 +65,44 @@ public final class Ghost { } public static boolean storiesOn(Context context) { - if (context == null) return false; - try { - return prefs(context).getBoolean(STORIES, false); - } catch (RuntimeException unreadable) { - return false; - } + return readFlag(context, STORIES); } public static void setStories(Context context, boolean on) { prefs(context).edit().putBoolean(STORIES, on).apply(); } + /** Asked by the IM Message model: true means recalled messages stay visible in the chat. */ + public static boolean keepRecalled() { + boolean on = keepRecalledOn(AppContext.get()); + if (on && !loggedRecalled) { + loggedRecalled = true; + try { + Log.i(TAG, "ghost: keeping recalled messages"); + } catch (Throwable noLogger) { + // diagnostic only + } + } + return on; + } + + public static boolean keepRecalledOn(Context context) { + return readFlag(context, KEEP_RECALLED); + } + + public static void setKeepRecalled(Context context, boolean on) { + prefs(context).edit().putBoolean(KEEP_RECALLED, on).apply(); + } + + private static boolean readFlag(Context context, String key) { + if (context == null) return false; + try { + return prefs(context).getBoolean(key, false); + } catch (RuntimeException unreadable) { + return false; + } + } + private static SharedPreferences prefs(Context context) { return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); } diff --git a/src/lihont/two/look/AntiBurn.java b/src/lihont/two/look/AntiBurn.java new file mode 100644 index 0000000..182e249 --- /dev/null +++ b/src/lihont/two/look/AntiBurn.java @@ -0,0 +1,89 @@ +package lihont.two.look; + +import android.app.Activity; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Handler; +import android.os.Looper; +import android.view.View; + +import java.lang.ref.WeakReference; + +/** + * OLED anti-burn: shifts the whole screen by one pixel once a minute. + * + *

Static parts of the interface (the island, tabs, counters) would otherwise sit on the same + * pixels for hours. A one-pixel walk around the screen is invisible in use and keeps those pixels + * from settling. The switch is in the look settings and is on by default. + */ +public final class AntiBurn { + private static final String PREFS = "lihont_look"; + private static final String KEY = "anti_burn"; + private static final long STEP_MS = 60_000L; + private static final int[][] WALK = { + {0, 0}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, + }; + + private static WeakReference watched = new WeakReference(null); + private static Handler handler; + private static int step; + + private AntiBurn() { + } + + public static boolean enabled(Context context) { + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY, true); + } + + public static void setEnabled(Context context, boolean on) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY, on).apply(); + } + + /** Called whenever TikTok's main screen comes to the front. */ + public static void onResumed(Activity activity) { + if (!enabled(activity)) { + reset(activity); + return; + } + watched = new WeakReference(activity); + if (handler == null) handler = new Handler(Looper.getMainLooper()); + handler.removeCallbacks(TICK); + handler.postDelayed(TICK, STEP_MS); + } + + private static final Runnable TICK = new Runnable() { + @Override public void run() { + Activity activity = watched.get(); + if (activity == null || activity.isFinishing() || activity.isDestroyed()) { + watched = new WeakReference(null); + return; + } + try { + if (!enabled(activity)) { + reset(activity); + return; + } + if (activity.hasWindowFocus()) { + View decor = activity.getWindow().getDecorView(); + int pixel = Math.max(1, Math.round(activity.getResources().getDisplayMetrics().density)); + int[] shift = WALK[step++ % WALK.length]; + decor.setTranslationX(shift[0] * pixel); + decor.setTranslationY(shift[1] * pixel); + } + } catch (Throwable ignored) { + // A cosmetic shift must never take TikTok down. + } + handler.postDelayed(this, STEP_MS); + } + }; + + private static void reset(Activity activity) { + try { + View decor = activity.getWindow().getDecorView(); + decor.setTranslationX(0f); + decor.setTranslationY(0f); + } catch (Throwable ignored) { + // Nothing to reset. + } + } +} diff --git a/src/lihont/two/look/FontsAndEmoji.java b/src/lihont/two/look/FontsAndEmoji.java new file mode 100644 index 0000000..3557682 --- /dev/null +++ b/src/lihont/two/look/FontsAndEmoji.java @@ -0,0 +1,380 @@ +package lihont.two.look; + +import android.app.Activity; +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Typeface; +import android.graphics.fonts.Font; +import android.graphics.fonts.FontFamily; +import android.net.Uri; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewTreeObserver; +import android.widget.TextView; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.WeakHashMap; + +/** + * Выбор системного или пользовательского шрифта и пака эмодзи (включая Twemoji .ttf). + * + * На Android 10+ (API 29+) шрифт текста и цветной эмодзи-пак собираются через + * {@link Typeface.CustomFallbackBuilder}: выбранный шрифт идёт основным семейством, а эмодзи + * добавляются первым резервным семейством. При выборе не-стандартного шрифта также обновляются + * статические поля {@link Typeface} и TextView на экранах через {@link Windows#attach(Activity)}. + */ +public final class FontsAndEmoji { + private static final String PREFS = "lihont_look"; + private static final String KEY_FONT = "font_mode"; + private static final String KEY_EMOJI = "emoji_mode"; + private static final String KEY_FONT_NAME = "font_name"; + private static final String KEY_EMOJI_NAME = "emoji_name"; + + public static final String FONT_DEFAULT = "default"; + public static final String FONT_SYSTEM = "system"; + public static final String FONT_SERIF = "serif"; + public static final String FONT_MONO = "mono"; + public static final String FONT_CUSTOM = "custom"; + + public static final String EMOJI_SYSTEM = "system"; + public static final String EMOJI_TWEMOJI = "twemoji"; + public static final String EMOJI_CUSTOM = "custom"; + + public static final String TWEMOJI_URL = + "https://github.com/mozilla/twemoji-colr/releases/download/v0.7.0/Twemoji.Mozilla.ttf"; + private static final int MAX_TTF_BYTES = 35 * 1024 * 1024; + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + + private static volatile int generation = 1; + private static volatile int builtGen = -1; + private static volatile Typeface cachedFace; + private static final WeakHashMap WATCHERS = new WeakHashMap(); + private static final WeakHashMap STAMPED = new WeakHashMap(); + + public interface DownloadCallback { + void done(boolean ok, String message); + } + + private FontsAndEmoji() {} + + public static String fontMode(Context context) { + if (context == null) return FONT_DEFAULT; + try { + return prefs(context).getString(KEY_FONT, FONT_DEFAULT); + } catch (Throwable ignored) { + return FONT_DEFAULT; + } + } + + public static String emojiMode(Context context) { + if (context == null) return EMOJI_SYSTEM; + try { + return prefs(context).getString(KEY_EMOJI, EMOJI_SYSTEM); + } catch (Throwable ignored) { + return EMOJI_SYSTEM; + } + } + + public static String fontLabel(Context context) { + String mode = fontMode(context); + if (FONT_SYSTEM.equals(mode)) return "Системный"; + if (FONT_SERIF.equals(mode)) return "Serif"; + if (FONT_MONO.equals(mode)) return "Моноширинный"; + if (FONT_CUSTOM.equals(mode)) { + String name = prefs(context).getString(KEY_FONT_NAME, ""); + return (name != null && !name.isEmpty()) ? name : "Свой .ttf"; + } + return "TikTok (стандартный)"; + } + + public static String emojiLabel(Context context) { + String mode = emojiMode(context); + if (EMOJI_TWEMOJI.equals(mode)) return "Twemoji"; + if (EMOJI_CUSTOM.equals(mode)) { + String name = prefs(context).getString(KEY_EMOJI_NAME, ""); + return (name != null && !name.isEmpty()) ? name : "Свой пак .ttf"; + } + return "Системные"; + } + + public static String summary(Context context) { + return "Шрифт: " + fontLabel(context) + " · Эмодзи: " + emojiLabel(context); + } + + public static void setFontMode(Context context, String mode) { + prefs(context).edit().putString(KEY_FONT, mode).apply(); + invalidate(); + applySystemDefaults(context); + } + + public static void setEmojiMode(Context context, String mode) { + prefs(context).edit().putString(KEY_EMOJI, mode).apply(); + invalidate(); + applySystemDefaults(context); + } + + public static boolean isActive(Context context) { + return !FONT_DEFAULT.equals(fontMode(context)) || !EMOJI_SYSTEM.equals(emojiMode(context)); + } + + public static File customFontFile(Context context) { + return new File(context.getFilesDir(), "lihont_font.ttf"); + } + + public static File twemojiFile(Context context) { + return new File(context.getFilesDir(), "lihont_twemoji.ttf"); + } + + public static File customEmojiFile(Context context) { + return new File(context.getFilesDir(), "lihont_emoji_custom.ttf"); + } + + /** Сохраняет выбранный пользователем .ttf/.otf файл шрифта или эмодзи-пака. */ + public static boolean importFile(Context context, Uri uri, boolean emoji, String displayName) { + if (context == null || uri == null) return false; + File dst = emoji ? customEmojiFile(context) : customFontFile(context); + File tmp = new File(dst.getParentFile(), dst.getName() + ".tmp"); + try { + InputStream in = context.getContentResolver().openInputStream(uri); + if (in == null) return false; + int total = 0; + try (InputStream src = in; OutputStream out = new FileOutputStream(tmp)) { + byte[] buf = new byte[16384]; + int n; + while ((n = src.read(buf)) > 0) { + total += n; + if (total > MAX_TTF_BYTES) { + tmp.delete(); + return false; + } + out.write(buf, 0, n); + } + } + // Проверяем, что Android реально может прочитать этот файл как Typeface + Typeface test = Typeface.createFromFile(tmp); + if (test == null || (dst.exists() && !dst.delete()) || !tmp.renameTo(dst)) { + tmp.delete(); + return false; + } + SharedPreferences.Editor edit = prefs(context).edit(); + if (emoji) { + edit.putString(KEY_EMOJI, EMOJI_CUSTOM); + if (displayName != null) edit.putString(KEY_EMOJI_NAME, displayName); + } else { + edit.putString(KEY_FONT, FONT_CUSTOM); + if (displayName != null) edit.putString(KEY_FONT_NAME, displayName); + } + edit.apply(); + invalidate(); + applySystemDefaults(context); + return true; + } catch (Throwable error) { + tmp.delete(); + return false; + } + } + + /** Скачивает цветной пак Twemoji (.ttf ~1.5 МБ) и включает его. */ + public static void downloadTwemoji(final Context context, final DownloadCallback callback) { + new Thread(() -> { + File dst = twemojiFile(context); + File tmp = new File(dst.getParentFile(), dst.getName() + ".tmp"); + HttpURLConnection conn = null; + try { + conn = (HttpURLConnection) new URL(TWEMOJI_URL).openConnection(); + conn.setConnectTimeout(15000); + conn.setReadTimeout(30000); + conn.setInstanceFollowRedirects(true); + int code = conn.getResponseCode(); + if (code != 200) { + post(callback, false, "Сервер вернул HTTP " + code); + return; + } + int total = 0; + try (InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(tmp)) { + byte[] buf = new byte[16384]; + int n; + while ((n = in.read(buf)) > 0) { + total += n; + if (total > MAX_TTF_BYTES) { + tmp.delete(); + post(callback, false, "Файл слишком большой"); + return; + } + out.write(buf, 0, n); + } + } + if (total < 100_000) { + tmp.delete(); + post(callback, false, "Скачался неполный файл"); + return; + } + if ((dst.exists() && !dst.delete()) || !tmp.renameTo(dst)) { + tmp.delete(); + post(callback, false, "Не удалось сохранить файл"); + return; + } + prefs(context).edit().putString(KEY_EMOJI, EMOJI_TWEMOJI).apply(); + invalidate(); + applySystemDefaults(context); + post(callback, true, "Twemoji скачан и включён"); + } catch (Throwable error) { + tmp.delete(); + post(callback, false, "Ошибка скачивания: " + error.getMessage()); + } finally { + if (conn != null) conn.disconnect(); + } + }, "lihont-twemoji-dl").start(); + } + + private static void post(DownloadCallback cb, boolean ok, String msg) { + MAIN.post(() -> cb.done(ok, msg)); + } + + private static void invalidate() { + cachedFace = null; + builtGen = -1; + generation++; + } + + /** Собирает итоговый Typeface (выбранный шрифт + эмодзи-пак fallback при наличии). */ + public static Typeface resolve(Context context) { + int gen = generation; + if (builtGen == gen) return cachedFace; + Typeface face = buildTypeface(context); + cachedFace = face; + builtGen = gen; + return face; + } + + private static Typeface buildTypeface(Context context) { + if (context == null || !isActive(context)) return null; + String font = fontMode(context); + String emoji = emojiMode(context); + + File fontFile = FONT_CUSTOM.equals(font) && customFontFile(context).isFile() + ? customFontFile(context) : null; + File emojiFile = null; + if (EMOJI_TWEMOJI.equals(emoji) && twemojiFile(context).isFile()) emojiFile = twemojiFile(context); + else if (EMOJI_CUSTOM.equals(emoji) && customEmojiFile(context).isFile()) emojiFile = customEmojiFile(context); + + if (emojiFile != null && Build.VERSION.SDK_INT >= 29) { + try { + File primaryFile = fontFile != null ? fontFile : firstExisting( + "/system/fonts/Roboto-Regular.ttf", + "/system/fonts/NotoSans-Regular.ttf", + "/system/fonts/DroidSans.ttf"); + if (primaryFile != null) { + FontFamily primary = new FontFamily.Builder(new Font.Builder(primaryFile).build()).build(); + FontFamily emojiFamily = new FontFamily.Builder(new Font.Builder(emojiFile).build()).build(); + String fallbackName = FONT_SERIF.equals(font) ? "serif" + : (FONT_MONO.equals(font) ? "monospace" : "sans-serif"); + return new Typeface.CustomFallbackBuilder(primary) + .addCustomFallback(emojiFamily) + .setSystemFallback(fallbackName) + .build(); + } + } catch (Throwable ignored) {} + } + + if (fontFile != null) { + try { + return Typeface.createFromFile(fontFile); + } catch (Throwable ignored) {} + } + if (FONT_SERIF.equals(font)) return Typeface.SERIF; + if (FONT_MONO.equals(font)) return Typeface.MONOSPACE; + if (FONT_SYSTEM.equals(font)) return Typeface.DEFAULT; + return null; + } + + private static File firstExisting(String... paths) { + for (String path : paths) { + File f = new File(path); + if (f.isFile()) return f; + } + return null; + } + + /** Меняет стандартные системные Typeface внутри процесса, если выбран кастомный или системный шрифт. */ + public static void applySystemDefaults(Context context) { + if (context == null || !isActive(context)) return; + Typeface face = resolve(context); + if (face == null) return; + try { + setStaticTypeface("DEFAULT", face); + setStaticTypeface("DEFAULT_BOLD", Typeface.create(face, Typeface.BOLD)); + setStaticTypeface("SANS_SERIF", face); + } catch (Throwable ignored) {} + } + + private static void setStaticTypeface(String name, Typeface value) { + try { + Field f = Typeface.class.getDeclaredField(name); + f.setAccessible(true); + f.set(null, value); + } catch (Throwable ignored) {} + } + + /** Следит за экраном и применяет выбранный шрифт/эмодзи ко всем TextView. */ + public static void watch(Activity activity) { + if (activity == null || !isActive(activity)) return; + applySystemDefaults(activity); + try { + View decor = activity.getWindow().getDecorView(); + Watcher w = WATCHERS.get(decor); + if (w == null) { + w = new Watcher(activity, decor); + WATCHERS.put(decor, w); + decor.getViewTreeObserver().addOnGlobalLayoutListener(w); + } + applyTree(decor, resolve(activity), generation); + } catch (Throwable ignored) {} + } + + private static void applyTree(View view, Typeface face, int gen) { + if (face == null || view == null) return; + if (view instanceof TextView) { + TextView tv = (TextView) view; + Integer prev = STAMPED.get(tv); + if (prev == null || prev.intValue() != gen) { + Typeface old = tv.getTypeface(); + int style = old == null ? Typeface.NORMAL : old.getStyle(); + tv.setTypeface(style == Typeface.NORMAL ? face : Typeface.create(face, style)); + STAMPED.put(tv, Integer.valueOf(gen)); + } + } + if (view instanceof ViewGroup) { + ViewGroup g = (ViewGroup) view; + for (int i = 0; i < g.getChildCount(); i++) applyTree(g.getChildAt(i), face, gen); + } + } + + private static final class Watcher implements ViewTreeObserver.OnGlobalLayoutListener { + private final Activity activity; + private final View decor; + + Watcher(Activity activity, View decor) { + this.activity = activity; + this.decor = decor; + } + + @Override public void onGlobalLayout() { + if (!isActive(activity)) return; + applyTree(decor, resolve(activity), generation); + } + } + + private static SharedPreferences prefs(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/src/lihont/two/look/Windows.java b/src/lihont/two/look/Windows.java index 43deb8e..38cb559 100644 --- a/src/lihont/two/look/Windows.java +++ b/src/lihont/two/look/Windows.java @@ -35,6 +35,11 @@ public final class Windows implements Application.ActivityLifecycleCallbacks { public static void attach(Activity activity) { // the recovery mode first: it may reset the look and the plugins before any skin reads them DebugMode.check(activity); + try { + lihont.two.play.PlayControl.warmUp(activity); + lihont.two.profile.ProfileMusic.syncFloatingBar(activity, null); + FontsAndEmoji.watch(activity); + } catch (Throwable ignored) {} try { lihont.two.privacy.AppLock.watch(activity); } catch (Throwable error) { @@ -55,12 +60,14 @@ public final class Windows implements Application.ActivityLifecycleCallbacks { try { // The streak keeper does not depend on the look: it only asks whether today's time has come. lihont.two.streak.AutoFlame.onForeground(activity); - if (!SettingsHost.md3()) return; ModSettings active = SettingsHost.active(); ModSettings.Theme theme = active != null ? active.theme() : ModSettings.Theme.SYSTEM; + if (SettingsHost.md3() || lihont.two.profile.ProfileMusic.enabled(activity)) { + ProfileSkin.watch(activity, theme); + } + if (!SettingsHost.md3()) return; lihont.two.widget.StreakWidget.refreshAll(activity); CommentSkin.watch(activity, theme); - ProfileSkin.watch(activity, theme); // Black backgrounds become the palette's tonal surface, unless pure black (AMOLED) is wanted. Md3.Palette palette = Md3.palette(activity, active != null ? active : ModSettings.defaults()); if (palette.dark && (active == null || !active.amoled())) TonalSurfaces.watch(activity, palette.surface); @@ -87,5 +94,7 @@ public final class Windows implements Application.ActivityLifecycleCallbacks { @Override public void onActivitySaveInstanceState(Activity activity, Bundle state) {} - @Override public void onActivityDestroyed(Activity activity) {} + @Override public void onActivityDestroyed(Activity activity) { + lihont.two.play.PlayControl.onActivityDestroyed(activity); + } } diff --git a/src/lihont/two/play/PlayControl.java b/src/lihont/two/play/PlayControl.java new file mode 100644 index 0000000..ca1669d --- /dev/null +++ b/src/lihont/two/play/PlayControl.java @@ -0,0 +1,271 @@ +package lihont.two.play; + +import android.app.Activity; +import android.app.PictureInPictureParams; +import android.content.Context; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.os.Build; +import android.util.Log; +import android.util.Rational; +import android.view.SurfaceView; +import android.view.TextureView; +import android.view.View; +import android.view.ViewGroup; + +import java.lang.ref.WeakReference; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Управление PiP (картинка в картинке) и фоновым воспроизведением в TikTok. + * + * Фоновое воспроизведение разблокирует встроенный {@code BackgroundPlayServiceImpl} + * ({@code LX/08LC}, {@code LX/1HoD}) и синхронизирует ключ {@code long_term_bg_play_enable} в Keva + * {@code BackgroundPlayManager}. + * PiP разблокирует {@code PipFeedManager}, включает системный PiP 9:16 при выходе с экрана видео + * и прячет интерфейс поверх плеера в режиме мини-окна ({@link #onPipChanged(Activity, boolean)}). + */ +public final class PlayControl { + private static final String TAG = "LIHONT"; + private static final String PREFS = "lihont_play"; + private static final String KEY_PIP = "pip"; + private static final String KEY_BG = "bg_play_v2"; + private static final String MAIN_ACTIVITY = "com.ss.android.ugc.aweme.main.MainActivity"; + + private static volatile Boolean cachedPip; + private static volatile Boolean cachedBg; + + private static final class HiddenView { + final WeakReference ref; + final float alpha; + + HiddenView(View view, float alpha) { + this.ref = new WeakReference(view); + this.alpha = alpha; + } + } + + private static final List HIDDEN_FOR_PIP = new ArrayList(); + + private PlayControl() {} + + public static boolean pipEnabled(Context context) { + Boolean value = cachedPip; + if (value != null) return value.booleanValue(); + if (context == null) return false; + try { + value = Boolean.valueOf(prefs(context).getBoolean(KEY_PIP, false)); + } catch (Throwable ignored) { + value = Boolean.FALSE; + } + cachedPip = value; + return value.booleanValue(); + } + + public static void setPipEnabled(Context context, boolean on) { + cachedPip = Boolean.valueOf(on); + if (context == null) return; + try { + prefs(context).edit().putBoolean(KEY_PIP, on).apply(); + } catch (Throwable ignored) {} + } + + public static boolean bgEnabled(Context context) { + Boolean value = cachedBg; + if (value != null) return value.booleanValue(); + if (context == null) return true; + try { + value = Boolean.valueOf(prefs(context).getBoolean(KEY_BG, true)); + } catch (Throwable ignored) { + value = Boolean.TRUE; + } + cachedBg = value; + return value.booleanValue(); + } + + public static void setBgEnabled(Context context, boolean on) { + cachedBg = Boolean.valueOf(on); + if (context == null) return; + try { + prefs(context).edit().putBoolean(KEY_BG, on).apply(); + } catch (Throwable ignored) {} + syncTikTokBgKeva(on); + } + + /** Хук на LX/116m;->LIZ()Z и PipFeedManager.isPipEnabled$pipfeed_release()Z. */ + public static boolean pipGate(boolean original) { + Boolean value = cachedPip; + return (value != null && value.booleanValue()) ? true : original; + } + + /** Хук на BackgroundPlayServiceImpl, LX/08LC и LX/1HoD. */ + public static boolean backgroundPlay(boolean original) { + Boolean value = cachedBg; + return (value != null && value.booleanValue()) ? true : original; + } + + /** Хук на LX/08LC;->LIZ()I: режим 2 включает долгосрочное фоновое воспроизведение. */ + public static int backgroundPlayMode(int original) { + Boolean value = cachedBg; + return (value != null && value.booleanValue()) ? 2 : original; + } + + /** Инициализация кэша и параметров при возврате Activity. */ + public static void warmUp(Activity activity) { + if (activity == null) return; + pipEnabled(activity); + boolean bg = bgEnabled(activity); + syncTikTokBgKeva(bg); + if (Build.VERSION.SDK_INT >= 26 && MAIN_ACTIVITY.equals(activity.getClass().getName())) { + try { + if (activity.isInPictureInPictureMode()) { + applyCleanPipUi(activity, true); + } else if (!HIDDEN_FOR_PIP.isEmpty()) { + applyCleanPipUi(activity, false); + } + } catch (Throwable ignored) {} + } + } + + /** Останавливает фоновый аудиоплеер при полном закрытии главной задачи. */ + public static void onActivityDestroyed(Activity activity) { + if (activity == null) return; + if (MAIN_ACTIVITY.equals(activity.getClass().getName()) && activity.isFinishing()) { + lihont.two.profile.ProfileMusic.release(); + } + } + + /** Вызывается из MainActivity.onUserLeaveHint() при уходе на рабочий стол. */ + public static void onUserLeaveHint(Activity activity) { + if (activity == null || !pipEnabled(activity)) return; + if (Build.VERSION.SDK_INT < 26) return; + try { + if (!activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return; + if (activity.isInPictureInPictureMode()) return; + if (activity.isFinishing() || activity.isDestroyed()) return; + View video = findVisibleVideo(activity); + if (video == null) { + Log.i(TAG, "play: skip PiP (no visible video)"); + return; + } + PictureInPictureParams.Builder builder = new PictureInPictureParams.Builder() + .setAspectRatio(new Rational(9, 16)); + applyCleanPipUi(activity, true); + boolean entered = activity.enterPictureInPictureMode(builder.build()); + Log.i(TAG, "play: enterPiP=" + entered); + if (!entered) applyCleanPipUi(activity, false); + } catch (Throwable error) { + applyCleanPipUi(activity, false); + Log.w(TAG, "play: enterPiP failed: " + error); + } + } + + /** Вызывается из MainActivity.onPictureInPictureModeChanged(). */ + public static void onPipChanged(Activity activity, boolean inPip) { + if (activity == null) return; + Log.i(TAG, "play: onPipChanged=" + inPip); + applyCleanPipUi(activity, inPip); + } + + private static void applyCleanPipUi(Activity activity, boolean hideOverlays) { + if (!hideOverlays) { + for (int i = 0; i < HIDDEN_FOR_PIP.size(); i++) { + HiddenView hv = HIDDEN_FOR_PIP.get(i); + View v = hv.ref.get(); + if (v != null) v.setAlpha(hv.alpha); + } + HIDDEN_FOR_PIP.clear(); + return; + } + if (!HIDDEN_FOR_PIP.isEmpty()) return; + View content = activity.findViewById(android.R.id.content); + View video = findVisibleVideo(activity); + if (!(content instanceof ViewGroup) || video == null) return; + Set keep = new HashSet(); + for (View p = video; p != null; p = p.getParent() instanceof View ? (View) p.getParent() : null) { + keep.add(p); + if (p == content) break; + } + hideNonVideo((ViewGroup) content, video, keep); + } + + private static void hideNonVideo(ViewGroup parent, View video, Set keep) { + for (int i = 0; i < parent.getChildCount(); i++) { + View child = parent.getChildAt(i); + if (child == video) { + if (child.getAlpha() != 1f) child.setAlpha(1f); + continue; + } + if (keep.contains(child)) { + if (child instanceof ViewGroup) hideNonVideo((ViewGroup) child, video, keep); + continue; + } + if (child.getVisibility() == View.VISIBLE && child.getAlpha() > 0f) { + HIDDEN_FOR_PIP.add(new HiddenView(child, child.getAlpha())); + child.setAlpha(0f); + } + } + } + + private static View findVisibleVideo(Activity activity) { + View content = activity.findViewById(android.R.id.content); + if (!(content instanceof ViewGroup)) return null; + int w = content.getWidth(); + int h = content.getHeight(); + if (w <= 0 || h <= 0) return null; + View[] best = new View[1]; + int[] bestScore = new int[] {Integer.MAX_VALUE}; + scanVideo((ViewGroup) content, w, h, best, bestScore); + return best[0]; + } + + private static void scanVideo(ViewGroup group, int screenW, int screenH, View[] best, int[] bestScore) { + if (!group.isShown()) return; + for (int i = 0; i < group.getChildCount(); i++) { + View c = group.getChildAt(i); + if (!c.isShown()) continue; + if (c instanceof TextureView || c instanceof SurfaceView) { + if (c.getWidth() < screenW / 3 || c.getHeight() < screenH / 4) continue; + int[] loc = new int[2]; + c.getLocationOnScreen(loc); + int cx = loc[0] + c.getWidth() / 2; + int cy = loc[1] + c.getHeight() / 2; + if (cx < 0 || cx > screenW || cy < 0 || cy > screenH) continue; + int dist = Math.abs(cx - screenW / 2) + Math.abs(cy - screenH / 2); + if (dist < bestScore[0]) { + bestScore[0] = dist; + best[0] = c; + } + } else if (c instanceof ViewGroup) { + scanVideo((ViewGroup) c, screenW, screenH, best, bestScore); + } + } + } + + private static void syncTikTokBgKeva(boolean on) { + try { + Class kevaCls = Class.forName("com.bytedance.keva.Keva"); + Object repo = null; + try { + repo = kevaCls.getMethod("getRepo", String.class).invoke(null, "background_play_repo"); + } catch (NoSuchMethodException ignored) { + repo = kevaCls.getMethod("getRepo", String.class, int.class).invoke(null, "background_play_repo", 0); + } + if (repo != null) { + repo.getClass().getMethod("storeBoolean", String.class, boolean.class) + .invoke(repo, "long_term_bg_play_enable", on); + } + Log.i(TAG, "play: bgKeva synced=" + on + " repo=" + (repo != null)); + } catch (Throwable error) { + Log.w(TAG, "play: bgKeva failed: " + error); + } + } + + private static SharedPreferences prefs(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/src/lihont/two/plugin/Act.java b/src/lihont/two/plugin/Act.java index a939d66..22946e9 100644 --- a/src/lihont/two/plugin/Act.java +++ b/src/lihont/two/plugin/Act.java @@ -8,6 +8,7 @@ import java.util.Map; * One thing a rule does. A JSON object with exactly one key: * * {"feed.hide": true} the video is left out of the feed (right feed.hide, trigger feed.item) + * {"feed.keep": true} the video stays even if another rule hides it (right feed.hide, trigger feed.item) * {"name.prefix": "text"} text before the name (right names, trigger name.show) * {"name.suffix": "text"} text after the name (right names, trigger name.show) * {"name.replace": "text"} another name (right names, trigger name.show) @@ -28,6 +29,7 @@ final class Act { static final int OVERLAY = 5; static final int DOWNLOAD = 6; static final int STYLE = 7; + static final int KEEP = 8; /** The looks a name can be given, with the words the defender uses for each. */ static final String[] STYLES = {"upper", "lower", "reverse", "wave", "spaced"}; @@ -83,7 +85,7 @@ final class Act { /** The rights the action needs. */ List permissions() { List rights = new ArrayList(); - if (kind == HIDE) { + if (kind == HIDE || kind == KEEP) { rights.add(Permission.FEED_HIDE); } else if (kind == NOTICE) { rights.add(Permission.NOTICE); @@ -102,6 +104,7 @@ final class Act { /** The action in plain words, for the defender. */ String says() { if (kind == HIDE) return "скрыть видео"; + if (kind == KEEP) return "оставить видео, даже если другие правила его скрывают"; if (kind == PREFIX) return "дописать «" + text + "» перед именем"; if (kind == SUFFIX) return "дописать «" + text + "» после имени"; if (kind == REPLACE) return "показать вместо имени «" + text + "»"; @@ -140,6 +143,11 @@ final class Act { if (!Boolean.TRUE.equals(value)) throw new LtpException(here + ": нужно true"); return new Act(HIDE, "", null); } + if (key.equals("feed.keep")) { + if (!Rule.FEED.equals(trigger)) throw new LtpException(here + ": работает только в правиле feed.item"); + if (!Boolean.TRUE.equals(value)) throw new LtpException(here + ": нужно true"); + return new Act(KEEP, "", null); + } if (key.equals("notice")) return new Act(NOTICE, Fields.text(value, 80, here), null); if (key.equals("overlay")) { if (!Rule.SCREEN.equals(trigger)) throw new LtpException(here + ": работает только в правиле screen.show"); diff --git a/src/lihont/two/plugin/Cond.java b/src/lihont/two/plugin/Cond.java index 6ddd612..3beb87e 100644 --- a/src/lihont/two/plugin/Cond.java +++ b/src/lihont/two/plugin/Cond.java @@ -16,6 +16,18 @@ import java.util.Set; * {"account": ["name", ...]} the rule works only while one of these accounts is signed in * {"time": "22:00-07:00"} the local time is in the range (it may pass midnight) * {"weekday": [1, 2, ...]} the day of the week (1 Monday to 7 Sunday) + * {"duration": [from, to]} the video lasts from..to seconds (null means no bound) + * {"likes": [from, to]} the video has from..to likes + * {"comments": [from, to]} the video has from..to comments + * {"shares": [from, to]} the video has from..to shares + * {"plays": [from, to]} the video has from..to plays + * {"age": [from, to]} the video is from..to days old + * {"followers": [from, to]} the author has from..to followers + * {"verified": true} the author has a verification mark + * {"photo": true} it is a photo post, not a video + * {"liked": true} you already liked it + * {"music": ["word", ...]} the title or the author of the music has any of the words + * {"chance": 10} it happens with this probability, in percent * {"all": [cond, ...]} {"any": [cond, ...]} {"not": cond} */ abstract class Cond { @@ -93,6 +105,19 @@ abstract class Cond { for (Object day : days) set.add(Integer.valueOf(Fields.integer(day, 1, 7, here))); return new Weekday(set); } + if (key.equals("duration")) return new Amount("duration", Fields.bounds(value, 86400, here)); + if (key.equals("likes")) return new Amount("likes", Fields.bounds(value, 2000000000, here)); + if (key.equals("comments")) return new Amount("comments", Fields.bounds(value, 2000000000, here)); + if (key.equals("shares")) return new Amount("shares", Fields.bounds(value, 2000000000, here)); + if (key.equals("plays")) return new Amount("plays", Fields.bounds(value, 2000000000, here)); + if (key.equals("age")) return new Amount("age", Fields.bounds(value, 36500, here)); + if (key.equals("followers")) return new Amount("followers", Fields.bounds(value, 2000000000, here)); + if (key.equals("verified") || key.equals("photo") || key.equals("liked")) { + Fields.truth(value, here); + return new Flag(key); + } + if (key.equals("music")) return new Music(Fields.words(value, 64, 80, here)); + if (key.equals("chance")) return new Chance(Fields.integer(value, 1, 100, here)); if (key.equals("all") || key.equals("any")) { List items = Fields.list(value, here); if (items.isEmpty() || items.size() > 16) throw new LtpException(here + ": от 1 до 16 условий"); @@ -274,6 +299,112 @@ abstract class Cond { } } + /** A number about the video: duration, likes, comments, shares, plays, age or followers, within bounds. */ + private static final class Amount extends Cond { + private final String field; + private final Long from; + private final Long to; + + Amount(String field, Long[] bounds) { + this.field = field; + this.from = bounds[0]; + this.to = bounds[1]; + } + + @Override String says() { + if (field.equals("age")) { + if (from != null && to != null) return "видео возрастом от " + from + " до " + to + " дней"; + if (from != null) return "видео не моложе " + from + " дней"; + return "видео не старше " + to + " дней"; + } + String range; + if (from != null && to != null) range = "от " + from + " до " + to; + else if (from != null) range = "не меньше " + from; + else range = "не больше " + to; + if (field.equals("duration")) return "видео длительностью " + range + " секунд"; + if (field.equals("likes")) return "лайков " + range; + if (field.equals("comments")) return "комментариев " + range; + if (field.equals("shares")) return "репостов " + range; + if (field.equals("plays")) return "просмотров " + range; + return "подписчиков у автора " + range; + } + + @Override boolean selects() { + return true; + } + + @Override boolean test(Ctx ctx) { + long value = ctx.number(field); + if (value < 0) return false; + return (from == null || value >= from.longValue()) && (to == null || value <= to.longValue()); + } + } + + /** A yes/no about the video: the author is verified, it is a photo post or you already liked it. */ + private static final class Flag extends Cond { + private final String field; + + Flag(String field) { + this.field = field; + } + + @Override String says() { + if (field.equals("verified")) return "автор с галочкой"; + if (field.equals("photo")) return "это фото, а не видео"; + return "вы уже лайкнули это видео"; + } + + @Override boolean selects() { + return true; + } + + @Override boolean test(Ctx ctx) { + return ctx.flag(field); + } + } + + /** The title or the author of the music. */ + private static final class Music extends Cond { + private final List words; + + Music(List words) { + this.words = words; + } + + @Override String says() { + return "в музыке есть " + items(words, "«", "»"); + } + + @Override boolean selects() { + return true; + } + + @Override boolean test(Ctx ctx) { + String music = ctx.music(); + for (String word : words) { + if (music.contains(word)) return true; + } + return false; + } + } + + /** A rule that fires by chance, in percent. */ + private static final class Chance extends Cond { + private final int percent; + + Chance(int percent) { + this.percent = percent; + } + + @Override String says() { + return "с вероятностью " + percent + "%"; + } + + @Override boolean test(Ctx ctx) { + return java.util.concurrent.ThreadLocalRandom.current().nextInt(100) < percent; + } + } + private static final class All extends Cond { private final List parts; diff --git a/src/lihont/two/plugin/Ctx.java b/src/lihont/two/plugin/Ctx.java index bcd79e7..b3dc86d 100644 --- a/src/lihont/two/plugin/Ctx.java +++ b/src/lihont/two/plugin/Ctx.java @@ -27,6 +27,18 @@ public interface Ctx { /** For a name on the screen: the id of the account it belongs to; empty for a video. */ String uid(); + /** + * A number about the video, -1 when TikTok did not say: duration (seconds), likes, comments, shares, plays, + * age (days since it was published) or followers (of the author). + */ + long number(String field); + + /** A yes/no about the video: verified (the author), photo (a photo post) or liked (you already liked it). */ + boolean flag(String field); + + /** The title and the author of the music, lower case; empty when TikTok did not say. */ + String music(); + /** The minute of the local day, 0 to 1439. */ int minute(); diff --git a/src/lihont/two/plugin/Defender.java b/src/lihont/two/plugin/Defender.java index d63011f..ebc4f92 100644 --- a/src/lihont/two/plugin/Defender.java +++ b/src/lihont/two/plugin/Defender.java @@ -78,6 +78,8 @@ public final class Defender { } else if (seen.add("hide")) { watch.add("Скрывает видео из ленты по условиям правил. Что и когда скрыто, видно в журнале плагина."); } + } else if (act.kind == Act.KEEP) { + if (seen.add("keep")) calm.add("Оставляет видео, даже если другие правила просят его скрыть."); } else if (act.kind == Act.REPLACE) { if (!selects) { careful.add("Правило «" + rule.title + "» подменяет все имена на экране на «" + act.text + "»."); diff --git a/src/lihont/two/plugin/Fields.java b/src/lihont/two/plugin/Fields.java index d23ee89..17a77a3 100644 --- a/src/lihont/two/plugin/Fields.java +++ b/src/lihont/two/plugin/Fields.java @@ -71,4 +71,25 @@ final class Fields { } return (int) number; } + + /** A pair [from, to] of whole numbers; each may be JSON null for "no bound", at least one is present. */ + static Long[] bounds(Object node, int max, String where) throws LtpException { + List items = list(node, where); + if (items.size() != 2) throw new LtpException(where + ": нужно [от, до], вместо границы можно null"); + Long from = items.get(0) == Json.NULL ? null : Long.valueOf(integer(items.get(0), 0, max, where)); + Long to = items.get(1) == Json.NULL ? null : Long.valueOf(integer(items.get(1), 0, max, where)); + if (from == null && to == null) throw new LtpException(where + ": назови хотя бы одну границу"); + if (from != null && to != null && from.longValue() > to.longValue()) { + throw new LtpException(where + ": «от» больше, чем «до»"); + } + return new Long[] {from, to}; + } + + /** A yes/no condition: only true is allowed, «не» is written as ~ in the library. */ + static boolean truth(Object value, String where) throws LtpException { + if (!Boolean.TRUE.equals(value)) { + throw new LtpException(where + ": нужно true (для «не» поставь ~ перед условием)"); + } + return true; + } } diff --git a/src/lihont/two/plugin/PluginEngine.java b/src/lihont/two/plugin/PluginEngine.java index a64959c..2ae0c3b 100644 --- a/src/lihont/two/plugin/PluginEngine.java +++ b/src/lihont/two/plugin/PluginEngine.java @@ -197,17 +197,26 @@ public final class PluginEngine { try { AwemeCtx ctx = new AwemeCtx(item, state.uid); boolean hide = false; + boolean keep = false; + Plugin hider = null; + Rule hidden = null; for (Plugin plugin : state.feed) { for (Rule rule : Evaluator.matching(plugin, Rule.FEED, ctx)) { for (String text : Evaluator.notices(rule)) notice(plugin, rule, text); + if (rule.keeps()) keep = true; if (rule.hides() && !hide) { hide = true; - Journal.add(plugin.id, "Скрыто видео" + (ctx.author().length() > 0 ? " @" + ctx.author() : "") - + " · «" + rule.title + "»"); + hider = plugin; + hidden = rule; } } } - return hide; + if (hide && !keep) { + Journal.add(hider.id, "Скрыто видео" + (ctx.author().length() > 0 ? " @" + ctx.author() : "") + + " · «" + hidden.title + "»"); + return true; + } + return false; } catch (Throwable failure) { return false; } @@ -395,22 +404,90 @@ public final class PluginEngine { /** A video of the feed (a TikTok Aweme), read through its getters. */ private static final class AwemeCtx extends Base { + private final Object aweme; private final String text; private final Set tags = new HashSet(); private final String author; private final String authorUid; + private final Object person; + private Object statistics; + private boolean statisticsRead; + private Object video; + private boolean videoRead; + private Object track; + private boolean trackRead; AwemeCtx(Object aweme, String selfUid) { super(selfUid); + this.aweme = aweme; String description = read(aweme, "getDesc"); text = lower(description); Matcher found = HASHTAG.matcher(description); while (found.find()) tags.add(lower(found.group(1))); - Object person = call(aweme, "getAuthor"); + person = call(aweme, "getAuthor"); author = lower(read(person, "getUniqueId")); authorUid = lower(read(person, "getUid")); } + private static long asLong(Object value) { + return value instanceof Number ? ((Number) value).longValue() : -1L; + } + + private Object statistics() { + if (!statisticsRead) { + statistics = call(aweme, "getStatistics"); + statisticsRead = true; + } + return statistics; + } + + private Object video() { + if (!videoRead) { + video = call(aweme, "getVideo"); + videoRead = true; + } + return video; + } + + private Object track() { + if (!trackRead) { + track = call(aweme, "getMusic"); + trackRead = true; + } + return track; + } + + @Override public long number(String field) { + if ("duration".equals(field)) { + long ms = asLong(call(video(), "getDuration")); + return ms <= 0 ? -1 : ms / 1000; + } + if ("likes".equals(field)) return asLong(call(statistics(), "getDiggCount")); + if ("comments".equals(field)) return asLong(call(statistics(), "getCommentCount")); + if ("shares".equals(field)) return asLong(call(statistics(), "getShareCount")); + if ("plays".equals(field)) return asLong(call(statistics(), "getPlayCount")); + if ("age".equals(field)) { + long created = asLong(call(aweme, "getCreateTime")); + if (created <= 0) return -1; + long days = (System.currentTimeMillis() / 1000L - created) / 86400L; + return days < 0 ? 0 : days; + } + if ("followers".equals(field)) return asLong(call(person, "getFollowerCount")); + return -1; + } + + @Override public boolean flag(String field) { + if ("verified".equals(field)) return Boolean.TRUE.equals(call(person, "isVerified")); + if ("photo".equals(field)) return call(aweme, "getPhotoModeImageInfo") != null; + if ("liked".equals(field)) return asLong(call(aweme, "getUserDigg")) > 0; + return false; + } + + @Override public String music() { + Object found = track(); + return lower((read(found, "getMusicName") + " " + read(found, "getAuthorName")).trim()); + } + @Override public String text() { return text; } @Override public Set hashtags() { return tags; } @Override public String author() { return author; } @@ -432,6 +509,9 @@ public final class PluginEngine { @Override public String author() { return ""; } @Override public String authorUid() { return ""; } @Override public String uid() { return uid; } + @Override public long number(String field) { return -1; } + @Override public boolean flag(String field) { return false; } + @Override public String music() { return ""; } } /** A screen of the app: only the moment and the account are known. */ @@ -445,6 +525,9 @@ public final class PluginEngine { @Override public String author() { return ""; } @Override public String authorUid() { return ""; } @Override public String uid() { return ""; } + @Override public long number(String field) { return -1; } + @Override public boolean flag(String field) { return false; } + @Override public String music() { return ""; } } /** For the log only. */ diff --git a/src/lihont/two/plugin/Rule.java b/src/lihont/two/plugin/Rule.java index cf148e7..617cd7a 100644 --- a/src/lihont/two/plugin/Rule.java +++ b/src/lihont/two/plugin/Rule.java @@ -58,6 +58,14 @@ public final class Rule { return false; } + /** Whether the rule keeps a video that other rules would hide (a white list). */ + boolean keeps() { + for (Act act : acts) { + if (act.kind == Act.KEEP) return true; + } + return false; + } + static Rule parse(Object node, int index, List permissions) throws LtpException { String where = "Правило " + (index + 1); Map map = Fields.map(node, where); diff --git a/src/lihont/two/profile/ProfileMusic.java b/src/lihont/two/profile/ProfileMusic.java new file mode 100644 index 0000000..ceda865 --- /dev/null +++ b/src/lihont/two/profile/ProfileMusic.java @@ -0,0 +1,1386 @@ +package lihont.two.profile; + +import android.app.Activity; +import android.app.Dialog; +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.graphics.Canvas; +import android.graphics.ColorFilter; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.PixelFormat; +import android.graphics.RectF; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.GradientDrawable; +import android.media.AudioAttributes; +import android.media.MediaMetadata; +import android.media.MediaPlayer; +import android.media.session.MediaSession; +import android.media.session.PlaybackState; +import android.net.Uri; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.provider.OpenableColumns; +import android.text.InputType; +import android.text.TextUtils; +import android.util.Base64; +import android.util.Log; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.Toast; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import lihont.two.avatar.Installation; +import lihont.two.badge.MemberClient; +import lihont.two.badge.NicheClaim; +import lihont.two.settings.Md3; +import lihont.two.settings.Md3Icon; +import lihont.two.settings.Md3Switch; +import lihont.two.settings.ModSettings; + +/** + * Shared moderated profile music synced via LihonT members service. + * + * When a profile has an approved active track on the server, a sleek single-pill mini player sits above the video grid. + * When a profile has NO music (or is still loading / has none approved), NO bubble or top gap is rendered at all. + */ +public final class ProfileMusic { + private static final String TAG = "LIHONT"; + private static final String PREFS = "lihont_profile_music"; + private static final String KEY_ENABLED = "enabled"; + private static final int PILL_TAG = 0x4C544D55; + private static final int OVERLAY_TAG = 0x4C544D4F; + private static final int ORIGINAL_TOP_PAD_TAG = 0x4C544D50; + private static final String CHANNEL_ID = "lihont_profile_music_ch"; + private static final int NOTIF_ID = 41130; + private static final String ACTION_TOGGLE = "lihont.two.profile.MUSIC_TOGGLE"; + private static final String ACTION_STOP = "lihont.two.profile.MUSIC_STOP"; + private static final long CACHE_TTL_MS = 45_000L; + private static final int MAX_UPLOAD_BYTES = 3_800_000; + public static final int REQUEST_PICK = 4113; + + public static final class Track { + public final String id; + public final String title; + public final String artist; + public final int duration; + public final String url; + public final String status; + public final String reason; + public final boolean active; + + Track(String id, String title, String artist, int duration, String url, String status, String reason, boolean active) { + this.id = id; + this.title = title; + this.artist = artist; + this.duration = duration; + this.url = url; + this.status = status; + this.reason = reason; + this.active = active; + } + } + + private static final class CacheEntry { + final Track track; + final long at; + + CacheEntry(Track track, long at) { + this.track = track; + this.at = at; + } + } + + private static final Map CACHE = new ConcurrentHashMap(); + private static final Map IN_FLIGHT = new ConcurrentHashMap(); + + private static MediaPlayer player; + private static Track playingTrack; + private static String playingHandle; + private static String playingTrackId; + private static String playingUrl; + private static boolean preparing; + private static boolean paused; + private static Context appContext; + private static MediaSession mediaSession; + private static BroadcastReceiver mediaReceiver; + private static WeakReference activeActivity = new WeakReference(null); + private static WeakReference activeDisc = new WeakReference(null); + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + private static boolean shutdownRegistered; + + private ProfileMusic() {} + + public static boolean enabled(Context context) { + if (context == null) return false; + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY_ENABLED, true); + } + + public static void setEnabled(Context context, boolean value) { + if (context == null) return; + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_ENABLED, value).apply(); + if (!value) release(); + } + + /** Called by ProfilePanel every frame on the active profile root. Never creates any bubble when no track exists. */ + static void attach(Activity activity, ViewGroup root, View grid, Md3.Palette palette, String handle) { + if (activity == null || root == null) return; + if (!enabled(activity)) { + removeIfPresent(root, grid); + return; + } + if (grid == null || !grid.isShown()) return; + final String key = resolveHandle(handle); + if (key.isEmpty()) { + removeIfPresent(root, grid); + return; + } + + CacheEntry cached = CACHE.get(key); + long now = android.os.SystemClock.elapsedRealtime(); + if (cached == null || now - cached.at > CACHE_TTL_MS) { + fetchTrackAsync(activity, root, grid, palette, key); + if (cached == null) { + removeIfPresent(root, grid); + return; + } + } + + Track track = cached.track; + if (track == null || track.url.isEmpty()) { + removeIfPresent(root, grid); + return; + } + + LinearLayout pill = findPill(root); + if (pill == null) { + pill = buildPill(activity, palette); + attachAboveGrid(activity, root, grid, pill); + } + updatePill(pill, activity, palette, key, track); + } + + private static String resolveHandle(String raw) { + String h = raw == null ? "" : raw.trim(); + if (h.startsWith("@")) h = h.substring(1); + h = h.toLowerCase(Locale.ROOT); + if (h.isEmpty() || "me".equals(h)) { + NicheClaim.Account account = NicheClaim.account(); + if (account != null && account.uniqueId != null) { + String own = account.uniqueId.trim().toLowerCase(Locale.ROOT); + if (own.startsWith("@")) own = own.substring(1); + if (!own.isEmpty()) return own; + } + return ""; + } + return h; + } + + private static void fetchTrackAsync(final Activity activity, final ViewGroup root, final View grid, + final Md3.Palette palette, final String handleKey) { + if (IN_FLIGHT.putIfAbsent(handleKey, Boolean.TRUE) != null) return; + new Thread(new Runnable() { + @Override public void run() { + Track found = null; + boolean gotAnswer = false; + try { + JSONObject reply = MemberClient.post("music_lookup", new JSONObject().put("unique_id", handleKey)); + gotAnswer = true; + JSONObject t = reply.optJSONObject("track"); + if (t != null) found = parseTrack(t); + } catch (Exception ignored) { + // Keep short negative cache only when network error didn't happen? Retry in 8s on failure. + } finally { + long stamp = gotAnswer + ? android.os.SystemClock.elapsedRealtime() + : android.os.SystemClock.elapsedRealtime() - (CACHE_TTL_MS - 8_000L); + CACHE.put(handleKey, new CacheEntry(found, stamp)); + IN_FLIGHT.remove(handleKey); + } + final Track ready = found; + activity.runOnUiThread(new Runnable() { + @Override public void run() { + if (activity.isFinishing() || activity.isDestroyed() || !enabled(activity)) return; + if (ready == null) { + removeIfPresent(root, grid); + } else if (grid.isShown()) { + attach(activity, root, grid, palette, handleKey); + } + } + }); + } + }, "lihont-music-lookup").start(); + } + + private static Track parseTrack(JSONObject obj) { + String path = obj.optString("path", ""); + String url = path.isEmpty() ? "" : MemberClient.API + path; + return new Track( + obj.optString("id", ""), + obj.optString("title", "Трек профиля"), + obj.optString("artist", ""), + obj.optInt("duration", 0), + url, + obj.optString("status", "approved"), + obj.optString("reason", ""), + obj.optBoolean("active", true) + ); + } + + private static void attachAboveGrid(Activity activity, ViewGroup root, View grid, LinearLayout pill) { + android.view.ViewParent gp = grid.getParent(); + if (gp instanceof ViewGroup) { + ViewGroup parent = (ViewGroup) gp; + if (grid.getTag(ORIGINAL_TOP_PAD_TAG) == null) { + grid.setTag(ORIGINAL_TOP_PAD_TAG, grid.getPaddingTop()); + } + int origTop = (Integer) grid.getTag(ORIGINAL_TOP_PAD_TAG); + int pillHeight = Md3.dp(activity, 52); + if (grid.getPaddingTop() < origTop + pillHeight) { + grid.setPadding(grid.getPaddingLeft(), origTop + pillHeight, grid.getPaddingRight(), grid.getPaddingBottom()); + } + int marginH = Md3.dp(activity, 12); + int marginTop = Md3.dp(activity, 6); + if (parent instanceof FrameLayout) { + FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + lp.leftMargin = marginH; + lp.rightMargin = marginH; + lp.topMargin = marginTop; + parent.addView(pill, lp); + return; + } + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + lp.leftMargin = marginH; + lp.rightMargin = marginH; + lp.topMargin = marginTop; + lp.bottomMargin = Md3.dp(activity, 4); + int idx = Math.max(0, parent.indexOfChild(grid)); + parent.addView(pill, idx, lp); + return; + } + root.addView(pill, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + } + + private static LinearLayout findPill(ViewGroup root) { + return root.findViewWithTag(PILL_TAG); + } + + private static void removeIfPresent(ViewGroup root, View grid) { + LinearLayout pill = findPill(root); + if (pill != null && pill.getParent() instanceof ViewGroup) { + ((ViewGroup) pill.getParent()).removeView(pill); + } + if (grid != null && grid.getTag(ORIGINAL_TOP_PAD_TAG) instanceof Integer) { + int origTop = (Integer) grid.getTag(ORIGINAL_TOP_PAD_TAG); + if (grid.getPaddingTop() != origTop) { + grid.setPadding(grid.getPaddingLeft(), origTop, grid.getPaddingRight(), grid.getPaddingBottom()); + } + } + } + + private static LinearLayout buildPill(Activity activity, Md3.Palette palette) { + LinearLayout pill = new LinearLayout(activity); + pill.setTag(PILL_TAG); + pill.setOrientation(LinearLayout.HORIZONTAL); + pill.setGravity(Gravity.CENTER_VERTICAL); + pill.setMinimumHeight(Md3.dp(activity, 44)); + int hPad = Md3.dp(activity, 10); + int vPad = Md3.dp(activity, 6); + pill.setPadding(hPad, vPad, Md3.dp(activity, 12), vPad); + pill.setElevation(Md3.dp(activity, 2)); + + PlayDiscView playBtn = new PlayDiscView(activity, palette); + int discSize = Md3.dp(activity, 32); + LinearLayout.LayoutParams playLp = new LinearLayout.LayoutParams(discSize, discSize); + playLp.rightMargin = Md3.dp(activity, 10); + pill.addView(playBtn, playLp); + + LinearLayout textCol = new LinearLayout(activity); + textCol.setOrientation(LinearLayout.VERTICAL); + TextView title = new TextView(activity); + title.setTextSize(13f); + title.setSingleLine(true); + title.setEllipsize(TextUtils.TruncateAt.END); + title.setTypeface(android.graphics.Typeface.DEFAULT_BOLD); + textCol.addView(title); + + TextView subtitle = new TextView(activity); + subtitle.setTextSize(11f); + subtitle.setSingleLine(true); + subtitle.setEllipsize(TextUtils.TruncateAt.END); + textCol.addView(subtitle); + + pill.addView(textCol, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)); + + TextView durView = new TextView(activity); + durView.setTextSize(11.5f); + durView.setTypeface(android.graphics.Typeface.DEFAULT_BOLD); + LinearLayout.LayoutParams durLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + durLp.leftMargin = Md3.dp(activity, 8); + pill.addView(durView, durLp); + + return pill; + } + + private static void updatePill(LinearLayout pill, Activity activity, Md3.Palette palette, String handleKey, Track track) { + GradientDrawable bg = new GradientDrawable(); + bg.setColor(palette.surfaceContainerHigh); + bg.setCornerRadius(Md3.dp(activity, 18)); + bg.setStroke(Math.max(1, Md3.dp(activity, 1)), (palette.outlineVariant & 0x00FFFFFF) | 0x44000000); + pill.setBackground(bg); + + PlayDiscView playBtn = (PlayDiscView) pill.getChildAt(0); + LinearLayout textCol = (LinearLayout) pill.getChildAt(1); + TextView title = (TextView) textCol.getChildAt(0); + TextView subtitle = (TextView) textCol.getChildAt(1); + TextView durView = (TextView) pill.getChildAt(2); + + playBtn.setPalette(palette); + title.setTextColor(palette.onSurface); + subtitle.setTextColor(palette.onSurfaceVariant); + durView.setTextColor(palette.primary); + + title.setText(track.title); + subtitle.setText(track.artist.isEmpty() ? "@" + handleKey : track.artist); + durView.setText(formatDuration(track.duration)); + + boolean isThis = track.id.equals(playingTrackId); + if (isThis && preparing) { + playBtn.setMode(PlayDiscView.MODE_LOADING); + } else if (isThis && isActuallyPlaying()) { + playBtn.setMode(PlayDiscView.MODE_PAUSE); + activeDisc = new WeakReference(playBtn); + } else { + playBtn.setMode(PlayDiscView.MODE_PLAY); + } + + playBtn.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + togglePlayback(activity, playBtn, handleKey, track); + } + }); + pill.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + openPlayerSheet(activity, palette, playBtn, handleKey, track); + } + }); + } + + private static String formatDuration(int sec) { + if (sec <= 0) return "MP3"; + return String.format(Locale.US, "%d:%02d", sec / 60, sec % 60); + } + + private static boolean isActuallyPlaying() { + try { + return player != null && player.isPlaying(); + } catch (IllegalStateException e) { + return false; + } + } + + private static void togglePlayback(Activity activity, PlayDiscView disc, String handleKey, Track track) { + if (track == null || track.url.isEmpty()) return; + if (track.id.equals(playingTrackId)) { + if (isActuallyPlaying()) { + try { player.pause(); } catch (IllegalStateException ignored) {} + paused = true; + if (disc != null) disc.setMode(PlayDiscView.MODE_PLAY); + syncSystemPlayer(); + refreshVisibleFloatingBar(); + return; + } + if (paused && player != null) { + try { player.start(); } catch (IllegalStateException ignored) {} + paused = false; + if (disc != null) disc.setMode(PlayDiscView.MODE_PAUSE); + if (disc != null) activeDisc = new WeakReference(disc); + syncSystemPlayer(); + refreshVisibleFloatingBar(); + return; + } + } + startPlayback(activity, disc, handleKey, track); + } + + private static void startPlayback(final Activity activity, PlayDiscView disc, final String handleKey, final Track track) { + release(); + if (activity != null) { + appContext = activity.getApplicationContext(); + activeActivity = new WeakReference(activity); + if (Build.VERSION.SDK_INT >= 24) { + try { + NotificationManager nm = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); + if (nm != null && !nm.areNotificationsEnabled()) { + Toast.makeText(activity, "Включите уведомления для TikTok, чтобы видеть плеер в шторке", Toast.LENGTH_LONG).show(); + } + } catch (Throwable ignored) {} + } + if (Build.VERSION.SDK_INT >= 33 + && activity.checkSelfPermission("android.permission.POST_NOTIFICATIONS") != android.content.pm.PackageManager.PERMISSION_GRANTED) { + try { activity.requestPermissions(new String[]{"android.permission.POST_NOTIFICATIONS"}, 4114); } catch (Throwable ignored) {} + } + } + registerReceiverIfNeeded(); + playingTrack = track; + playingHandle = handleKey == null ? "" : handleKey; + playingTrackId = track.id; + playingUrl = track.url; + preparing = true; + paused = false; + activeDisc = new WeakReference(disc); + if (disc != null) disc.setMode(PlayDiscView.MODE_LOADING); + syncSystemPlayer(); + refreshVisibleFloatingBar(); + try { + MediaPlayer mp = new MediaPlayer(); + player = mp; + mp.setAudioAttributes(new AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) + .setUsage(AudioAttributes.USAGE_MEDIA) + .build()); + mp.setDataSource(track.url); + mp.setLooping(true); + mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { + @Override public void onPrepared(MediaPlayer m) { + if (player != m) return; + preparing = false; + paused = false; + m.start(); + PlayDiscView d = activeDisc.get(); + if (d != null) d.setMode(PlayDiscView.MODE_PAUSE); + syncSystemPlayer(); + refreshVisibleFloatingBar(); + } + }); + mp.setOnErrorListener(new MediaPlayer.OnErrorListener() { + @Override public boolean onError(MediaPlayer m, int what, int extra) { + if (player == m) release(); + if (activity != null) Toast.makeText(activity, "Не удалось воспроизвести трек", Toast.LENGTH_SHORT).show(); + return true; + } + }); + mp.prepareAsync(); + } catch (Throwable t) { + release(); + if (activity != null) Toast.makeText(activity, "Не удалось запустить аудио", Toast.LENGTH_SHORT).show(); + } + } + + public static void release() { + preparing = false; + paused = false; + playingTrack = null; + playingHandle = null; + playingTrackId = null; + playingUrl = null; + PlayDiscView d = activeDisc.get(); + if (d != null) d.setMode(PlayDiscView.MODE_PLAY); + activeDisc = new WeakReference(null); + if (player != null) { + try { player.reset(); } catch (Throwable ignored) {} + try { player.release(); } catch (Throwable ignored) {} + player = null; + } + cancelSystemNotification(); + MAIN.post(new Runnable() { + @Override public void run() { + Activity a = activeActivity.get(); + if (a != null) removeFloatingBar(a); + } + }); + } + + private static void refreshVisibleFloatingBar() { + MAIN.post(new Runnable() { + @Override public void run() { + Activity a = activeActivity.get(); + if (a != null && !a.isFinishing() && !a.isDestroyed()) { + View decor = a.getWindow().getDecorView(); + LinearLayout bar = decor.findViewWithTag(OVERLAY_TAG); + if (bar != null) updateFloatingBar(bar, a); + } + } + }); + } + + /** Shows or hides a sleek top floating mini-player when user leaves the track's profile page. */ + public static void syncFloatingBar(final Activity activity, View profileRoot) { + if (activity == null || activity.isFinishing() || activity.isDestroyed()) return; + appContext = activity.getApplicationContext(); + activeActivity = new WeakReference(activity); + final Track t = playingTrack; + if (t == null || playingTrackId == null || !enabled(activity)) { + removeFloatingBar(activity); + return; + } + boolean hidingForSameProfile = false; + if (profileRoot instanceof ViewGroup && findPill((ViewGroup) profileRoot) != null) { + String currentProfileHandle = ""; + try { + int hid = activity.getResources().getIdentifier("t6g", "id", activity.getPackageName()); + View hv = hid != 0 ? profileRoot.findViewById(hid) : null; + if (hv instanceof TextView) currentProfileHandle = resolveHandle(((TextView) hv).getText().toString()); + } catch (Throwable ignored) {} + if (currentProfileHandle.isEmpty() || currentProfileHandle.equals(playingHandle)) { + hidingForSameProfile = true; + } + } + if (hidingForSameProfile) { + removeFloatingBar(activity); + return; + } + View decor = activity.getWindow().getDecorView(); + if (!(decor instanceof FrameLayout)) return; + FrameLayout frame = (FrameLayout) decor; + LinearLayout bar = frame.findViewWithTag(OVERLAY_TAG); + if (bar == null) { + bar = buildFloatingBar(activity); + FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP); + lp.leftMargin = Md3.dp(activity, 12); + lp.rightMargin = Md3.dp(activity, 12); + lp.topMargin = statusBarHeight(activity) + Md3.dp(activity, 6); + frame.addView(bar, lp); + } + updateFloatingBar(bar, activity); + } + + private static void removeFloatingBar(Activity activity) { + if (activity == null) return; + try { + View decor = activity.getWindow().getDecorView(); + View bar = decor.findViewWithTag(OVERLAY_TAG); + if (bar != null && bar.getParent() instanceof ViewGroup) { + ((ViewGroup) bar.getParent()).removeView(bar); + } + } catch (Throwable ignored) {} + } + + private static int statusBarHeight(Context context) { + int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); + return resId > 0 ? context.getResources().getDimensionPixelSize(resId) : Md3.dp(context, 24); + } + + private static LinearLayout buildFloatingBar(final Activity activity) { + LinearLayout bar = new LinearLayout(activity); + bar.setTag(OVERLAY_TAG); + bar.setOrientation(LinearLayout.HORIZONTAL); + bar.setGravity(Gravity.CENTER_VERTICAL); + bar.setMinimumHeight(Md3.dp(activity, 46)); + bar.setPadding(Md3.dp(activity, 10), Md3.dp(activity, 6), Md3.dp(activity, 8), Md3.dp(activity, 6)); + bar.setElevation(Md3.dp(activity, 6)); + bar.setClickable(true); + + Md3.Palette palette = Md3.palette(activity, ModSettings.Theme.SYSTEM); + PlayDiscView disc = new PlayDiscView(activity, palette); + int discSize = Md3.dp(activity, 32); + LinearLayout.LayoutParams dpLp = new LinearLayout.LayoutParams(discSize, discSize); + dpLp.rightMargin = Md3.dp(activity, 10); + bar.addView(disc, dpLp); + + LinearLayout textCol = new LinearLayout(activity); + textCol.setOrientation(LinearLayout.VERTICAL); + TextView title = new TextView(activity); + title.setTextSize(13f); + title.setSingleLine(true); + title.setEllipsize(TextUtils.TruncateAt.END); + title.setTypeface(android.graphics.Typeface.DEFAULT_BOLD); + textCol.addView(title); + TextView sub = new TextView(activity); + sub.setTextSize(11f); + sub.setSingleLine(true); + sub.setEllipsize(TextUtils.TruncateAt.END); + textCol.addView(sub); + bar.addView(textCol, new LinearLayout.LayoutParams(0, -2, 1f)); + + ImageView closeBtn = new ImageView(activity); + closeBtn.setScaleType(ImageView.ScaleType.CENTER); + closeBtn.setContentDescription("Закрыть плеер"); + int cbSize = Md3.dp(activity, 34); + bar.addView(closeBtn, new LinearLayout.LayoutParams(cbSize, cbSize)); + return bar; + } + + private static void updateFloatingBar(LinearLayout bar, final Activity activity) { + final Track t = playingTrack; + if (t == null) return; + boolean dark = (activity.getResources().getConfiguration().uiMode + & android.content.res.Configuration.UI_MODE_NIGHT_MASK) == android.content.res.Configuration.UI_MODE_NIGHT_YES; + final Md3.Palette palette = Md3.palette(activity, dark ? ModSettings.Theme.DARK : ModSettings.Theme.LIGHT); + bar.setBackground(Md3.outlined(palette.surfaceContainerHigh, palette.outlineVariant, 1f, 18f, activity)); + + final PlayDiscView disc = (PlayDiscView) bar.getChildAt(0); + LinearLayout textCol = (LinearLayout) bar.getChildAt(1); + TextView title = (TextView) textCol.getChildAt(0); + TextView sub = (TextView) textCol.getChildAt(1); + ImageView closeBtn = (ImageView) bar.getChildAt(2); + + disc.setPalette(palette); + if (preparing) { + disc.setMode(PlayDiscView.MODE_LOADING); + } else if (isActuallyPlaying()) { + disc.setMode(PlayDiscView.MODE_PAUSE); + } else { + disc.setMode(PlayDiscView.MODE_PLAY); + } + + title.setTextColor(palette.onSurface); + title.setText(t.title); + sub.setTextColor(palette.onSurfaceVariant); + String who = t.artist.isEmpty() ? "@" + playingHandle : t.artist + (playingHandle != null && !playingHandle.isEmpty() ? " · @" + playingHandle : ""); + sub.setText(who); + + closeBtn.setImageDrawable(Md3Icon.of(Md3Icon.CLOSE, palette.onSurfaceVariant, activity)); + closeBtn.setBackground(Md3.stateLayer(activity, Md3.SHAPE_FULL, Md3.stateLayerColor(palette.onSurfaceVariant))); + + disc.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + togglePlayback(activity, disc, playingHandle, t); + } + }); + bar.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + openPlayerSheet(activity, palette, disc, playingHandle == null ? "" : playingHandle, t); + } + }); + closeBtn.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + release(); + } + }); + } + + private static void registerReceiverIfNeeded() { + Context ctx = appContext; + if (ctx == null) return; + if (!shutdownRegistered) { + shutdownRegistered = true; + try { + Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { + @Override public void run() { cancelSystemNotification(); } + })); + } catch (Throwable ignored) {} + } + if (mediaReceiver != null) return; + mediaReceiver = new BroadcastReceiver() { + @Override public void onReceive(Context context, Intent intent) { + String act = intent == null ? null : intent.getAction(); + if (ACTION_STOP.equals(act)) { + MAIN.post(new Runnable() { + @Override public void run() { release(); } + }); + } else if (ACTION_TOGGLE.equals(act)) { + MAIN.post(new Runnable() { + @Override public void run() { + if (playingTrack != null) { + togglePlayback(activeActivity.get(), activeDisc.get(), playingHandle, playingTrack); + } + } + }); + } + } + }; + IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_TOGGLE); + filter.addAction(ACTION_STOP); + try { + if (Build.VERSION.SDK_INT >= 33) { + ctx.registerReceiver(mediaReceiver, filter, Context.RECEIVER_NOT_EXPORTED); + } else { + ctx.registerReceiver(mediaReceiver, filter); + } + } catch (Throwable ignored) {} + } + + private static void syncSystemPlayer() { + Context ctx = appContext; + Track t = playingTrack; + if (ctx == null || t == null) return; + try { + NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE); + if (nm == null) return; + if (Build.VERSION.SDK_INT >= 26) { + NotificationChannel ch = new NotificationChannel(CHANNEL_ID, "Музыка профиля", NotificationManager.IMPORTANCE_LOW); + ch.setShowBadge(false); + nm.createNotificationChannel(ch); + } + if (mediaSession == null) { + mediaSession = new MediaSession(ctx, "LihonTProfileMusic"); + mediaSession.setCallback(new MediaSession.Callback() { + @Override public void onPlay() { + MAIN.post(new Runnable() { + @Override public void run() { + if (playingTrack != null && !isActuallyPlaying()) { + togglePlayback(activeActivity.get(), activeDisc.get(), playingHandle, playingTrack); + } + } + }); + } + + @Override public void onPause() { + MAIN.post(new Runnable() { + @Override public void run() { + if (playingTrack != null && isActuallyPlaying()) { + togglePlayback(activeActivity.get(), activeDisc.get(), playingHandle, playingTrack); + } + } + }); + } + + @Override public void onStop() { + MAIN.post(new Runnable() { + @Override public void run() { release(); } + }); + } + }); + } + mediaSession.setActive(true); + mediaSession.setMetadata(new MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_TITLE, t.title) + .putString(MediaMetadata.METADATA_KEY_ARTIST, + t.artist.isEmpty() ? "@" + (playingHandle == null ? "LihonT" : playingHandle) : t.artist) + .putLong(MediaMetadata.METADATA_KEY_DURATION, t.duration * 1000L) + .build()); + int stateCode = preparing ? PlaybackState.STATE_BUFFERING + : isActuallyPlaying() ? PlaybackState.STATE_PLAYING : PlaybackState.STATE_PAUSED; + long pos = 0L; + try { if (player != null) pos = player.getCurrentPosition(); } catch (Throwable ignored) {} + mediaSession.setPlaybackState(new PlaybackState.Builder() + .setActions(PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PAUSE | PlaybackState.ACTION_PLAY_PAUSE | PlaybackState.ACTION_STOP) + .setState(stateCode, pos, isActuallyPlaying() ? 1f : 0f) + .build()); + + int piFlags = PendingIntent.FLAG_UPDATE_CURRENT | (Build.VERSION.SDK_INT >= 23 ? PendingIntent.FLAG_IMMUTABLE : 0); + PendingIntent togglePi = PendingIntent.getBroadcast(ctx, 1, + new Intent(ACTION_TOGGLE).setPackage(ctx.getPackageName()), piFlags); + PendingIntent stopPi = PendingIntent.getBroadcast(ctx, 2, + new Intent(ACTION_STOP).setPackage(ctx.getPackageName()), piFlags); + Intent launch = ctx.getPackageManager().getLaunchIntentForPackage(ctx.getPackageName()); + PendingIntent contentPi = launch == null ? null : PendingIntent.getActivity(ctx, 0, launch, piFlags); + + boolean playingNow = isActuallyPlaying() || preparing; + Notification.Builder nb = Build.VERSION.SDK_INT >= 26 + ? new Notification.Builder(ctx, CHANNEL_ID) + : new Notification.Builder(ctx); + nb.setSmallIcon(android.R.drawable.ic_media_play) + .setContentTitle(t.title) + .setContentText(t.artist.isEmpty() ? "@" + (playingHandle == null ? "" : playingHandle) : t.artist) + .setOngoing(playingNow) + .setShowWhen(false) + .setDeleteIntent(stopPi) + .setStyle(new Notification.MediaStyle() + .setMediaSession(mediaSession.getSessionToken()) + .setShowActionsInCompactView(0, 1)) + .addAction(playingNow ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play, + playingNow ? "Пауза" : "Играть", togglePi) + .addAction(android.R.drawable.ic_menu_close_clear_cancel, "Закрыть", stopPi); + if (contentPi != null) nb.setContentIntent(contentPi); + nm.notify(NOTIF_ID, nb.build()); + } catch (Throwable error) { + Log.w(TAG, "music: notification failed: " + error); + } + } + + private static void cancelSystemNotification() { + Context ctx = appContext; + if (ctx != null) { + try { + NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE); + if (nm != null) nm.cancel(NOTIF_ID); + } catch (Throwable ignored) {} + } + if (mediaSession != null) { + try { + mediaSession.setActive(false); + mediaSession.release(); + } catch (Throwable ignored) {} + mediaSession = null; + } + } + + // ---- MD3 bubbleDialog player & manager --------------------------------------------------------------- + + private static Dialog styledBubbleDialog(Activity activity, Md3.Palette palette, String title, View body, + String actionLabel, final Runnable onAction) { + final Dialog dialog = new Dialog(activity); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout shell = new LinearLayout(activity); + shell.setOrientation(LinearLayout.VERTICAL); + shell.setPadding(Md3.dp(activity, 24), Md3.dp(activity, 22), Md3.dp(activity, 24), Md3.dp(activity, 16)); + shell.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), activity)); + TextView heading = Md3.text(activity, title, Md3.HEADLINE_SMALL, false, palette.onSurface); + heading.setPadding(0, 0, 0, Md3.dp(activity, 14)); + shell.addView(heading); + shell.addView(body, new LinearLayout.LayoutParams(-1, 0, 1f)); + LinearLayout actions = new LinearLayout(activity); + actions.setGravity(Gravity.END); + actions.setPadding(0, Md3.dp(activity, 12), 0, 0); + if (actionLabel != null && onAction != null) { + TextView act = Md3.filledButton(activity, palette, actionLabel); + act.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { onAction.run(); } + }); + LinearLayout.LayoutParams ap = new LinearLayout.LayoutParams(-2, -2); + ap.rightMargin = Md3.dp(activity, 8); + actions.addView(act, ap); + } + TextView close = Md3.textButton(activity, palette, "Закрыть"); + close.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { dialog.dismiss(); } + }); + actions.addView(close); + shell.addView(actions); + dialog.setContentView(shell); + Window window = dialog.getWindow(); + if (window != null) { + window.setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(0)); + int width = Math.round(activity.getResources().getDisplayMetrics().widthPixels * 0.92f); + window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT); + } + dialog.show(); + return dialog; + } + + /** Clean MD3 track card opened when tapping the profile music pill. */ + private static void openPlayerSheet(final Activity activity, final Md3.Palette palette, + final PlayDiscView disc, final String handleKey, final Track track) { + LinearLayout body = new LinearLayout(activity); + body.setOrientation(LinearLayout.VERTICAL); + + LinearLayout card = new LinearLayout(activity); + card.setOrientation(LinearLayout.HORIZONTAL); + card.setGravity(Gravity.CENTER_VERTICAL); + card.setPadding(Md3.dp(activity, 16), Md3.dp(activity, 14), Md3.dp(activity, 16), Md3.dp(activity, 14)); + card.setBackground(Md3.shape(palette.surfaceContainerLow, 20f, activity)); + + ImageView icon = Md3.flowerIconAvatar(activity, palette.primaryContainer, Md3Icon.NOTE, palette.onPrimaryContainer, 10); + LinearLayout.LayoutParams ip = new LinearLayout.LayoutParams(Md3.dp(activity, 48), Md3.dp(activity, 48)); + ip.rightMargin = Md3.dp(activity, 14); + card.addView(icon, ip); + + LinearLayout meta = new LinearLayout(activity); + meta.setOrientation(LinearLayout.VERTICAL); + TextView tView = Md3.text(activity, track.title, Md3.TITLE_MEDIUM, true, palette.onSurface); + meta.addView(tView); + String who = track.artist.isEmpty() ? "@" + handleKey : track.artist + " · @" + handleKey; + meta.addView(Md3.text(activity, who + " · " + formatDuration(track.duration), Md3.BODY_SMALL, false, palette.onSurfaceVariant)); + card.addView(meta, new LinearLayout.LayoutParams(0, -2, 1f)); + body.addView(card); + + LinearLayout controls = new LinearLayout(activity); + controls.setOrientation(LinearLayout.HORIZONTAL); + controls.setGravity(Gravity.CENTER_VERTICAL); + controls.setPadding(0, Md3.dp(activity, 14), 0, 0); + + final TextView playPause = Md3.filledButton(activity, palette, + track.id.equals(playingTrackId) && isActuallyPlaying() ? "Пауза" : "Играть"); + playPause.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + togglePlayback(activity, disc, handleKey, track); + playPause.setText(track.id.equals(playingTrackId) && (isActuallyPlaying() || preparing) ? "Пауза" : "Играть"); + } + }); + controls.addView(playPause); + + TextView stop = Md3.filledTonalButton(activity, palette, "Стоп"); + stop.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + release(); + playPause.setText("Играть"); + } + }); + LinearLayout.LayoutParams sp = new LinearLayout.LayoutParams(-2, -2); + sp.leftMargin = Md3.dp(activity, 8); + controls.addView(stop, sp); + body.addView(controls); + + styledBubbleDialog(activity, palette, "Музыка профиля @" + handleKey, body, null, null); + } + + /** Opens the sleek MD3 profile music manager inside LihonTSettingsActivity. */ + public static void openManager(final Activity activity, final Md3.Palette palette) { + final NicheClaim.Account account = NicheClaim.account(); + if (account == null) { + Toast.makeText(activity, "Сначала войдите в аккаунт TikTok", Toast.LENGTH_LONG).show(); + return; + } + final LinearLayout list = new LinearLayout(activity); + list.setOrientation(LinearLayout.VERTICAL); + ScrollView scroll = new ScrollView(activity); + scroll.addView(list); + + LinearLayout headerCard = new LinearLayout(activity); + headerCard.setOrientation(LinearLayout.VERTICAL); + headerCard.setPadding(Md3.dp(activity, 14), Md3.dp(activity, 12), Md3.dp(activity, 14), Md3.dp(activity, 12)); + headerCard.setBackground(Md3.shape(palette.surfaceContainerLow, 18f, activity)); + headerCard.addView(Md3.text(activity, "Ваш MP3-трек в профиле", Md3.TITLE_MEDIUM, true, palette.onSurface)); + headerCard.addView(Md3.text(activity, + "Другие пользователи увидят и смогут послушать трек, когда зайдут к вам. Перед публикацией аудио проверяется вручную.", + Md3.BODY_SMALL, false, palette.onSurfaceVariant)); + list.addView(headerCard); + + final TextView stateView = Md3.text(activity, "Загружаем список треков…", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + stateView.setPadding(0, Md3.dp(activity, 12), 0, Md3.dp(activity, 6)); + list.addView(stateView); + + final LinearLayout tracksContainer = new LinearLayout(activity); + tracksContainer.setOrientation(LinearLayout.VERTICAL); + list.addView(tracksContainer); + + final Dialog[] holder = new Dialog[1]; + holder[0] = styledBubbleDialog(activity, palette, "Музыка в профиле", scroll, "Выбрать MP3", new Runnable() { + @Override public void run() { + launchMp3Picker(activity); + } + }); + + loadMyTracks(activity, palette, account, stateView, tracksContainer, holder); + } + + private static void launchMp3Picker(Activity activity) { + try { + Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType("audio/*"); + intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"audio/mpeg", "audio/mp3"}); + activity.startActivityForResult(intent, REQUEST_PICK); + } catch (Throwable t) { + Toast.makeText(activity, "Не удалось открыть выбор файла", Toast.LENGTH_SHORT).show(); + } + } + + private static void loadMyTracks(final Activity activity, final Md3.Palette palette, + final NicheClaim.Account account, final TextView stateView, + final LinearLayout container, final Dialog[] holder) { + new Thread(new Runnable() { + @Override public void run() { + final List items = new ArrayList(); + String err = null; + try { + JSONObject reply = MemberClient.post("music_mine", new JSONObject() + .put("uid", account.uid) + .put("installation", Installation.secret(activity))); + JSONArray arr = reply.optJSONArray("tracks"); + if (arr != null) { + for (int i = 0; i < arr.length(); i++) { + JSONObject o = arr.optJSONObject(i); + if (o != null) items.add(parseTrack(o)); + } + } + } catch (Exception e) { + err = e.getMessage() == null ? "Нет связи с сервером" : e.getMessage(); + } + final String message = err; + activity.runOnUiThread(new Runnable() { + @Override public void run() { + if (activity.isFinishing() || activity.isDestroyed()) return; + container.removeAllViews(); + if (message != null) { + stateView.setText("⚠ " + message); + return; + } + if (items.isEmpty()) { + stateView.setText("Пока нет загруженных треков. Если музыки нет — на профиле ничего не показывается."); + return; + } + stateView.setText("Мои треки (" + items.size() + "):"); + boolean hasActive = false; + for (int i = 0; i < items.size(); i++) { + if (items.get(i).active && "approved".equals(items.get(i).status)) hasActive = true; + } + for (int i = 0; i < items.size(); i++) { + final Track t = items.get(i); + String sub = statusLabel(t) + (t.artist.isEmpty() ? "" : " · " + t.artist); + ImageView icon = Md3.flowerIconAvatar(activity, + t.active ? palette.primaryContainer : palette.surfaceContainer, + Md3Icon.NOTE, + t.active ? palette.onPrimaryContainer : palette.onSurfaceVariant, 8); + View trailing = null; + if (t.active) { + TextView badge = Md3.text(activity, "✓", Md3.TITLE_MEDIUM, true, palette.primary); + trailing = badge; + } + LinearLayout row = Md3.listItem(activity, palette, icon, + t.title + " (" + formatDuration(t.duration) + ")", sub, trailing, false); + row.setBackground(Md3.shape(t.active ? palette.surfaceContainerLowest : palette.surfaceContainerLow, 16f, activity)); + LinearLayout.LayoutParams rp = new LinearLayout.LayoutParams(-1, -2); + rp.topMargin = Md3.dp(activity, 8); + row.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + if (!"approved".equals(t.status)) { + Toast.makeText(activity, statusLabel(t), Toast.LENGTH_SHORT).show(); + return; + } + selectTrack(activity, palette, account, t.id, stateView, container, holder); + } + }); + container.addView(row, rp); + } + if (hasActive) { + TextView clear = Md3.filledTonalButton(activity, palette, "Убрать музыку с профиля"); + clear.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + clearTrack(activity, palette, account, stateView, container, holder); + } + }); + LinearLayout.LayoutParams cp = new LinearLayout.LayoutParams(-2, -2); + cp.topMargin = Md3.dp(activity, 12); + container.addView(clear, cp); + } + } + }); + } + }, "lihont-music-mine").start(); + } + + private static String statusLabel(Track t) { + if ("approved".equals(t.status)) return t.active ? "Установлен на профиле" : "Одобрен (нажмите, чтобы включить)"; + if ("rejected".equals(t.status)) return t.reason.isEmpty() ? "Отклонён модератором" : "Отклонён: " + t.reason; + return "Ожидает модерации"; + } + + private static void selectTrack(final Activity activity, final Md3.Palette palette, + final NicheClaim.Account account, final String id, + final TextView stateView, final LinearLayout container, final Dialog[] holder) { + new Thread(new Runnable() { + @Override public void run() { + try { + MemberClient.post("music_select", new JSONObject() + .put("uid", account.uid) + .put("installation", Installation.secret(activity)) + .put("id", id)); + invalidate(account.uniqueId); + activity.runOnUiThread(new Runnable() { + @Override public void run() { + Toast.makeText(activity, "Трек включён на профиле", Toast.LENGTH_SHORT).show(); + loadMyTracks(activity, palette, account, stateView, container, holder); + } + }); + } catch (final Exception e) { + activity.runOnUiThread(new Runnable() { + @Override public void run() { + Toast.makeText(activity, e.getMessage() == null ? "Ошибка" : e.getMessage(), Toast.LENGTH_SHORT).show(); + } + }); + } + } + }, "lihont-music-select").start(); + } + + private static void clearTrack(final Activity activity, final Md3.Palette palette, + final NicheClaim.Account account, + final TextView stateView, final LinearLayout container, final Dialog[] holder) { + new Thread(new Runnable() { + @Override public void run() { + try { + MemberClient.post("music_clear", new JSONObject() + .put("uid", account.uid) + .put("installation", Installation.secret(activity))); + invalidate(account.uniqueId); + activity.runOnUiThread(new Runnable() { + @Override public void run() { + Toast.makeText(activity, "Музыка убрана с профиля", Toast.LENGTH_SHORT).show(); + loadMyTracks(activity, palette, account, stateView, container, holder); + } + }); + } catch (final Exception e) { + activity.runOnUiThread(new Runnable() { + @Override public void run() { + Toast.makeText(activity, e.getMessage() == null ? "Ошибка" : e.getMessage(), Toast.LENGTH_SHORT).show(); + } + }); + } + } + }, "lihont-music-clear").start(); + } + + /** Handles a document URI picked from Settings: asks title/artist in MD3 bubbleDialog and uploads MP3. */ + public static void handlePickedAudio(final Activity activity, final Md3.Palette palette, final Uri uri) { + if (activity == null || uri == null) return; + new Thread(new Runnable() { + @Override public void run() { + try { + final String fileName = queryDisplayName(activity, uri); + final byte[] bytes = readBytesLimited(activity, uri, MAX_UPLOAD_BYTES); + activity.runOnUiThread(new Runnable() { + @Override public void run() { + if (!activity.isFinishing() && !activity.isDestroyed()) { + openUploadForm(activity, palette, fileName, bytes); + } + } + }); + } catch (final Exception e) { + activity.runOnUiThread(new Runnable() { + @Override public void run() { + Toast.makeText(activity, e.getMessage() == null ? "Не удалось прочитать файл" : e.getMessage(), + Toast.LENGTH_LONG).show(); + } + }); + } + } + }, "lihont-music-read").start(); + } + + private static void openUploadForm(final Activity activity, final Md3.Palette palette, String fileName, final byte[] bytes) { + String guessTitle = fileName == null ? "Мой трек" : fileName.replaceFirst("(?i)\\.[a-z0-9]{2,5}$", "").trim(); + String guessArtist = ""; + int dash = guessTitle.indexOf(" - "); + if (dash > 0 && dash + 3 < guessTitle.length()) { + guessArtist = guessTitle.substring(0, dash).trim(); + guessTitle = guessTitle.substring(dash + 3).trim(); + } + if (guessTitle.isEmpty()) guessTitle = "Мой трек"; + + LinearLayout form = new LinearLayout(activity); + form.setOrientation(LinearLayout.VERTICAL); + + form.addView(Md3.text(activity, "Файл: " + (bytes.length / 1024) + " КБ · будет проверен модератором", + Md3.BODY_SMALL, false, palette.onSurfaceVariant)); + + final EditText titleInput = styledField(activity, palette, "Название трека", guessTitle); + LinearLayout.LayoutParams tp = new LinearLayout.LayoutParams(-1, -2); + tp.topMargin = Md3.dp(activity, 12); + form.addView(titleInput, tp); + + final EditText artistInput = styledField(activity, palette, "Исполнитель", guessArtist); + LinearLayout.LayoutParams ap = new LinearLayout.LayoutParams(-1, -2); + ap.topMargin = Md3.dp(activity, 10); + form.addView(artistInput, ap); + + final Dialog[] holder = new Dialog[1]; + holder[0] = styledBubbleDialog(activity, palette, "Отправить MP3", form, "Отправить", new Runnable() { + @Override public void run() { + String t = titleInput.getText().toString().trim(); + String a = artistInput.getText().toString().trim(); + if (t.isEmpty()) t = "Мой трек"; + if (holder[0] != null) holder[0].dismiss(); + uploadTrack(activity, palette, t, a, bytes); + } + }); + } + + private static EditText styledField(Activity activity, Md3.Palette palette, String hint, String value) { + EditText edit = new EditText(activity); + edit.setHint(hint); + edit.setText(value); + edit.setHintTextColor(palette.onSurfaceVariant); + edit.setTextColor(palette.onSurface); + edit.setTextSize(Md3.BODY_LARGE); + edit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); + edit.setSingleLine(true); + edit.setBackground(Md3.outlined(0, palette.outline, 1f, 16f, activity)); + edit.setPadding(Md3.dp(activity, 14), Md3.dp(activity, 12), Md3.dp(activity, 14), Md3.dp(activity, 12)); + return edit; + } + + private static void uploadTrack(final Activity activity, final Md3.Palette palette, + final String title, final String artist, final byte[] bytes) { + final NicheClaim.Account account = NicheClaim.account(); + if (account == null) { + Toast.makeText(activity, "Сначала войдите в TikTok", Toast.LENGTH_LONG).show(); + return; + } + Toast.makeText(activity, "Отправляем MP3 на модерацию…", Toast.LENGTH_SHORT).show(); + new Thread(new Runnable() { + @Override public void run() { + try { + String b64 = Base64.encodeToString(bytes, Base64.NO_WRAP); + final JSONObject reply = MemberClient.post("music_upload", new JSONObject() + .put("uid", account.uid) + .put("installation", Installation.secret(activity)) + .put("unique_id", account.uniqueId) + .put("title", title) + .put("artist", artist) + .put("mp3", b64), 35000); + invalidate(account.uniqueId); + activity.runOnUiThread(new Runnable() { + @Override public void run() { + if (reply.optBoolean("published", false)) { + JSONObject tr = reply.optJSONObject("track"); + String st = tr != null ? tr.optString("status", "new") : "new"; + String msg = "approved".equals(st) + ? "Трек уже одобрен и включён на профиле!" + : "Отправлено на ручную модерацию! Появится после проверки."; + Toast.makeText(activity, msg, Toast.LENGTH_LONG).show(); + } else { + String code = reply.optString("code", ""); + if (!code.isEmpty()) { + openProofDialog(activity, palette, code, new Runnable() { + @Override public void run() { + uploadTrack(activity, palette, title, artist, bytes); + } + }); + } else { + Toast.makeText(activity, "Нужно подтвердить аккаунт", Toast.LENGTH_LONG).show(); + } + } + } + }); + } catch (final Exception e) { + activity.runOnUiThread(new Runnable() { + @Override public void run() { + Toast.makeText(activity, e.getMessage() == null ? "Не удалось загрузить MP3" : e.getMessage(), + Toast.LENGTH_LONG).show(); + } + }); + } + } + }, "lihont-music-upload").start(); + } + + private static void openProofDialog(final Activity activity, final Md3.Palette palette, final String code, final Runnable onRetry) { + LinearLayout box = new LinearLayout(activity); + box.setOrientation(LinearLayout.VERTICAL); + box.addView(Md3.text(activity, + "Чтобы привязать музыку к вашему профилю для всех, сервер должен один раз проверить ваш аккаунт:\n" + + "1. Скопируйте код и вставьте его в описание профиля TikTok.\n" + + "2. Нажмите «Проверить».", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant)); + TextView codeView = Md3.text(activity, code, Md3.TITLE_LARGE, true, palette.primary); + codeView.setPadding(0, Md3.dp(activity, 12), 0, Md3.dp(activity, 8)); + box.addView(codeView); + + TextView copyBtn = Md3.filledTonalButton(activity, palette, "Скопировать код"); + copyBtn.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + ClipboardManager cm = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); + if (cm != null) cm.setPrimaryClip(ClipData.newPlainText("LihonT", code)); + Toast.makeText(activity, "Код скопирован", Toast.LENGTH_SHORT).show(); + } + }); + box.addView(copyBtn, new LinearLayout.LayoutParams(-2, -2)); + + final Dialog[] holder = new Dialog[1]; + holder[0] = styledBubbleDialog(activity, palette, "Подтвердить профиль", box, "Проверить", new Runnable() { + @Override public void run() { + if (holder[0] != null) holder[0].dismiss(); + onRetry.run(); + } + }); + } + + private static void invalidate(String uniqueId) { + String h = resolveHandle(uniqueId); + if (!h.isEmpty()) CACHE.remove(h); + } + + private static String queryDisplayName(Context context, Uri uri) { + try (Cursor c = context.getContentResolver().query(uri, new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null)) { + if (c != null && c.moveToFirst()) return c.getString(0); + } catch (Throwable ignored) {} + return uri.getLastPathSegment(); + } + + private static byte[] readBytesLimited(Context context, Uri uri, int limit) throws IOException { + try (InputStream in = context.getContentResolver().openInputStream(uri); + ByteArrayOutputStream out = new ByteArrayOutputStream()) { + if (in == null) throw new IOException("Файл недоступен"); + byte[] buf = new byte[8192]; + int total = 0; + int n; + while ((n = in.read(buf)) >= 0) { + total += n; + if (total > limit) throw new IOException("Файл больше 3.5 МБ — выберите покороче"); + out.write(buf, 0, n); + } + if (out.size() < 256) throw new IOException("Слишком маленький файл"); + return out.toByteArray(); + } + } + + /** Compact rounded-pill play/pause disc painted directly with Canvas. */ + private static final class PlayDiscView extends View { + static final int MODE_PLAY = 0; + static final int MODE_PAUSE = 1; + static final int MODE_LOADING = 2; + + private Md3.Palette palette; + private int mode = MODE_PLAY; + private final Paint bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint fgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final RectF rect = new RectF(); + private final Path tri = new Path(); + + PlayDiscView(Context context, Md3.Palette palette) { + super(context); + this.palette = palette; + bgPaint.setStyle(Paint.Style.FILL); + fgPaint.setStyle(Paint.Style.FILL); + } + + void setPalette(Md3.Palette palette) { + this.palette = palette; + invalidate(); + } + + void setMode(int mode) { + if (this.mode != mode) { + this.mode = mode; + invalidate(); + } + } + + @Override protected void onDraw(Canvas canvas) { + int w = getWidth(), h = getHeight(); + if (w <= 0 || h <= 0) return; + float cx = w / 2f, cy = h / 2f; + float r = Math.min(w, h) / 2f; + bgPaint.setColor(palette.primary); + fgPaint.setColor(palette.onPrimary); + canvas.drawCircle(cx, cy, r, bgPaint); + + if (mode == MODE_PAUSE) { + float bw = r * 0.22f, bh = r * 0.72f, gap = r * 0.16f; + rect.set(cx - gap - bw, cy - bh / 2f, cx - gap, cy + bh / 2f); + canvas.drawRoundRect(rect, bw / 2f, bw / 2f, fgPaint); + rect.set(cx + gap, cy - bh / 2f, cx + gap + bw, cy + bh / 2f); + canvas.drawRoundRect(rect, bw / 2f, bw / 2f, fgPaint); + } else if (mode == MODE_LOADING) { + fgPaint.setStyle(Paint.Style.STROKE); + fgPaint.setStrokeWidth(Math.max(2f, r * 0.14f)); + rect.set(cx - r * 0.42f, cy - r * 0.42f, cx + r * 0.42f, cy + r * 0.42f); + canvas.drawArc(rect, 0f, 260f, false, fgPaint); + fgPaint.setStyle(Paint.Style.FILL); + } else { + tri.reset(); + tri.moveTo(cx - r * 0.22f, cy - r * 0.36f); + tri.lineTo(cx + r * 0.42f, cy); + tri.lineTo(cx - r * 0.22f, cy + r * 0.36f); + tri.close(); + canvas.drawPath(tri, fgPaint); + } + } + } +} diff --git a/src/lihont/two/profile/ProfilePanel.java b/src/lihont/two/profile/ProfilePanel.java index feb9baf..0b38272 100644 --- a/src/lihont/two/profile/ProfilePanel.java +++ b/src/lihont/two/profile/ProfilePanel.java @@ -139,15 +139,24 @@ final class ProfilePanel { /** Brings the page back to the skin; true when a layout parameter changed (never, today). */ boolean enforce() { if (!root.isShown()) return false; - View header = root.findViewById(id(HEADER)); - if (header instanceof ViewGroup) header((ViewGroup) header); - View avatar = root.findViewById(id(AVATAR)); - if (avatar instanceof ViewGroup) avatarBadge((ViewGroup) avatar, avatar); View grid = root.findViewById(id(GRID)); - if (grid instanceof ViewGroup) grid((ViewGroup) grid); + if (lihont.two.settings.SettingsHost.md3()) { + View header = root.findViewById(id(HEADER)); + if (header instanceof ViewGroup) header((ViewGroup) header); + View avatar = root.findViewById(id(AVATAR)); + if (avatar instanceof ViewGroup) avatarBadge((ViewGroup) avatar, avatar); + if (grid instanceof ViewGroup) grid((ViewGroup) grid); + } + ProfileMusic.attach(activity, root, grid, palette, findHandle()); return false; } + private String findHandle() { + View h = root.findViewById(id(HANDLE)); + if (h instanceof TextView) return ((TextView) h).getText().toString(); + return "me"; + } + // ---- header ------------------------------------------------------------------------ private void header(ViewGroup group) { diff --git a/src/lihont/two/profile/ProfileSkin.java b/src/lihont/two/profile/ProfileSkin.java index 213b162..80686ba 100644 --- a/src/lihont/two/profile/ProfileSkin.java +++ b/src/lihont/two/profile/ProfileSkin.java @@ -76,13 +76,18 @@ public final class ProfileSkin { if (found != root) panel = null; root = found; } - if (found == null) return true; + if (found == null) { + ProfileMusic.syncFloatingBar(activity, null); + return true; + } if (panel == null) panel = ProfilePanel.create(activity, found, theme); if (panel == null) { root = null; + ProfileMusic.syncFloatingBar(activity, null); return true; } boolean relayout = panel.enforce(); + ProfileMusic.syncFloatingBar(activity, found); if (relayout && held < MAX_HELD) { held++; return false; diff --git a/src/lihont/two/settings/AgentChat.java b/src/lihont/two/settings/AgentChat.java index caa4751..d7930a9 100644 --- a/src/lihont/two/settings/AgentChat.java +++ b/src/lihont/two/settings/AgentChat.java @@ -2,6 +2,7 @@ package lihont.two.settings; import android.app.Dialog; import android.content.ActivityNotFoundException; +import android.content.ContentValues; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; @@ -10,6 +11,9 @@ import android.graphics.Color; import android.graphics.Outline; import android.graphics.drawable.ColorDrawable; import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.provider.MediaStore; import android.text.InputType; import android.text.SpannableString; import android.text.Spanned; @@ -26,17 +30,28 @@ import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; +import android.widget.MediaController; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; +import android.widget.VideoView; import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import lihont.two.agent.AgentClient; import lihont.two.agent.CardPlan; @@ -236,9 +251,8 @@ final class AgentChat { list.removeAllViews(); List turns = store.turns(); if (turns.isEmpty()) { - addAssistantBubble("Привет! Я умею болтать, искать в интернете, находить картинки и делать слайды для поста: так, как сами " - + "скажете, не по шаблону. Свои картинки присылайте кнопкой «+».\n\nЯ не рисую новые картинки и сам ничего не публикую: " - + "открою экран публикации TikTok, а кнопку нажмёте вы. Я могу ошибаться: проверяйте то, что я сделал."); + addAssistantBubble("Привет! Я умею болтать, искать в интернете, находить картинки и делать слайды для поста. " + + "А ещё можно скинуть ссылку на видео TikTok — подождёте немного, и я переведу речь и пришлю видео с русской озвучкой и субтитрами."); return; } int lastDeck = -1; @@ -366,10 +380,68 @@ final class AgentChat { store.addUser(text, numbers); final List added = new ArrayList<>(); added.add(addUserBubble(text, numbers, jpegs)); - final View typing = addAssistantBubble("…"); + final View typing = addAssistantBubble(jpegs.isEmpty() && extractTikTokUrl(text) != null + ? "⏳ Подождите, запускаю озвучку видео…" : "…"); added.add(typing); scrollDown(); - new Thread(() -> talk(base, text, jpegs, added, typing), "lihont-agent-talk").start(); + final String dubUrl = jpegs.isEmpty() ? extractTikTokUrl(text) : null; + if (dubUrl != null) { + new Thread(() -> dubVideo(base, text, dubUrl, added, typing), "lihont-agent-dub").start(); + } else { + new Thread(() -> talk(base, text, jpegs, added, typing), "lihont-agent-talk").start(); + } + } + + private static final Pattern TIKTOK_LINK = Pattern.compile("https://(?:vt\\.|vm\\.|www\\.|m\\.)?tiktok\\.com/\\S{4,220}", Pattern.CASE_INSENSITIVE); + private static final Pattern DUB_TAG = Pattern.compile("\\[DUB_VIDEO:(https://[^\\]]+)\\]"); + + private static String extractTikTokUrl(String text) { + if (text == null) return null; + Matcher m = TIKTOK_LINK.matcher(text); + return m.find() ? m.group() : null; + } + + /** Handles TikTok link -> polls server-side Russian dubbing -> shows playable/saveable MP4 card in chat. */ + private void dubVideo(int base, final String text, final String tiktokUrl, final List added, final View typing) { + final TextView bubble = (TextView) typing; + try { + AgentClient.DubState st = AgentClient.dubStart(activity, tiktokUrl); + final String jobId = st.jobId; + if (jobId.isEmpty()) throw new AgentClient.Problem("Не удалось запустить озвучку", false); + String lastStage = ""; + for (int attempt = 0; attempt < 130; attempt++) { + if (!st.stage.isEmpty() && !st.stage.equals(lastStage)) { + lastStage = st.stage; + final String line = "⏳ Подождите: " + lastStage; + activity.runOnUiThread(() -> { + if (dialog != null) bubble.setText(line); + }); + } + if ("done".equals(st.status)) { + final String stored = (st.summary.isEmpty() ? "Готово! Видео озвучено на русский:" : st.summary) + + "\n[DUB_VIDEO:" + st.url + "]"; + store.addAssistant(stored); + activity.runOnUiThread(() -> { + if (dialog == null) return; + list.removeView(typing); + addAnswer(stored, false, added); + finishSending(); + }); + return; + } + if ("error".equals(st.status)) { + throw new AgentClient.Problem(st.error.isEmpty() ? "Не удалось озвучить видео" : st.error, false); + } + Thread.sleep(1800); + st = AgentClient.dubStatus(activity, jobId); + } + throw new AgentClient.Problem("Сервер слишком долго собирал видео, попробуйте ещё раз", false); + } catch (final AgentClient.Problem problem) { + failed(base, problem.getMessage(), problem.needLogin, text, new ArrayList(), added); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + failed(base, "Озвучка прервана", false, text, new ArrayList(), added); + } } /** @@ -590,15 +662,24 @@ final class AgentChat { * ones), the slides under it. Every view added is put into {@code shown} when that list is given. */ private void addAnswer(String raw, boolean withDeck, List shown) { + Matcher dubMatcher = DUB_TAG.matcher(raw); + String dubVideoUrl = null; + if (dubMatcher.find()) { + dubVideoUrl = dubMatcher.group(1); + raw = DUB_TAG.matcher(raw).replaceAll("").trim(); + } String words = ToolCalls.strip(CardPlan.prose(raw)); List calls = ToolCalls.parse(raw); final Deck deck = deckOf(raw); String plain = words.trim().toLowerCase(Locale.ROOT).replaceAll("[.!\\s]+$", ""); boolean done = plain.equals("готово") || plain.equals("ок"); - if (!done && (!words.isEmpty() || (deck == null && calls.isEmpty()))) { + if (!done && (!words.isEmpty() || (deck == null && calls.isEmpty() && dubVideoUrl == null))) { View bubble = addAssistantBubble(words.isEmpty() ? raw : words); if (shown != null) shown.add(bubble); } + if (dubVideoUrl != null) { + addDubCard(dubVideoUrl, shown); + } for (ToolCalls.Call call : calls) { View note = addNote((call.kind.equals(ToolCalls.FETCH) ? "Открываю: " : "Ищу: ") + call.argument); if (shown != null) shown.add(note); @@ -607,6 +688,189 @@ final class AgentChat { addDeck(deck, shown); } + /** Sleek MD3 result card for a dubbed TikTok video returned by the agent. */ + private void addDubCard(final String videoUrl, List shown) { + LinearLayout card = new LinearLayout(activity); + card.setOrientation(LinearLayout.VERTICAL); + card.setPadding(Md3.dp(activity, 14), Md3.dp(activity, 12), Md3.dp(activity, 14), Md3.dp(activity, 12)); + card.setBackground(Md3.outlined(palette.surfaceContainerHigh, palette.outlineVariant, 1f, 20f, activity)); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); + params.rightMargin = Md3.dp(activity, 28); + params.topMargin = Md3.dp(activity, 6); + + LinearLayout header = new LinearLayout(activity); + header.setOrientation(LinearLayout.HORIZONTAL); + header.setGravity(Gravity.CENTER_VERTICAL); + ImageView icon = Md3.flowerIconAvatar(activity, palette.primaryContainer, Md3Icon.LIVE, palette.onPrimaryContainer, 8); + LinearLayout.LayoutParams ip = new LinearLayout.LayoutParams(Md3.dp(activity, 40), Md3.dp(activity, 40)); + ip.rightMargin = Md3.dp(activity, 12); + header.addView(icon, ip); + LinearLayout info = new LinearLayout(activity); + info.setOrientation(LinearLayout.VERTICAL); + info.addView(Md3.text(activity, "Видео с русской озвучкой", Md3.TITLE_MEDIUM, true, palette.onSurface)); + info.addView(Md3.text(activity, "Переведённый звук + субтитры · MP4", Md3.BODY_SMALL, false, palette.onSurfaceVariant)); + header.addView(info, new LinearLayout.LayoutParams(0, -2, 1f)); + card.addView(header); + + LinearLayout actions = new LinearLayout(activity); + actions.setOrientation(LinearLayout.HORIZONTAL); + actions.setPadding(0, Md3.dp(activity, 12), 0, 0); + final TextView watch = Md3.filledButton(activity, palette, "Смотреть"); + watch.setOnClickListener(v -> openDubPlayer(videoUrl, watch)); + actions.addView(watch); + final TextView save = Md3.filledTonalButton(activity, palette, "В галерею"); + save.setOnClickListener(v -> saveDubVideo(videoUrl, save)); + LinearLayout.LayoutParams sp = new LinearLayout.LayoutParams(-2, -2); + sp.leftMargin = Md3.dp(activity, 8); + actions.addView(save, sp); + card.addView(actions); + + list.addView(card, params); + if (shown != null) shown.add(card); + } + + private File ensureDubCached(String videoUrl) throws IOException { + File dir = new File(activity.getCacheDir(), "lihont_dub"); + if (!dir.isDirectory() && !dir.mkdirs()) throw new IOException("Нет доступа к кэшу"); + String name = Integer.toHexString(videoUrl.hashCode()) + ".mp4"; + File dest = new File(dir, name); + if (dest.isFile() && dest.length() > 4096) return dest; + File part = new File(dir, name + ".part"); + HttpURLConnection conn = (HttpURLConnection) new URL(videoUrl).openConnection(); + conn.setConnectTimeout(8000); + conn.setReadTimeout(30000); + conn.setRequestProperty("User-Agent", "LihonT-Members/2"); + try { + if (conn.getResponseCode() != 200) throw new IOException("Видео больше недоступно (" + conn.getResponseCode() + ")"); + try (InputStream in = conn.getInputStream(); FileOutputStream out = new FileOutputStream(part)) { + byte[] buf = new byte[16384]; + int n; + while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); + } + if (!part.renameTo(dest)) { + //noinspection ResultOfMethodCallIgnored + dest.delete(); + if (!part.renameTo(dest)) throw new IOException("Не удалось сохранить во временный файл"); + } + return dest; + } finally { + conn.disconnect(); + } + } + + private void openDubPlayer(final String videoUrl, final TextView button) { + button.setEnabled(false); + button.setText("Загрузка…"); + new Thread(() -> { + try { + final File file = ensureDubCached(videoUrl); + activity.runOnUiThread(() -> { + button.setEnabled(true); + button.setText("Смотреть"); + if (dialog == null) return; + showVideoDialog(file); + }); + } catch (final Exception e) { + activity.runOnUiThread(() -> { + button.setEnabled(true); + button.setText("Смотреть"); + Toast.makeText(activity, e.getMessage() == null ? "Не удалось скачать видео" : e.getMessage(), + Toast.LENGTH_LONG).show(); + }); + } + }, "lihont-dub-play").start(); + } + + private void showVideoDialog(File mp4File) { + final Dialog playerDlg = new Dialog(activity); + playerDlg.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout shell = new LinearLayout(activity); + shell.setOrientation(LinearLayout.VERTICAL); + shell.setPadding(Md3.dp(activity, 14), Md3.dp(activity, 14), Md3.dp(activity, 14), Md3.dp(activity, 10)); + shell.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), activity)); + + final VideoView vv = new VideoView(activity); + MediaController mc = new MediaController(activity); + mc.setAnchorView(vv); + vv.setMediaController(mc); + vv.setVideoURI(Uri.fromFile(mp4File)); + vv.setOnPreparedListener(mp -> { + mp.setLooping(true); + vv.start(); + }); + int vh = Math.round(activity.getResources().getDisplayMetrics().heightPixels * 0.62f); + shell.addView(vv, new LinearLayout.LayoutParams(-1, vh)); + + LinearLayout footer = new LinearLayout(activity); + footer.setGravity(Gravity.END); + footer.setPadding(0, Md3.dp(activity, 8), 0, 0); + TextView close = Md3.textButton(activity, palette, "Закрыть"); + close.setOnClickListener(v -> playerDlg.dismiss()); + footer.addView(close); + shell.addView(footer); + + playerDlg.setContentView(shell); + playerDlg.setOnDismissListener(d -> { + try { vv.stopPlayback(); } catch (Throwable ignored) {} + }); + activity.styleDialog(playerDlg); + Window w = playerDlg.getWindow(); + if (w != null) { + w.setBackgroundDrawable(new ColorDrawable(0)); + int width = Math.round(activity.getResources().getDisplayMetrics().widthPixels * 0.94f); + w.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT); + } + playerDlg.show(); + } + + private void saveDubVideo(final String videoUrl, final TextView button) { + button.setEnabled(false); + button.setText("Сохраняю…"); + new Thread(() -> { + try { + File cached = ensureDubCached(videoUrl); + String name = "LihonT_dub_" + System.currentTimeMillis() + ".mp4"; + if (Build.VERSION.SDK_INT >= 29) { + ContentValues cv = new ContentValues(); + cv.put(MediaStore.Video.Media.DISPLAY_NAME, name); + cv.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4"); + cv.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES + "/LihonT"); + Uri uri = activity.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cv); + if (uri == null) throw new IOException("Не удалось создать файл в Галерее"); + try (FileInputStream in = new FileInputStream(cached); + OutputStream out = activity.getContentResolver().openOutputStream(uri)) { + if (out == null) throw new IOException("Не удалось записать в Галерею"); + byte[] buf = new byte[16384]; + int n; + while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); + } + } else { + File movies = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "LihonT"); + if (!movies.isDirectory() && !movies.mkdirs()) throw new IOException("Не удалось создать папку Movies/LihonT"); + File outFile = new File(movies, name); + try (FileInputStream in = new FileInputStream(cached); FileOutputStream out = new FileOutputStream(outFile)) { + byte[] buf = new byte[16384]; + int n; + while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); + } + activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(outFile))); + } + activity.runOnUiThread(() -> { + button.setEnabled(true); + button.setText("В галерею"); + Toast.makeText(activity, "Видео сохранено в Галерею (Movies/LihonT)", Toast.LENGTH_LONG).show(); + }); + } catch (final Exception e) { + activity.runOnUiThread(() -> { + button.setEnabled(true); + button.setText("В галерею"); + Toast.makeText(activity, e.getMessage() == null ? "Не удалось сохранить видео" : e.getMessage(), + Toast.LENGTH_LONG).show(); + }); + } + }, "lihont-dub-save").start(); + } + /** The slides under the answer: a strip of small pictures, the description, and the button for TikTok's post screen. */ private void addDeck(final Deck deck, List shown) { final LinearLayout box = new LinearLayout(activity); diff --git a/src/lihont/two/settings/LihonTSettingsActivity.java b/src/lihont/two/settings/LihonTSettingsActivity.java index e39dc3d..af19c91 100644 --- a/src/lihont/two/settings/LihonTSettingsActivity.java +++ b/src/lihont/two/settings/LihonTSettingsActivity.java @@ -19,6 +19,7 @@ import android.os.Handler; import android.os.Looper; import android.text.Editable; import android.text.InputFilter; +import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; @@ -46,7 +47,7 @@ import java.util.Locale; /** Material 3 settings screen for LihonT 2. */ public final class LihonTSettingsActivity extends Activity { - private static final String VERSION_LINE = "LihonT 3 · Luna beta 1"; + private static final String VERSION_LINE = "LihonT 2.3.0 · Serena"; private static final String BASE_LINE = "База TikTok 47.1.3"; private static final String CHANNEL_URL = "https://t.me/lihont"; private static final String SOURCE_URL = "https://git.lihont.space/lihont/LihonT"; @@ -93,7 +94,17 @@ public final class LihonTSettingsActivity extends Activity { + "• Компактная нижняя панель без подписей.\n" + "• Меню сохранения: качество от меньшего к большему, только звук, фото без водяного знака.\n" + "• Переключатели рекламы, эфиров и вкладки «Магазин» в ленте.\n" - + "• Значки TikTok You и MargyT рядом с ником и значок «Нишевый мод»."; + + "• Значки TikTok You и MargyT рядом с ником и значок «Нишевый мод».\n" + + "• Чёрный список ленты: @ник, id:..., #тег или слово. Включается в настройках мода и хранится только на телефоне.\n" + + "• Возврат звука у видео, которые TikTok заглушил по региону или авторским правам: игрок снова идёт по обычному пути unmute. Выключается в настройках мода.\n" + + "• Защита OLED от выгорания: раз в минуту интерфейс сдвигается на пиксель по маленькому квадрату. Включается в «Параметрах».\n" + + "• A/B-флаги TikTok: редактор key=value в разделе «Эксперименты». Подменяет серверные значения после сохранения, часть флагов ждёт перезапуска.\n" + + "• Плагины .ltp: условия по длительности, лайкам, свежести, музыке и подписчикам; действие keep — белый список поверх скрытия.\n" + + "• PiP (картинка в картинке) и фоновое воспроизведение звука.\n" + + "• Системный шрифт, свой .ttf и паки эмодзи (Twemoji или свой .ttf).\n" + + "• Очистка аккаунта: удаление репостов, снятие лайков и отписка с живым счётчиком и остановкой.\n" + + "• Общая музыка профиля (MP3 после ручной модерации, мини-плеер сверху и медиа-плеер в шторке).\n" + + "• ИИ-озвучка видео TikTok по ссылке на русский язык с субтитрами прямо в чате ИИ-агента."; private static final String DISCLAIMER = "Бесплатная модификация TikTok для Android. Проект не связан с ByteDance и TikTok Pte. Ltd."; @@ -210,12 +221,20 @@ public final class LihonTSettingsActivity extends Activity { Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BANNER, palette.onPrimaryContainer, 8), settings.profileBanners(), TOGGLE_BANNERS)); cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(profileMusicRow()); + cardFunc.addView(Md3.cardDivider(this, palette)); cardFunc.addView(switchRow("Репост комментариев", "Действие репоста у комментария", Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.REPOST, palette.onPrimaryContainer, 8), settings.commentReposts(), TOGGLE_REPOSTS)); cardFunc.addView(Md3.cardDivider(this, palette)); cardFunc.addView(commentPhotosRow()); cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(longCommentsRow()); + cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(pipRow()); + cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(bgPlayRow()); + cardFunc.addView(Md3.cardDivider(this, palette)); cardFunc.addView(switchRow("Интерфейс в стиле MD3", "Нижняя панель, меню профиля и настройки TikTok. Выключено: вид Serena 1.2", Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8), @@ -229,6 +248,8 @@ public final class LihonTSettingsActivity extends Activity { cardFunc.addView(Md3.cardDivider(this, palette)); cardFunc.addView(seekbarRow()); cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(soundRow()); + cardFunc.addView(Md3.cardDivider(this, palette)); cardFunc.addView(switchRow("Меню сохранения", "Качество от меньшего к большему, только звук, фото карусели", Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8), settings.downloadMenu(), TOGGLE_MENU)); @@ -241,6 +262,8 @@ public final class LihonTSettingsActivity extends Activity { cardPrivacy.addView(Md3.cardDivider(this, palette)); cardPrivacy.addView(ghostMessagesRow()); cardPrivacy.addView(Md3.cardDivider(this, palette)); + cardPrivacy.addView(keepRecalledRow()); + cardPrivacy.addView(Md3.cardDivider(this, palette)); cardPrivacy.addView(lockRow()); addSection("Приватность", cardPrivacy, false); @@ -299,6 +322,8 @@ public final class LihonTSettingsActivity extends Activity { cardFeed.addView(switchRow("Убрать раздел «Магазин»", "Вкладка над лентой. В бете может сбиться полоса под вкладками", Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.SHOP, palette.onPrimaryContainer, 8), settings.hideShop(), TOGGLE_SHOP)); + cardFeed.addView(Md3.cardDivider(this, palette)); + cardFeed.addView(blacklistRow()); addSection("Лента", cardFeed, false); LinearLayout cardBadges = Md3.card(this, palette); @@ -324,11 +349,21 @@ public final class LihonTSettingsActivity extends Activity { Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.MOON, palette.onPrimaryContainer, 8), settings.amoled(), TOGGLE_AMOLED)); cardParams.addView(Md3.cardDivider(this, palette)); + cardParams.addView(antiBurnRow()); + cardParams.addView(Md3.cardDivider(this, palette)); + cardParams.addView(fontsEmojiRow()); + cardParams.addView(Md3.cardDivider(this, palette)); cardParams.addView(switchRow("Компактная нижняя панель", "Без подписей под значками", Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8), settings.compactBar(), TOGGLE_COMPACT)); addSection("Параметры", cardParams, false); + LinearLayout cardFlags = Md3.card(this, palette); + cardFlags.addView(flagsRow()); + cardFlags.addView(Md3.cardDivider(this, palette)); + cardFlags.addView(cleanerRow()); + addSection("Эксперименты", cardFlags, false); + LinearLayout cardIcon = Md3.card(this, palette); View appIcon = appIconRow(); if (appIcon != null) { @@ -625,6 +660,23 @@ public final class LihonTSettingsActivity extends Activity { return row; } + /** Long comments (TikTok's cap is 2200; its own long-comment experiment knows 10000); a choice about the app. */ + private View longCommentsRow() { + Md3Switch toggle = new Md3Switch(this, palette); + toggle.setContentDescription("Длинные комментарии"); + toggle.setChecked(lihont.two.comments.LongComments.enabled(this), false); + toggle.setOnCheckedChangeListener((view, value) -> { + lihont.two.comments.LongComments.set(this, value); + showRestartNotice(); + }); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.SEND, palette.onPrimaryContainer, 8), + "Длинные комментарии", "До 10 000 символов вместо 2 200. Принимает ли их сервер, " + + "зависит от аккаунта", toggle, true); + row.setOnClickListener(v -> toggle.toggle()); + return row; + } + /** Saves the profile picture of any public account, by its user name, into the gallery. */ private View saveAvatarRow() { LinearLayout row = Md3.listItem(this, palette, @@ -676,6 +728,253 @@ public final class LihonTSettingsActivity extends Activity { sizeDialog(dialog, 0.92f); } + private static final int REQUEST_FONT = 4111; + private static final int REQUEST_EMOJI = 4112; + + /** Shared row for bubbleDialog lists, matching chooseStyle(). */ + private LinearLayout dialogOptionRow(String title, String hint, boolean current, View.OnClickListener onClick) { + LinearLayout item = new LinearLayout(this); + item.setOrientation(LinearLayout.VERTICAL); + item.setPadding(Md3.dp(this, 12), Md3.dp(this, 12), Md3.dp(this, 12), Md3.dp(this, 12)); + item.setBackground(Md3.stateLayer(this, Md3.SHAPE_EXTRA_SMALL, Md3.stateLayerColor(palette.onSurface))); + item.setClickable(true); + item.setFocusable(true); + item.addView(Md3.text(this, title + (current ? " ✓" : ""), Md3.BODY_LARGE, true, + current ? palette.primary : palette.onSurface)); + if (hint != null && !hint.isEmpty()) { + item.addView(Md3.text(this, hint, Md3.BODY_MEDIUM, false, palette.onSurfaceVariant)); + } + item.setOnClickListener(onClick); + return item; + } + + private View pipRow() { + Md3Switch toggle = new Md3Switch(this, palette); + toggle.setContentDescription("Картинка в картинке"); + toggle.setChecked(lihont.two.play.PlayControl.pipEnabled(this), false); + toggle.setOnCheckedChangeListener((view, value) -> { + lihont.two.play.PlayControl.setPipEnabled(this, value); + showRestartNotice(); + }); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8), + "Картинка в картинке (PiP)", + "Мини-окно видео при сворачивании кнопкой «Домой» и через меню TikTok", + toggle, true); + row.setOnClickListener(v -> toggle.toggle()); + return row; + } + + private View bgPlayRow() { + Md3Switch toggle = new Md3Switch(this, palette); + toggle.setContentDescription("Фоновое воспроизведение"); + toggle.setChecked(lihont.two.play.PlayControl.bgEnabled(this), false); + toggle.setOnCheckedChangeListener((view, value) -> { + lihont.two.play.PlayControl.setBgEnabled(this, value); + if (value && Build.VERSION.SDK_INT >= 24) { + try { + android.app.NotificationManager nm = (android.app.NotificationManager) getSystemService(NOTIFICATION_SERVICE); + if (nm != null && !nm.areNotificationsEnabled()) { + Intent intent = new Intent("android.settings.APP_NOTIFICATION_SETTINGS") + .putExtra("android.provider.extra.APP_PACKAGE", getPackageName()); + startActivity(intent); + } + } catch (Throwable ignored) {} + } + showRestartNotice(); + }); + boolean notifOff = false; + if (Build.VERSION.SDK_INT >= 24) { + try { + android.app.NotificationManager nm = (android.app.NotificationManager) getSystemService(NOTIFICATION_SERVICE); + notifOff = nm != null && !nm.areNotificationsEnabled(); + } catch (Throwable ignored) {} + } + String sub = notifOff + ? "Уведомления TikTok выключены в системе — включите, чтобы плеер появился в шторке" + : "При сворачивании видео продолжает играть звук и появляется плеер сверху в шторке (при выключенном PiP)"; + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.NOTE, palette.onPrimaryContainer, 8), + "Фоновое воспроизведение", sub, toggle, true); + row.setOnClickListener(v -> toggle.toggle()); + return row; + } + + private View fontsEmojiRow() { + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.CODE, palette.onPrimaryContainer, 8), + "Шрифт и паки эмодзи", + lihont.two.look.FontsAndEmoji.summary(this), + Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openFontsEmojiDialog()); + return row; + } + + private void openFontsEmojiDialog() { + final Dialog[] shown = new Dialog[1]; + LinearLayout list = new LinearLayout(this); + list.setOrientation(LinearLayout.VERTICAL); + + list.addView(Md3.subheader(this, palette, "Шрифт интерфейса")); + String[] fontIds = { + lihont.two.look.FontsAndEmoji.FONT_DEFAULT, + lihont.two.look.FontsAndEmoji.FONT_SYSTEM, + lihont.two.look.FontsAndEmoji.FONT_SERIF, + lihont.two.look.FontsAndEmoji.FONT_MONO, + }; + String[] fontNames = {"TikTok (стандартный)", "Системный Android", "Serif (с засечками)", "Моноширинный"}; + String[] fontHints = { + "Встроенный TikTok Sans", + "Шрифт вашей системы (Honor / Samsung / Pixel)", + "Книжная гарнитура с засечками", + "Фиксированная ширина знаков", + }; + String curFont = lihont.two.look.FontsAndEmoji.fontMode(this); + for (int i = 0; i < fontIds.length; i++) { + final String fid = fontIds[i]; + list.addView(dialogOptionRow(fontNames[i], fontHints[i], fid.equals(curFont), v -> { + shown[0].dismiss(); + lihont.two.look.FontsAndEmoji.setFontMode(this, fid); + showRestartNotice(); + buildScreen(); + })); + } + list.addView(dialogOptionRow("Свой файл шрифта (.ttf / .otf)", + lihont.two.look.FontsAndEmoji.FONT_CUSTOM.equals(curFont) + ? "Активен: " + lihont.two.look.FontsAndEmoji.fontLabel(this) + : "Выбрать файл шрифта с телефона", + lihont.two.look.FontsAndEmoji.FONT_CUSTOM.equals(curFont), + v -> { + shown[0].dismiss(); + pickFontFile(REQUEST_FONT); + })); + + list.addView(Md3.cardDivider(this, palette)); + list.addView(Md3.subheader(this, palette, "Паки эмодзи")); + + String curEmoji = lihont.two.look.FontsAndEmoji.emojiMode(this); + list.addView(dialogOptionRow("Системные эмодзи", "Стандартные эмодзи телефона", + lihont.two.look.FontsAndEmoji.EMOJI_SYSTEM.equals(curEmoji), v -> { + shown[0].dismiss(); + lihont.two.look.FontsAndEmoji.setEmojiMode(this, lihont.two.look.FontsAndEmoji.EMOJI_SYSTEM); + showRestartNotice(); + buildScreen(); + })); + + final boolean hasTwemoji = lihont.two.look.FontsAndEmoji.twemojiFile(this).isFile(); + final boolean twemojiActive = lihont.two.look.FontsAndEmoji.EMOJI_TWEMOJI.equals(curEmoji); + final LinearLayout twemojiRow = dialogOptionRow( + "Twemoji", + hasTwemoji ? "Цветной пак эмодзи уже скачан" : "Скачать и включить (~1.5 МБ)", + twemojiActive, null); + twemojiRow.setOnClickListener(v -> { + if (hasTwemoji) { + shown[0].dismiss(); + lihont.two.look.FontsAndEmoji.setEmojiMode(this, lihont.two.look.FontsAndEmoji.EMOJI_TWEMOJI); + showRestartNotice(); + buildScreen(); + return; + } + twemojiRow.setEnabled(false); + ((TextView) twemojiRow.getChildAt(1)).setText("Скачиваю Twemoji…"); + lihont.two.look.FontsAndEmoji.downloadTwemoji(this, (ok, msg) -> { + Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); + if (shown[0] != null && shown[0].isShowing()) shown[0].dismiss(); + if (ok) { + showRestartNotice(); + buildScreen(); + } + }); + }); + list.addView(twemojiRow); + + list.addView(dialogOptionRow("Свой пак эмодзи (.ttf)", + lihont.two.look.FontsAndEmoji.EMOJI_CUSTOM.equals(curEmoji) + ? "Активен: " + lihont.two.look.FontsAndEmoji.emojiLabel(this) + : "Выбрать цветной .ttf файл с телефона", + lihont.two.look.FontsAndEmoji.EMOJI_CUSTOM.equals(curEmoji), + v -> { + shown[0].dismiss(); + pickFontFile(REQUEST_EMOJI); + })); + + ScrollView scroll = new ScrollView(this); + scroll.addView(list, new ScrollView.LayoutParams(-1, -2)); + shown[0] = bubbleDialog("Шрифт и паки эмодзи", scroll, null, null); + } + + private void pickFontFile(int reqCode) { + Intent pick = new Intent(Intent.ACTION_OPEN_DOCUMENT); + pick.addCategory(Intent.CATEGORY_OPENABLE); + pick.setType("*/*"); + try { + startActivityForResult(pick, reqCode); + } catch (ActivityNotFoundException | SecurityException none) { + Toast.makeText(this, "Не найден файловый менеджер", Toast.LENGTH_SHORT).show(); + } + } + + private View cleanerRow() { + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DELETE, palette.onPrimaryContainer, 8), + "Очистка аккаунта", + "Удалить все репосты, снять лайки или отписаться от подписок", + Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openCleanerDialog()); + return row; + } + + private void openCleanerDialog() { + LinearLayout body = new LinearLayout(this); + body.setOrientation(LinearLayout.VERTICAL); + final TextView statusText = Md3.text(this, + "Удаляет элементы через вашу текущую сессию с паузой между запросами. Действие необратимо.", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + statusText.setPadding(0, 0, 0, Md3.dp(this, 10)); + body.addView(statusText); + + final java.util.concurrent.atomic.AtomicReference stopRef = + new java.util.concurrent.atomic.AtomicReference(); + final TextView stopBtn = Md3.textButton(this, palette, "Остановить"); + stopBtn.setVisibility(View.GONE); + stopBtn.setOnClickListener(v -> { + java.util.concurrent.atomic.AtomicBoolean flag = stopRef.get(); + if (flag != null) flag.set(true); + stopBtn.setEnabled(false); + }); + + for (final lihont.two.account.AccountCleaner.Kind kind : lihont.two.account.AccountCleaner.Kind.values()) { + String title = kind == lihont.two.account.AccountCleaner.Kind.REPOSTS ? "Убрать все репосты" + : kind == lihont.two.account.AccountCleaner.Kind.LIKES ? "Снять все лайки" + : "Отписаться от всех подписок"; + String hint = kind == lihont.two.account.AccountCleaner.Kind.REPOSTS ? "Пройти по списку репостов и удалить" + : kind == lihont.two.account.AccountCleaner.Kind.LIKES ? "Убрать «Нравится» с видео в избранном" + : "Отписаться от аккаунтов в списке подписок"; + body.addView(dialogOptionRow(title, hint, false, v -> { + if (stopRef.get() != null) return; + stopBtn.setVisibility(View.VISIBLE); + stopBtn.setEnabled(true); + statusText.setText("Очищаю " + kind.title + "…"); + stopRef.set(lihont.two.account.AccountCleaner.start(kind, new lihont.two.account.AccountCleaner.Progress() { + @Override public void onStep(int removed, int failed, String detail) { + statusText.setText(detail + (failed > 0 ? " (ошибок: " + failed + ")" : "")); + } + @Override public void onDone(boolean stopped, int removed, int failed, String message) { + stopRef.set(null); + stopBtn.setVisibility(View.GONE); + statusText.setText(message); + } + })); + })); + } + body.addView(stopBtn); + Dialog shown = bubbleDialog("Очистка аккаунта", body, null, null); + shown.setOnDismissListener(d -> { + java.util.concurrent.atomic.AtomicBoolean flag = stopRef.get(); + if (flag != null) flag.set(true); + }); + } + /** The scrubbing bar under every video, also where TikTok hides it. */ private View seekbarRow() { Md3Switch toggle = new Md3Switch(this, palette); @@ -690,6 +989,194 @@ public final class LihonTSettingsActivity extends Activity { return row; } + /** The A/B editor: raw key=value overrides for TikTok's server settings. */ + private View flagsRow() { + int count = lihont.two.flags.Flags.lines(this).size(); + boolean on = lihont.two.flags.Flags.enabled(this); + String hint = count == 0 + ? "Пока пусто: key=value" + : "Флагов: " + count + (on ? " · включены" : " · выключены"); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.CODE, palette.onPrimaryContainer, 8), + "A/B-флаги TikTok", hint, Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openFlagsDialog()); + return row; + } + + private void openFlagsDialog() { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout box = new LinearLayout(this); + box.setOrientation(LinearLayout.VERTICAL); + box.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); + box.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + box.addView(Md3.text(this, "A/B-флаги TikTok", Md3.HEADLINE_SMALL, false, palette.onSurface)); + TextView info = Md3.text(this, + "По одному key=value в строке. Это серверные эксперименты TikTok: можно включить скрытую функцию или сломать ленту. После сохранения часть флагов ждёт перезапуска.", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + info.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 12)); + box.addView(info); + + final EditText input = new EditText(this); + input.setGravity(Gravity.TOP | Gravity.START); + input.setMinLines(5); + input.setMaxLines(9); + input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE + | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + input.setHorizontallyScrolling(false); + input.setTextSize(16f); + input.setTextColor(palette.onSurface); + input.setHintTextColor(palette.onSurfaceVariant); + input.setHint("key=value\nanother_flag=true"); + input.setBackground(Md3.outlined(Color.TRANSPARENT, palette.outline, 1f, Md3.SHAPE_SMALL, this)); + input.setPadding(Md3.dp(this, 12), Md3.dp(this, 10), Md3.dp(this, 12), Md3.dp(this, 10)); + input.setText(android.text.TextUtils.join("\n", lihont.two.flags.Flags.lines(this))); + box.addView(input); + + final Md3Switch toggle = new Md3Switch(this, palette); + toggle.setChecked(lihont.two.flags.Flags.enabled(this), false); + LinearLayout toggleRow = Md3.listItem(this, palette, null, "Подменять значения", + "Выключено — флаги TikTok остаются как с сервера", toggle, true); + toggleRow.setOnClickListener(v -> toggle.toggle()); + LinearLayout.LayoutParams toggleParams = new LinearLayout.LayoutParams(-1, -2); + toggleParams.topMargin = Md3.dp(this, 12); + box.addView(toggleRow, toggleParams); + + LinearLayout buttons = new LinearLayout(this); + buttons.setGravity(Gravity.END); + buttons.setPadding(0, Md3.dp(this, 16), 0, 0); + TextView cancel = Md3.textButton(this, palette, "Отмена"); + TextView save = Md3.filledButton(this, palette, "Сохранить"); + buttons.addView(cancel); + buttons.addView(save); + box.addView(buttons); + + cancel.setOnClickListener(v -> dialog.dismiss()); + save.setOnClickListener(v -> { + List lines = new ArrayList(); + for (String line : input.getText().toString().split("\n")) lines.add(line); + lihont.two.flags.Flags.save(this, lines, toggle.isChecked()); + dialog.dismiss(); + Toast.makeText(this, "Флаги сохранены", Toast.LENGTH_SHORT).show(); + buildScreen(); + }); + dialog.setContentView(box); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.92f); + } + + /** The OLED shift: one pixel around a small square once a minute. */ + private View antiBurnRow() { + final Md3Switch toggle = new Md3Switch(this, palette); + toggle.setContentDescription("Защита OLED от выгорания"); + toggle.setChecked(lihont.two.look.AntiBurn.enabled(this), false); + toggle.setOnCheckedChangeListener((view, value) -> lihont.two.look.AntiBurn.setEnabled(this, value)); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.MOON, palette.onPrimaryContainer, 8), + "Защита OLED от выгорания", + "Раз в минуту сдвигает экран на пиксель: незаметно, но статичные элементы не выжигают матрицу", + toggle, true); + row.setOnClickListener(v -> toggle.toggle()); + return row; + } + + /** The switch for the region/copyright mute that TikTok puts on some videos. */ + private View soundRow() { + final Md3Switch toggle = new Md3Switch(this, palette); + toggle.setContentDescription("Вернуть звук заглушённым видео"); + toggle.setChecked(lihont.two.sound.Sound.enabled(this), false); + toggle.setOnCheckedChangeListener((view, value) -> lihont.two.sound.Sound.setEnabled(this, value)); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.NOTE, palette.onPrimaryContainer, 8), + "Вернуть звук заглушённым видео", + "Если TikTok убрал звук по региону или авторским правам", toggle, true); + row.setOnClickListener(v -> toggle.toggle()); + return row; + } + + /** The feed black list: authors, hashtags, ids and words whose videos are not shown. */ + private View blacklistRow() { + int count = lihont.two.feed.BlacklistStore.rules(this).size(); + boolean on = lihont.two.feed.BlacklistStore.enabled(this); + String hint = count == 0 + ? "Пока пусто: @ник, #тег, id:... или слово" + : "Правил: " + count + (on ? " · включён" : " · выключен"); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DELETE, palette.onPrimaryContainer, 8), + "Чёрный список ленты", hint, Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openBlacklistDialog()); + return row; + } + + private void openBlacklistDialog() { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout box = new LinearLayout(this); + box.setOrientation(LinearLayout.VERTICAL); + box.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); + box.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + box.addView(Md3.text(this, "Чёрный список ленты", Md3.HEADLINE_SMALL, false, palette.onSurface)); + TextView info = Md3.text(this, + "По одному правилу в строке: @ник, id:..., #тег или слово. Слова ищутся в описании видео. До 500 правил.", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + info.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 12)); + box.addView(info); + + final EditText input = new EditText(this); + input.setGravity(Gravity.TOP | Gravity.START); + input.setMinLines(5); + input.setMaxLines(9); + input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE + | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + input.setHorizontallyScrolling(false); + input.setTextSize(16f); + input.setTextColor(palette.onSurface); + input.setHintTextColor(palette.onSurfaceVariant); + input.setHint("@spammer\n#fyp\nid:MS4wLjAB...\nслово"); + input.setBackground(Md3.outlined(Color.TRANSPARENT, palette.outline, 1f, Md3.SHAPE_SMALL, this)); + input.setPadding(Md3.dp(this, 12), Md3.dp(this, 10), Md3.dp(this, 12), Md3.dp(this, 10)); + input.setText(android.text.TextUtils.join("\n", lihont.two.feed.BlacklistStore.rules(this))); + box.addView(input); + + final Md3Switch toggle = new Md3Switch(this, palette); + toggle.setChecked(lihont.two.feed.BlacklistStore.enabled(this), false); + LinearLayout toggleRow = Md3.listItem(this, palette, null, "Скрывать эти видео", + "Выключено — список не трогает ленту", toggle, true); + toggleRow.setOnClickListener(v -> toggle.toggle()); + LinearLayout.LayoutParams toggleParams = new LinearLayout.LayoutParams(-1, -2); + toggleParams.topMargin = Md3.dp(this, 12); + box.addView(toggleRow, toggleParams); + + LinearLayout buttons = new LinearLayout(this); + buttons.setGravity(Gravity.END); + buttons.setPadding(0, Md3.dp(this, 16), 0, 0); + TextView cancel = Md3.textButton(this, palette, "Отмена"); + TextView save = Md3.filledButton(this, palette, "Сохранить"); + buttons.addView(cancel); + buttons.addView(save); + box.addView(buttons); + + cancel.setOnClickListener(v -> dialog.dismiss()); + save.setOnClickListener(v -> { + List lines = new ArrayList(); + for (String line : input.getText().toString().split("\n")) lines.add(line); + if (!lihont.two.feed.BlacklistStore.save(this, lines)) { + Toast.makeText(this, "Не удалось сохранить список", Toast.LENGTH_LONG).show(); + return; + } + lihont.two.feed.BlacklistStore.setEnabled(this, toggle.isChecked()); + lihont.two.feed.BlacklistStore.reload(); + dialog.dismiss(); + Toast.makeText(this, "Чёрный список сохранён", Toast.LENGTH_SHORT).show(); + buildScreen(); + }); + dialog.setContentView(box); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.92f); + } + /** Ghost mode for stories: the view is not reported, so the author does not see the person among the viewers. */ private View ghostStoriesRow() { Md3Switch toggle = new Md3Switch(this, palette); @@ -718,6 +1205,47 @@ public final class LihonTSettingsActivity extends Activity { return row; } + /** Keeps recalled chat messages visible locally when the sender deletes them for everyone. */ + private View keepRecalledRow() { + Md3Switch toggle = new Md3Switch(this, palette); + toggle.setContentDescription("Сохранять удалённые"); + toggle.setChecked(lihont.two.ghost.Ghost.keepRecalledOn(this), false); + toggle.setOnCheckedChangeListener((view, value) -> lihont.two.ghost.Ghost.setKeepRecalled(this, value)); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DELETE, palette.onPrimaryContainer, 8), + "Сохранять удалённые", "Сообщения, которые собеседник удалил у всех, останутся видимыми в чате", + toggle, true); + row.setOnClickListener(v -> toggle.toggle()); + return row; + } + + /** Shared moderated profile music bar & my MP3 uploader. */ + private View profileMusicRow() { + LinearLayout group = new LinearLayout(this); + group.setOrientation(LinearLayout.VERTICAL); + + Md3Switch toggle = new Md3Switch(this, palette); + toggle.setContentDescription("Музыка в профиле"); + toggle.setChecked(lihont.two.profile.ProfileMusic.enabled(this), false); + toggle.setOnCheckedChangeListener((view, value) -> lihont.two.profile.ProfileMusic.setEnabled(this, value)); + LinearLayout toggleRow = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.NOTE, palette.onPrimaryContainer, 8), + "Музыка в профиле", "Слушать треки на профилях (если музыки нет — пузырь скрыт)", + toggle, true); + toggleRow.setOnClickListener(v -> toggle.toggle()); + group.addView(toggleRow); + + group.addView(Md3.cardDivider(this, palette)); + + LinearLayout manageRow = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.secondaryContainer, Md3Icon.NOTE, palette.onSecondaryContainer, 8), + "Мой MP3-трек", "Загрузить аудио на модерацию для своего профиля", + Md3.chevron(this, palette), false); + manageRow.setOnClickListener(v -> lihont.two.profile.ProfileMusic.openManager(this, palette)); + group.addView(manageRow); + return group; + } + // ---- the lock: TikTok, every chat or chosen chats, opened by the phone's own fingerprint / face / lock-screen code @@ -2403,6 +2931,12 @@ public final class LihonTSettingsActivity extends Activity { @Override protected void onActivityResult(int request, int result, Intent data) { super.onActivityResult(request, result, data); + if (request == lihont.two.profile.ProfileMusic.REQUEST_PICK) { + if (result == RESULT_OK && data != null && data.getData() != null) { + lihont.two.profile.ProfileMusic.handlePickedAudio(this, palette, data.getData()); + } + return; + } if (request == AgentChat.REQUEST_PICK) { if (result == RESULT_OK && data != null && data.getData() != null && cards != null) cards.picked(data.getData()); return; @@ -2419,6 +2953,18 @@ public final class LihonTSettingsActivity extends Activity { if (result == RESULT_OK && data != null && data.getData() != null) bubblePicked(data.getData()); return; } + if (request == REQUEST_FONT || request == REQUEST_EMOJI) { + if (result == RESULT_OK && data != null && data.getData() != null) { + boolean isEmoji = request == REQUEST_EMOJI; + Uri pickedUri = data.getData(); + String name = pickedUri.getLastPathSegment(); + boolean ok = lihont.two.look.FontsAndEmoji.importFile(this, pickedUri, isEmoji, name); + Toast.makeText(this, ok ? "Сохранено, перезапустите приложение" : "Не удалось загрузить .ttf/.otf", + Toast.LENGTH_LONG).show(); + if (ok) buildScreen(); + } + return; + } if (request == PluginSettings.REQUEST_PICK) { if (result == RESULT_OK && data != null && data.getData() != null && plugins != null) { plugins.picked(data.getData()); diff --git a/src/lihont/two/settings/Md3.java b/src/lihont/two/settings/Md3.java index 3472315..1b1ef16 100644 --- a/src/lihont/two/settings/Md3.java +++ b/src/lihont/two/settings/Md3.java @@ -89,7 +89,7 @@ public final class Md3 { /** The look of the LihonT site (calm, near-monochrome, thin lines); set once, when the palette is made, by {@link #siteOf}. */ public boolean site; - private Palette(boolean dark, boolean classic, int primary, int onPrimary, int primaryContainer, + Palette(boolean dark, boolean classic, int primary, int onPrimary, int primaryContainer, int onPrimaryContainer, int secondaryContainer, int onSecondaryContainer, int tertiary, int onTertiary, int tertiaryContainer, int onTertiaryContainer, int surface, int surfaceContainerLowest, int surfaceContainerLow, @@ -218,6 +218,8 @@ public final class Md3 { /** True while the screens being built use the site look (the icon tiles below have no palette to ask). */ static volatile boolean siteLook; + /** Corner scale chosen for the site look (SiteAccent): 1 soft, 1.4 round, 0.6 sharp. */ + static volatile float siteRadiusScale = 1f; /** The palette of the site look for the light or the dark scheme. */ static Palette site(boolean dark) { @@ -451,7 +453,7 @@ public final class Md3 { public static GradientDrawable shape(int color, float radiusDp, Context context) { GradientDrawable drawable = new GradientDrawable(); drawable.setColor(color); - drawable.setCornerRadius(dp(context, radiusDp)); + drawable.setCornerRadius(dp(context, siteLook && radiusDp < SHAPE_FULL ? radiusDp * siteRadiusScale : radiusDp)); return drawable; } diff --git a/src/lihont/two/settings/Presets.java b/src/lihont/two/settings/Presets.java new file mode 100644 index 0000000..76f2286 --- /dev/null +++ b/src/lihont/two/settings/Presets.java @@ -0,0 +1,220 @@ +package lihont.two.settings; + +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Base64; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; + +/** + * Named snapshots of the full mod settings plus the style chosen in ThemeEngine. + * + * Up to {@link #MAX_PRESETS} presets live in the SharedPreferences file "lihont_presets" as one + * JSON array (org.json ships with Android): + * {"presets":[{"name":..., "settings":, "style":}, ...]}. + * The array keeps the user's order; an equal name overwrites in place. Nothing here throws + * outward: every failure is reported as null or false. + */ +public final class Presets { + public static final int MAX_PRESETS = 10; + /** Long enough for a memorable name, short enough to stay readable in the dialog. */ + public static final int MAX_NAME_LENGTH = 50; + /** The prefix of a portable export produced by {@link #exportText} and read by {@link #importText}. */ + public static final String EXPORT_PREFIX = "LIHONT-PRESET:1:"; + /** A bound for pasted import strings, well above what a real preset needs. */ + private static final int MAX_EXPORT_LENGTH = 20000; + + private static final String PREFS = "lihont_presets"; + private static final String KEY = "presets"; + + /** + * ThemeEngine stores its choice privately ("lihont_style", key "theme", legacy "sticker" + * flag) and offers no id getter: its active() is package-private and returns a spec, not the + * id. Presets therefore read the same file and mirror ThemeEngine.active's mapping. + */ + private static final String STYLE_PREFS = "lihont_style"; + private static final String STYLE_KEY = "theme"; + private static final String STYLE_LEGACY_STICKER = "sticker"; + + private Presets() {} + + /** A loaded preset: the settings to persist and the theme id to hand to ThemeEngine.set. */ + public static final class Loaded { + public final ModSettings settings; + public final String styleId; + + Loaded(ModSettings settings, String styleId) { + this.settings = settings; + this.styleId = styleId; + } + } + + /** The preset names in stored order; empty when there are none or storage cannot be read. */ + public static List list(Context context) { + List names = new ArrayList(); + try { + JSONArray presets = read(context); + for (int i = 0; i < presets.length(); i++) { + JSONObject preset = presets.optJSONObject(i); + String name = preset == null ? null : preset.optString("name", null); + if (name != null && name.length() > 0 && !names.contains(name)) names.add(name); + } + } catch (Exception unreadable) { + names.clear(); + } + return names; + } + + /** + * Saves the current settings and the current ThemeEngine style under name. An equal name + * overwrites in place. False when the name is empty or too long, the settings are unusable, + * or all ten slots are taken. + */ + public static boolean save(Context context, String name, ModSettings settings) { + String trimmed = trimmedName(name); + if (trimmed == null) return false; + try { + JSONArray presets = read(context); + JSONObject entry = new JSONObject(); + entry.put("name", trimmed); + entry.put("settings", SettingsCodec.encode(settings)); + entry.put("style", currentStyleId(context)); + int existing = indexOf(presets, trimmed); + if (existing >= 0) { + presets.put(existing, entry); + } else { + if (presets.length() >= MAX_PRESETS) return false; + presets.put(entry); + } + write(context, presets); + return true; + } catch (Exception error) { + return false; + } + } + + /** The preset under name, or null when it is missing, unreadable or not a valid document. */ + public static Loaded load(Context context, String name) { + if (name == null) return null; + try { + JSONArray presets = read(context); + int index = indexOf(presets, name); + if (index < 0) return null; + JSONObject preset = presets.getJSONObject(index); + ModSettings settings = SettingsCodec.decode(preset.getString("settings")); + String style = preset.optString("style", "site"); + return new Loaded(settings, style.length() == 0 ? "site" : style); + } catch (Exception error) { + return null; + } + } + + /** Removes the preset; false when it was not there or storage failed. */ + public static boolean delete(Context context, String name) { + if (name == null) return false; + try { + JSONArray presets = read(context); + int index = indexOf(presets, name); + if (index < 0) return false; + presets.remove(index); + write(context, presets); + return true; + } catch (Exception error) { + return false; + } + } + + /** "LIHONT-PRESET:1:" + base64 of the preset's JSON, or null when it cannot be produced. */ + public static String exportText(Context context, String name) { + if (name == null) return null; + try { + JSONArray presets = read(context); + int index = indexOf(presets, name); + if (index < 0) return null; + byte[] bytes = presets.getJSONObject(index).toString().getBytes("UTF-8"); + return EXPORT_PREFIX + Base64.encodeToString(bytes, Base64.NO_WRAP); + } catch (Exception error) { + return null; + } + } + + /** + * Accepts a string produced by {@link #exportText}. The preset is stored under its own name + * (an equal name is overwritten) and the name is returned. Null when the string is not a + * valid preset or all ten slots are taken. + */ + public static String importText(Context context, String text) { + if (text == null) return null; + String trimmed = text.trim(); + if (!trimmed.startsWith(EXPORT_PREFIX) || trimmed.length() > MAX_EXPORT_LENGTH) return null; + try { + byte[] bytes = Base64.decode(trimmed.substring(EXPORT_PREFIX.length()), Base64.DEFAULT); + JSONObject preset = new JSONObject(new String(bytes, "UTF-8")); + String name = trimmedName(preset.optString("name", "")); + if (name == null) return null; + // Validate the settings document before anything is stored. + String document = preset.getString("settings"); + SettingsCodec.decode(document); + String style = preset.optString("style", "site"); + JSONArray presets = read(context); + JSONObject entry = new JSONObject(); + entry.put("name", name); + entry.put("settings", document); + entry.put("style", style.length() == 0 ? "site" : style); + int existing = indexOf(presets, name); + if (existing >= 0) { + presets.put(existing, entry); + } else { + if (presets.length() >= MAX_PRESETS) return null; + presets.put(entry); + } + write(context, presets); + return name; + } catch (Exception error) { + return null; + } + } + + // ---- storage ----------------------------------------------------------- + + private static JSONArray read(Context context) throws JSONException { + String document = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .getString(KEY, null); + if (document == null || document.length() == 0) return new JSONArray(); + return new JSONArray(document); + } + + private static void write(Context context, JSONArray presets) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putString(KEY, presets.toString()).apply(); + } + + private static int indexOf(JSONArray presets, String name) throws JSONException { + for (int i = 0; i < presets.length(); i++) { + JSONObject preset = presets.optJSONObject(i); + if (preset != null && name.equals(preset.optString("name", null))) return i; + } + return -1; + } + + /** A name is trimmed, non-empty and short enough to stay readable in the dialog. */ + private static String trimmedName(String name) { + if (name == null) return null; + String trimmed = name.trim(); + if (trimmed.length() == 0 || trimmed.length() > MAX_NAME_LENGTH) return null; + return trimmed; + } + + /** + * The style id the way ThemeEngine stores it: the "theme" string, the legacy "sticker" flag, + * or "site" when nothing was chosen ("md3" is stored as "md3", as ThemeEngine.set does). + */ + private static String currentStyleId(Context context) { + return ThemeEngine.activeId(context); + } +} diff --git a/src/lihont/two/settings/SiteAccent.java b/src/lihont/two/settings/SiteAccent.java new file mode 100644 index 0000000..02347e0 --- /dev/null +++ b/src/lihont/two/settings/SiteAccent.java @@ -0,0 +1,271 @@ +package lihont.two.settings; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Color; + +/** + * Custom accent and corner rounding choices for the "Site" ("Как сайт") theme. + * + * Persisted in the "lihont_style" SharedPreferences under "site_accent" and "site_corners". + */ +public final class SiteAccent { + public static final String PREFS_NAME = "lihont_style"; + public static final String KEY_ACCENT = "site_accent"; + public static final String KEY_CORNERS = "site_corners"; + + // ---- Accent IDs --------------------------------------------------------- + public static final String ACCENT_INK = "ink"; + public static final String ACCENT_VIOLET = "violet"; + public static final String ACCENT_BLUE = "blue"; + public static final String ACCENT_GREEN = "green"; + public static final String ACCENT_ORANGE = "orange"; + public static final String ACCENT_PINK = "pink"; + + public static final String DEFAULT_ACCENT = ACCENT_INK; + + public static final String[] ACCENTS = { + ACCENT_INK, + ACCENT_VIOLET, + ACCENT_BLUE, + ACCENT_GREEN, + ACCENT_ORANGE, + ACCENT_PINK + }; + + // Baseline accent colors + public static final int COLOR_VIOLET = 0xFF7A4FD0; + public static final int COLOR_BLUE = 0xFF2F6FEB; + public static final int COLOR_GREEN = 0xFF1F9D55; + public static final int COLOR_ORANGE = 0xFFE8590C; + public static final int COLOR_PINK = 0xFFD6336C; + + // ---- Corner radius IDs -------------------------------------------------- + public static final String CORNERS_SOFT = "soft"; + public static final String CORNERS_ROUND = "round"; + public static final String CORNERS_SHARP = "sharp"; + + public static final String DEFAULT_CORNERS = CORNERS_SOFT; + + public static final String[] CORNERS = { + CORNERS_SOFT, + CORNERS_ROUND, + CORNERS_SHARP + }; + + public static final float SCALE_SOFT = 1.0f; + public static final float SCALE_ROUND = 1.4f; + public static final float SCALE_SHARP = 0.6f; + + private SiteAccent() {} + + // ---- SharedPreferences Accessors ---------------------------------------- + + public static String getAccent(Context context) { + if (context == null) return DEFAULT_ACCENT; + try { + return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .getString(KEY_ACCENT, DEFAULT_ACCENT); + } catch (Exception e) { + return DEFAULT_ACCENT; + } + } + + public static void setAccent(Context context, String accent) { + if (context == null) return; + try { + SharedPreferences.Editor edit = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit(); + if (accent == null) { + edit.remove(KEY_ACCENT); + } else { + edit.putString(KEY_ACCENT, accent); + } + edit.apply(); + } catch (Exception ignored) { + } + } + + public static String getCorners(Context context) { + if (context == null) return DEFAULT_CORNERS; + try { + return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .getString(KEY_CORNERS, DEFAULT_CORNERS); + } catch (Exception e) { + return DEFAULT_CORNERS; + } + } + + public static void setCorners(Context context, String corners) { + if (context == null) return; + try { + SharedPreferences.Editor edit = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit(); + if (corners == null) { + edit.remove(KEY_CORNERS); + } else { + edit.putString(KEY_CORNERS, corners); + } + edit.apply(); + } catch (Exception ignored) { + } + } + + // Convenience aliases + public static String accent(Context context) { + return getAccent(context); + } + + public static String corners(Context context) { + return getCorners(context); + } + + /** + * Scale factor for corner rounding: soft (1.0), round (1.4), sharp (0.6). + */ + public static float radiusScale(Context context) { + String corners = getCorners(context); + if (CORNERS_ROUND.equals(corners)) return SCALE_ROUND; + if (CORNERS_SHARP.equals(corners)) return SCALE_SHARP; + return SCALE_SOFT; + } + + // ---- Palette Transformation -------------------------------------------- + + /** + * Returns a copy of the site palette with custom accent colors applied. + * For "ink" (the default), returns the site palette as-is. + */ + public static Md3.Palette apply(Context ctx, Md3.Palette site) { + if (site == null) return null; + String accent = getAccent(ctx); + if (accent == null || ACCENT_INK.equals(accent)) { + return site; + } + + Md3.Palette cached = lastMade; + if (cached != null && lastBase == site && accent.equals(lastAccent)) return cached; + int primaryColor = accentColor(accent); + if (primaryColor == 0) { + return site; + } + + int onPrimary = onColor(primaryColor); + int primaryContainer; + int onPrimaryContainer; + int secondaryContainer; + + if (site.dark) { + // Dark scheme: deep tinted container and subtle highlight + primaryContainer = blend(primaryColor, Color.rgb(13, 13, 15), 0.22f); + onPrimaryContainer = blend(primaryColor, Color.WHITE, 0.25f); + secondaryContainer = blend(primaryColor, Color.rgb(13, 13, 15), 0.14f); + } else { + // Light scheme: pastel tinted container and dark accent text + primaryContainer = blend(primaryColor, Color.WHITE, 0.14f); + onPrimaryContainer = blend(primaryColor, Color.BLACK, 0.35f); + secondaryContainer = blend(primaryColor, Color.WHITE, 0.08f); + } + + Md3.Palette made = createPalette( + site.dark, + site.classic, + primaryColor, + onPrimary, + primaryContainer, + onPrimaryContainer, + secondaryContainer, + site.onSecondaryContainer, + site.tertiary, + site.onTertiary, + site.tertiaryContainer, + site.onTertiaryContainer, + site.surface, + site.surfaceContainerLowest, + site.surfaceContainerLow, + site.surfaceContainer, + site.surfaceContainerHigh, + site.surfaceContainerHighest, + site.onSurface, + site.onSurfaceVariant, + site.outline, + site.outlineVariant, + site.error, + site.onError, + site.errorContainer, + site.onErrorContainer + ); + lastBase = site; + lastAccent = accent; + lastMade = made; + return made; + } + + private static volatile Md3.Palette lastBase; + private static volatile String lastAccent; + private static volatile Md3.Palette lastMade; + + // ---- Color Helpers ----------------------------------------------------- + + public static int accentColor(String id) { + if (ACCENT_VIOLET.equals(id)) return COLOR_VIOLET; + if (ACCENT_BLUE.equals(id)) return COLOR_BLUE; + if (ACCENT_GREEN.equals(id)) return COLOR_GREEN; + if (ACCENT_ORANGE.equals(id)) return COLOR_ORANGE; + if (ACCENT_PINK.equals(id)) return COLOR_PINK; + return 0; + } + + /** Color for UI swatches and previews. */ + public static int color(String id, boolean dark) { + int c = accentColor(id); + if (c != 0) return c; + return dark ? Color.rgb(245, 245, 247) : Color.rgb(13, 13, 15); + } + + /** Contrast-compliant text color (white or near-black ink) on top of the given color. */ + public static int onColor(int color) { + double luminance = 0.2126 * Color.red(color) + 0.7152 * Color.green(color) + 0.0722 * Color.blue(color); + return luminance > 140 ? Color.rgb(13, 13, 15) : Color.WHITE; + } + + public static String accentName(String id) { + if (ACCENT_VIOLET.equals(id)) return "Фиолетовый"; + if (ACCENT_BLUE.equals(id)) return "Синий"; + if (ACCENT_GREEN.equals(id)) return "Зелёный"; + if (ACCENT_ORANGE.equals(id)) return "Оранжевый"; + if (ACCENT_PINK.equals(id)) return "Розовый"; + return "Графит"; + } + + public static String cornersName(String id) { + if (CORNERS_ROUND.equals(id)) return "Круглые"; + if (CORNERS_SHARP.equals(id)) return "Прямые"; + return "Мягкие"; + } + + public static int blend(int fg, int bg, float ratio) { + float inv = 1f - ratio; + int r = Math.round(Color.red(fg) * ratio + Color.red(bg) * inv); + int g = Math.round(Color.green(fg) * ratio + Color.green(bg) * inv); + int b = Math.round(Color.blue(fg) * ratio + Color.blue(bg) * inv); + return Color.rgb(r, g, b); + } + + /** A copy of the site palette with the accent colours; on any failure the site palette itself. */ + private static Md3.Palette createPalette(boolean dark, boolean classic, int primary, int onPrimary, + int primaryContainer, int onPrimaryContainer, int secondaryContainer, int onSecondaryContainer, + int tertiary, int onTertiary, int tertiaryContainer, int onTertiaryContainer, + int surface, int surfaceContainerLowest, int surfaceContainerLow, + int surfaceContainer, int surfaceContainerHigh, int surfaceContainerHighest, + int onSurface, int onSurfaceVariant, int outline, int outlineVariant, + int error, int onError, int errorContainer, int onErrorContainer) { + Md3.Palette copy = new Md3.Palette(dark, classic, primary, onPrimary, + primaryContainer, onPrimaryContainer, secondaryContainer, onSecondaryContainer, + tertiary, onTertiary, tertiaryContainer, onTertiaryContainer, + surface, surfaceContainerLowest, surfaceContainerLow, + surfaceContainer, surfaceContainerHigh, surfaceContainerHighest, + onSurface, onSurfaceVariant, outline, outlineVariant, + error, onError, errorContainer, onErrorContainer); + copy.site = true; + return copy; + } +} diff --git a/src/lihont/two/settings/ThemeEngine.java b/src/lihont/two/settings/ThemeEngine.java index 0270370..dad8227 100644 --- a/src/lihont/two/settings/ThemeEngine.java +++ b/src/lihont/two/settings/ThemeEngine.java @@ -20,6 +20,18 @@ public final class ThemeEngine { private ThemeEngine() {} /** The theme that is on: the site look when nothing was chosen; null for Material 3 (or plain TikTok when Material 3 is off). */ + /** The id of the chosen style as stored ("site" when nothing is stored yet, "sticker" for the old flag), for presets. */ + static String activeId(Context context) { + try { + android.content.SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + String id = prefs.getString(KEY, null); + if (id == null && prefs.getBoolean(LEGACY_STICKER, false)) id = "sticker"; + return id == null ? "site" : id; + } catch (RuntimeException unreadable) { + return "site"; + } + } + static ThemeSpec active(Context context) { try { android.content.SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); @@ -82,7 +94,14 @@ public final class ThemeEngine { static Md3.Palette palette(Context context, Md3.Palette base) { ThemeSpec spec = active(context); Md3.siteLook = spec == ThemeSpec.SITE; - if (spec == ThemeSpec.SITE) return Md3.site(base.dark); + if (spec == ThemeSpec.SITE) { + Md3.siteRadiusScale = SiteAccent.radiusScale(context); + try { + return SiteAccent.apply(context, Md3.site(base.dark)); + } catch (RuntimeException broken) { + return Md3.site(base.dark); // an accent must never break the screen + } + } if (spec == null || !spec.ownColors) return base; Md3.Palette built = spec.palette; if (built == null) { diff --git a/src/lihont/two/sound/Sound.java b/src/lihont/two/sound/Sound.java new file mode 100644 index 0000000..e93abd7 --- /dev/null +++ b/src/lihont/two/sound/Sound.java @@ -0,0 +1,47 @@ +package lihont.two.sound; + +import android.content.Context; +import android.content.SharedPreferences; + +/** + * Restores audio that TikTok muted for a region or a copyright claim. + * + *

TikTok marks such videos in {@code AwemeStatus.VideoMuteInfo.isMute}; the feed player + * calls {@code mute()} when it sees the flag. The smali patch sends the flag through + * {@link #unmute(boolean)} instead, so the player takes its normal {@code unmute()} path. + */ +public final class Sound { + private static final String PREFS = "lihont_sound"; + private static final String KEY = "unmute"; + private static volatile Boolean cached; + + private Sound() { + } + + /** The switch from the settings screen; on until the person turns it off. */ + public static boolean enabled(Context context) { + Boolean value = cached; + if (value == null) { + SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + value = prefs.getBoolean(KEY, true); + cached = value; + } + return value; + } + + /** The value used by the patched TikTok class, which has no context. */ + public static boolean enabled() { + Boolean value = cached; + return value == null || value; + } + + public static void setEnabled(Context context, boolean on) { + cached = on; + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY, on).apply(); + } + + /** Replaces the server's mute flag with "not muted" while the switch is on. */ + public static boolean unmute(boolean original) { + return enabled() ? false : original; + } +} diff --git a/src/lihont/two/theme/NativeTheme.java b/src/lihont/two/theme/NativeTheme.java index f919ddb..2c4b653 100644 --- a/src/lihont/two/theme/NativeTheme.java +++ b/src/lihont/two/theme/NativeTheme.java @@ -312,6 +312,31 @@ public final class NativeTheme { // the window background; the bar colours cover older, non-edge-to-edge setups. Window window = activity.getWindow(); window.setBackgroundDrawable(new ColorDrawable(palette.surface | 0xFF000000)); + // newer TikTok versions lay their own light background over the window, behind the system bars too: every view + // from the content up to the decor that carries a plain opaque colour takes the page colour + final int page = palette.surface | 0xFF000000; + final android.view.View decor = window.getDecorView(); + decor.post(() -> { + try { + android.view.View content = decor.findViewById(android.R.id.content); + for (android.view.View view = content; view != null; ) { + android.graphics.drawable.Drawable bg = view.getBackground(); + if (bg instanceof ColorDrawable && (((ColorDrawable) bg).getColor() >>> 24) == 0xFF + && ((ColorDrawable) bg).getColor() != page) { + view.setBackgroundColor(page); + } + android.view.ViewParent parent = view.getParent(); + view = parent instanceof android.view.View ? (android.view.View) parent : null; + } + if (content instanceof android.view.ViewGroup && ((android.view.ViewGroup) content).getChildCount() > 0) { + android.view.View root = ((android.view.ViewGroup) content).getChildAt(0); + android.graphics.drawable.Drawable bg = root.getBackground(); + if (bg instanceof ColorDrawable && (((ColorDrawable) bg).getColor() >>> 24) == 0xFF) root.setBackgroundColor(page); + } + } catch (Throwable ignored) { + // the window colour above still covers the common case + } + }); window.setStatusBarColor(palette.surface); window.setNavigationBarColor(palette.surface); if (Build.VERSION.SDK_INT >= 29) { diff --git a/src/web/assets/promo/beta1/cat_1.jpg b/src/web/assets/promo/beta1/cat_1.jpg new file mode 100644 index 0000000..bfe5341 Binary files /dev/null and b/src/web/assets/promo/beta1/cat_1.jpg differ diff --git a/src/web/assets/promo/beta1/cat_2.jpg b/src/web/assets/promo/beta1/cat_2.jpg new file mode 100644 index 0000000..98b68e5 Binary files /dev/null and b/src/web/assets/promo/beta1/cat_2.jpg differ diff --git a/src/web/assets/promo/beta1/cat_3.jpg b/src/web/assets/promo/beta1/cat_3.jpg new file mode 100644 index 0000000..c49f474 Binary files /dev/null and b/src/web/assets/promo/beta1/cat_3.jpg differ diff --git a/src/web/assets/promo/beta1/cat_4.jpg b/src/web/assets/promo/beta1/cat_4.jpg new file mode 100644 index 0000000..3645c37 Binary files /dev/null and b/src/web/assets/promo/beta1/cat_4.jpg differ diff --git a/src/web/index.html b/src/web/index.html index 88a703d..a627b01 100644 --- a/src/web/index.html +++ b/src/web/index.html @@ -6,12 +6,12 @@ - - - + + + - LihonT 3 · Luna: TikTok в стиле Material 3 + LihonT 2.3.0 · Serena: TikTok в стиле Material 3 + + diff --git a/tests/java/lihont/two/feed/BlacklistTest.java b/tests/java/lihont/two/feed/BlacklistTest.java new file mode 100644 index 0000000..92b033f --- /dev/null +++ b/tests/java/lihont/two/feed/BlacklistTest.java @@ -0,0 +1,56 @@ +package lihont.two.feed; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** Scenarios of the black list rules; prints PASS when every one holds. */ +public final class BlacklistTest { + private static int checks; + + private BlacklistTest() {} + + public static void main(String[] args) { + List lines = Arrays.asList("", " ", "@Spammer", "cat", "#fyp", "id:MS4wLjAB", + "@ spaced ", "#", "@", "id:", " #Dogs "); + Blacklist list = Blacklist.parse(lines); + check(list.size() == 6, "six rules, blank and bare-prefix lines skipped: " + list.size()); + + check(list.blocks("funny cat video", "someone", "1", "s", null), "a word of the description"); + check(list.blocks("CAT", null, null, null, null), "the word ignores case"); + check(list.blocks("cats and dogs are friends here", "someone", "1", "s", null), + "a word is a part of the description"); + check(!list.blocks("i love dogs", "someone", "1", "s", null), "a tag rule does not match the description"); + check(!list.blocks("a quiet video", "someone", "1", "s", null), "no rule, no block"); + + check(list.blocks("hello", "spammer", "1", "s", null), "the author by nick, any case"); + check(!list.blocks("hello", "@spammer", "1", "s", null), "the nick is compared as TikTok keeps it, without @"); + check(!list.blocks("hello", "spammer2", "1", "s", null), "a nick is whole, not a part"); + + check(list.blocks("hello", "renamed", "ms4wljab", "x", null), "the author by uid"); + check(list.blocks("hello", "renamed", "1", "MS4wLjAB", null), "the author by secUid"); + check(!list.blocks("hello", "renamed", "2", "x", null), "another uid passes"); + + check(list.blocks("x", "someone", "1", "s", new String[] {"FYP", "other"}), "a hashtag of the video"); + check(list.blocks("x", "someone", "1", "s", new String[] {null, "dogs"}), "a hashtag after a null one"); + check(!list.blocks("#fyp in the text only", "someone", "1", "s", null), "a tag rule looks at hashtags, not at the text"); + + check(!list.blocks(null, null, null, null, null), "a video without anything is not blocked"); + check(!Blacklist.parse(null).blocks("cat", "spammer", "1", "s", new String[] {"fyp"}), "no list blocks nothing"); + check(Blacklist.parse(Arrays.asList("a", "b")).isEmpty() == false, "two rules are a list"); + + List many = new ArrayList(); + for (int i = 0; i < Blacklist.MAX_RULES + 50; i++) many.add("word" + i); + check(Blacklist.parse(many).size() == Blacklist.MAX_RULES, "the list is capped"); + StringBuilder longWord = new StringBuilder("x"); + for (int i = 0; i < 200; i++) longWord.append('y'); + check(Blacklist.parse(Arrays.asList(longWord.toString())).isEmpty(), "a rule too long to read is dropped"); + + System.out.println("PASS"); + } + + private static void check(boolean holds, String what) { + checks++; + if (!holds) throw new AssertionError("check " + checks + " failed: " + what); + } +} diff --git a/tests/java/lihont/two/plugin/PluginTest.java b/tests/java/lihont/two/plugin/PluginTest.java index 83f51a3..119ec46 100644 --- a/tests/java/lihont/two/plugin/PluginTest.java +++ b/tests/java/lihont/two/plugin/PluginTest.java @@ -7,6 +7,7 @@ import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; @@ -28,6 +29,9 @@ public final class PluginTest { String selfName = "me"; String selfUid = "1000001"; String uid = ""; + final Map numbers = new HashMap(); + final Set flags = new HashSet(); + String music = ""; int minute = 12 * 60; int weekday = 3; @@ -38,6 +42,12 @@ public final class PluginTest { @Override public String selfName() { return selfName; } @Override public String selfUid() { return selfUid; } @Override public String uid() { return uid; } + @Override public long number(String field) { + Long value = numbers.get(field); + return value == null ? -1 : value.longValue(); + } + @Override public boolean flag(String field) { return flags.contains(field); } + @Override public String music() { return music; } @Override public int minute() { return minute; } @Override public int weekday() { return weekday; } @Override public String clock() { return "14:35"; } @@ -106,6 +116,13 @@ public final class PluginTest { refused(head("[\"feed.hide\"]", ok).replace("\"ltp\":1,", ""), "ltp"); refused(head("[\"feed.hide\"]", hide("{\"text\":[\"a\"],\"hashtag\":[\"b\"]}")), "ровно одно"); refused(head("[\"feed.hide\"]", hide("{\"magic\":[\"a\"]}")), "такого условия нет"); + refused(head("[\"feed.hide\"]", hide("{\"likes\":[1]}")), "нужно [от, до]"); + refused(head("[\"feed.hide\"]", hide("{\"likes\":[null,null]}")), "хотя бы одну границу"); + refused(head("[\"feed.hide\"]", hide("{\"likes\":[10,5]}")), "больше"); + refused(head("[\"feed.hide\"]", hide("{\"chance\":0}")), "от 1 до 100"); + refused(head("[\"feed.hide\"]", hide("{\"verified\":false}")), "нужно true"); + refused(head("[\"feed.hide\"]", "{\"title\":\"r\",\"when\":\"name.show\",\"do\":[{\"feed.keep\":true}]}"), + "только в правиле feed.item"); refused(head("[\"feed.hide\"]", hide("{\"time\":\"25:00-07:00\"}")), "время"); refused(head("[\"feed.hide\"]", hide("{\"time\":\"10:00-10:00\"}")), "не равно"); refused(head("[\"feed.hide\"]", hide("{\"weekday\":[8]}")), "от 1 до 7"); @@ -192,6 +209,88 @@ public final class PluginTest { check(Evaluator.hidingRule(mine, f) != null, "rule for this account"); } + private static void numbers() throws Exception { + Fake f = new Fake(); + + Plugin seconds = plugin(head("[\"feed.hide\"]", hide("{\"duration\":[10,60]}"))); + f.numbers.put("duration", Long.valueOf(30)); + check(Evaluator.hidingRule(seconds, f) != null, "duration inside the range"); + f.numbers.put("duration", Long.valueOf(10)); + check(Evaluator.hidingRule(seconds, f) != null, "duration on the lower bound"); + f.numbers.put("duration", Long.valueOf(5)); + check(Evaluator.hidingRule(seconds, f) == null, "duration below the range"); + f.numbers.put("duration", Long.valueOf(61)); + check(Evaluator.hidingRule(seconds, f) == null, "duration above the range"); + + Plugin likes = plugin(head("[\"feed.hide\"]", hide("{\"likes\":[1000,null]}"))); + f.numbers.put("likes", Long.valueOf(1000)); + check(Evaluator.hidingRule(likes, f) != null, "likes on the bound"); + f.numbers.put("likes", Long.valueOf(999)); + check(Evaluator.hidingRule(likes, f) == null, "fewer likes"); + f.numbers.remove("likes"); + check(Evaluator.hidingRule(likes, f) == null, "unknown likes never match"); + + Plugin fresh = plugin(head("[\"feed.hide\"]", hide("{\"age\":[0,7]}"))); + f.numbers.put("age", Long.valueOf(7)); + check(Evaluator.hidingRule(fresh, f) != null, "a week old is fresh"); + f.numbers.put("age", Long.valueOf(8)); + check(Evaluator.hidingRule(fresh, f) == null, "eight days is older"); + + Plugin followers = plugin(head("[\"feed.hide\"]", hide("{\"followers\":[100000,null]}"))); + f.numbers.put("followers", Long.valueOf(250000)); + check(Evaluator.hidingRule(followers, f) != null, "a big author"); + f.numbers.put("followers", Long.valueOf(50)); + check(Evaluator.hidingRule(followers, f) == null, "a small author"); + + Plugin verified = plugin(head("[\"feed.hide\"]", hide("{\"verified\":true}"))); + f.flags.add("verified"); + check(Evaluator.hidingRule(verified, f) != null, "verified author"); + f.flags.clear(); + check(Evaluator.hidingRule(verified, f) == null, "not verified"); + + Plugin photo = plugin(head("[\"feed.hide\"]", hide("{\"photo\":true}"))); + f.flags.add("photo"); + check(Evaluator.hidingRule(photo, f) != null, "photo post"); + f.flags.clear(); + + Plugin liked = plugin(head("[\"feed.hide\"]", hide("{\"liked\":true}"))); + f.flags.add("liked"); + check(Evaluator.hidingRule(liked, f) != null, "already liked"); + f.flags.clear(); + + Plugin music = plugin(head("[\"feed.hide\"]", hide("{\"music\":[\"phonk\"]}"))); + f.music = "night phonk mix"; + check(Evaluator.hidingRule(music, f) != null, "music word"); + f.music = "calm piano"; + check(Evaluator.hidingRule(music, f) == null, "other music"); + f.music = ""; + + Plugin chance = plugin(head("[\"feed.hide\"]", hide("{\"chance\":100}"))); + check(Evaluator.hidingRule(chance, f) != null, "100% always"); + + Plugin keep = plugin(head("[\"feed.hide\"]", + "{\"title\":\"r\",\"when\":\"feed.item\",\"do\":[{\"feed.keep\":true}]}")); + check(keep.rules.get(0).keeps(), "keep is read"); + check(!keep.rules.get(0).hides(), "keep does not hide"); + check(keep.rules.get(0).says().contains("оставить видео"), "keep in words: " + keep.rules.get(0).says()); + check(Defender.check(keep).text().contains("Оставляет видео, даже если другие правила просят его скрыть."), + "keep in the defender"); + + // the numbers say themselves in words, the same words the Python library uses + check(plugin(head("[\"feed.hide\"]", hide("{\"duration\":[10,60]}"))).rules.get(0).says() + .contains("видео длительностью от 10 до 60 секунд"), "duration words"); + check(plugin(head("[\"feed.hide\"]", hide("{\"likes\":[null,5]}"))).rules.get(0).says() + .contains("лайков не больше 5"), "likes words"); + check(plugin(head("[\"feed.hide\"]", hide("{\"age\":[3,null]}"))).rules.get(0).says() + .contains("видео не моложе 3 дней"), "age words"); + check(plugin(head("[\"feed.hide\"]", hide("{\"verified\":true}"))).rules.get(0).says() + .contains("автор с галочкой"), "verified words"); + check(plugin(head("[\"feed.hide\"]", hide("{\"music\":[\"jazz\"]}"))).rules.get(0).says() + .contains("в музыке есть «jazz»"), "music words"); + check(plugin(head("[\"feed.hide\"]", hide("{\"chance\":25}"))).rules.get(0).says() + .contains("с вероятностью 25%"), "chance words"); + } + private static void names() throws Exception { String rules = "{\"title\":\"p\",\"when\":\"name.show\",\"if\":{\"uid\":[\"self\"]},\"do\":[{\"name.suffix\":\" · {time}\"}]}," + "{\"title\":\"q\",\"when\":\"name.show\",\"if\":{\"uid\":[\"555\"]},\"do\":[{\"name.prefix\":\"★ \"},{\"name.suffix\":\" ({date})\"}]}," @@ -709,6 +808,7 @@ public final class PluginTest { if (name.equals("parse")) parse(); else if (name.equals("refusals")) refusals(); else if (name.equals("conditions")) conditions(); + else if (name.equals("numbers")) numbers(); else if (name.equals("names")) names(); else if (name.equals("package")) pack(); else if (name.equals("hash")) hash(); diff --git a/tests/test_blacklist.py b/tests/test_blacklist.py new file mode 100644 index 0000000..39490e0 --- /dev/null +++ b/tests/test_blacklist.py @@ -0,0 +1,74 @@ +"""The black list of the feed (lihont.two.feed.Blacklist) on plain Java. + +The matching has no Android in it, so javac and one run of a small harness cover every kind of rule; +the Android part (BlacklistStore, the call from FeedFilter) is checked as text, and the whole of the +mod's Java is compiled against android.jar by the build. +""" + +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SOURCES = ROOT / "src" / "lihont" / "two" / "feed" +HARNESS = ROOT / "tests" / "java" / "lihont" / "two" / "feed" / "BlacklistTest.java" + + +class BlacklistRulesTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.javac = shutil.which("javac") + cls.java = shutil.which("java") + if not cls.javac or not cls.java: + raise RuntimeError("Blacklist tests require a JDK with java and javac") + cls.temporary = tempfile.TemporaryDirectory(prefix="lihont-blacklist-tests-") + cls.addClassCleanup(cls.temporary.cleanup) + cls.classes = Path(cls.temporary.name) / "classes" + cls.classes.mkdir() + cls.environment = dict(os.environ) + cls.environment.pop("JAVA_TOOL_OPTIONS", None) + command = [cls.javac, "--release", "17", "-encoding", "UTF-8", "-Xlint:all", "-Werror", + "-d", str(cls.classes), str(SOURCES / "Blacklist.java"), str(HARNESS)] + result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", + env=cls.environment, timeout=120) + if result.returncode: + raise AssertionError("javac failed:\n%s%s" % (result.stdout, result.stderr)) + + def test_rules(self): + command = [self.java, "-Dfile.encoding=UTF-8", "-cp", str(self.classes), "lihont.two.feed.BlacklistTest"] + result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", + env=self.environment, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stdout.strip(), "PASS") + + +class BlacklistHooksTest(unittest.TestCase): + """The feed asks the list only when the person switched it on.""" + + def test_the_feed_filter_asks_the_black_list(self): + text = (SOURCES / "FeedFilter.java").read_text(encoding="utf-8") + self.assertIn("BlacklistStore.enabled(context)", text) + self.assertIn("isBlacklisted(item, blacklist)", text) + + def test_the_filter_only_runs_when_the_list_is_on(self): + text = (SOURCES / "FeedFilter.java").read_text(encoding="utf-8") + self.assertIn("if (!ads && !live && !plugins && blacklist == null) return input;", text) + + def test_the_switch_is_off_until_the_person_turns_it_on(self): + text = (SOURCES / "BlacklistStore.java").read_text(encoding="utf-8") + self.assertIn('getBoolean(KEY_ON, false)', text) + self.assertNotIn("java.net", text) + + def test_the_settings_screen_edits_the_list(self): + text = (ROOT / "src" / "lihont" / "two" / "settings" / "LihonTSettingsActivity.java").read_text( + encoding="utf-8") + self.assertIn("blacklistRow()", text) + self.assertIn("BlacklistStore.save(this, lines)", text) + self.assertIn("BlacklistStore.setEnabled(this, toggle.isChecked())", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_dub.py b/tests/test_dub.py new file mode 100644 index 0000000..d1f2abf --- /dev/null +++ b/tests/test_dub.py @@ -0,0 +1,78 @@ +import importlib.util +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +MEMBERS_DIR = ROOT / "services" / "members" +if str(MEMBERS_DIR) not in sys.path: + sys.path.insert(0, str(MEMBERS_DIR)) + +SPEC = importlib.util.spec_from_file_location("members_server", MEMBERS_DIR / "server.py") +try: + server = importlib.util.module_from_spec(SPEC) + SPEC.loader.exec_module(server) +except ModuleNotFoundError: + server = None + +DUB_SPEC = importlib.util.spec_from_file_location("members_dub", MEMBERS_DIR / "dub.py") +try: + dub = importlib.util.module_from_spec(DUB_SPEC) + DUB_SPEC.loader.exec_module(dub) +except ModuleNotFoundError: + dub = None + + +@unittest.skipIf(server is None or dub is None, "private moderation module excluded") +class DubTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.now = 1_790_000_000 + self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now) + self.registry.dub.run_async = False + self.inst = "c" * 64 + self._sign_in(555000, self.inst) + + def _sign_in(self, tg_id, installation): + token = self.registry.accounts.call("tg_start", {"installation": installation})["token"] + self.assertTrue(self.registry.accounts.bot_link(token, tg_id)["ok"]) + self.assertEqual("linked", self.registry.accounts.call("tg_poll", {"installation": installation, "token": token})["status"]) + + def test_extract_url_and_ass_generation(self): + self.assertEqual( + "https://vt.tiktok.com/ZSr123abc/", + dub.extract_tiktok_url("озвучь пожалуйста https://vt.tiktok.com/ZSr123abc/ срочно"), + ) + self.assertIsNone(dub.extract_tiktok_url("просто текст без ссылки https://youtube.com/watch?v=1")) + + ass = dub.build_ass([{"start": 0.5, "end": 2.25, "ru": "Привет\\мир"}], 1080, 1920) + self.assertIn("PlayResX: 1080", ass) + self.assertIn("PlayResY: 1920", ass) + self.assertIn("Dialogue: 0,0:00:00.50,0:00:02.25,Default,,0,0,0,,Привет мир", ass) + + def test_parse_translation_json(self): + raw = '```json\n[{"i":0,"ru":"Первая строка"},{"i":1,"ru":"Вторая"}]\n```' + out = dub.parse_translation_json(raw, 2) + self.assertEqual(["Первая строка", "Вторая"], out) + + def test_start_and_status_lifecycle(self): + with self.assertRaises(ValueError): + self.registry.dub.start({"installation": self.inst, "url": "not a link"}) + + started = self.registry.dub.start({"installation": self.inst, "url": "https://www.tiktok.com/@bob/video/7123456789"}) + job_id = started["job_id"] + self.assertEqual("queued", started["status"]) + + st = self.registry.dub.status({"installation": self.inst, "job_id": job_id}) + self.assertEqual("queued", st["status"]) + + # Another installation cannot inspect someone else's job. + self._sign_in(999111, "d" * 64) + with self.assertRaises(ValueError): + self.registry.dub.status({"installation": "d" * 64, "job_id": job_id}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_flags.py b/tests/test_flags.py new file mode 100644 index 0000000..eee8425 --- /dev/null +++ b/tests/test_flags.py @@ -0,0 +1,63 @@ +import unittest +from pathlib import Path + +from lihont import flags_patch + +ROOT = Path(__file__).resolve().parents[1] +SETTINGS = ROOT / "src" / "lihont" / "two" / "settings" / "LihonTSettingsActivity.java" +FLAGS = ROOT / "src" / "lihont" / "two" / "flags" / "Flags.java" + +SAMPLE = """.class public Lcom/bytedance/ies/abmock/SettingsManager; +.super Ljava/lang/Object; + +.method public static LIZ(Ljava/lang/String;Z)Z + .registers 3 + return p1 +.end method + +.method public static LJ(Ljava/lang/String;I)I + .registers 3 + return p1 +.end method + +.method public static LJFF(Ljava/lang/String;J)J + .registers 4 + return-wide p1 +.end method + +.method public static LJI(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; + .registers 3 + return-object p1 +.end method +""" + + +class FlagsPatchTest(unittest.TestCase): + def test_primitive_getters_are_hooked(self): + patched = flags_patch.rewrite(SAMPLE) + self.assertIn("Flags;->bool(Ljava/lang/String;Z)Z", patched) + self.assertIn("Flags;->number(Ljava/lang/String;I)I", patched) + self.assertIn("Flags;->longer(Ljava/lang/String;J)J", patched) + self.assertIn("Flags;->text(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", patched) + self.assertIn("invoke-static {p0, p1, p2},", patched) + self.assertIn("move-result-wide p1", patched) + + def test_it_refuses_to_patch_twice(self): + patched = flags_patch.rewrite(SAMPLE) + with self.assertRaises(ValueError): + flags_patch.rewrite(patched) + + def test_the_editor_is_in_the_settings(self): + text = SETTINGS.read_text(encoding="utf-8") + self.assertIn("flagsRow()", text) + self.assertIn("Flags.save(this, lines, toggle.isChecked())", text) + self.assertIn('addSection("Эксперименты"', text) + + def test_the_editor_is_off_until_turned_on(self): + text = FLAGS.read_text(encoding="utf-8") + self.assertIn("getBoolean(KEY_ON, false)", text) + self.assertIn("MAX_LINES = 500", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_ghost_patch.py b/tests/test_ghost_patch.py index 420d3e2..941f6dc 100644 --- a/tests/test_ghost_patch.py +++ b/tests/test_ghost_patch.py @@ -145,24 +145,67 @@ class StoryViewTest(unittest.TestCase): ghost_patch.rewrite_story_view(SAMPLE.replace("LIZJ(", "LIZK(")) def test_runtime_and_build_are_in_step(self): - self.assertEqual(ghost_patch.runtime_targets(), [ghost_patch.HOOK, ghost_patch.MARK_READ_HOOK]) + self.assertEqual(ghost_patch.runtime_targets(), [ghost_patch.HOOK, ghost_patch.MARK_READ_HOOK, ghost_patch.KEEP_RECALLED_HOOK]) source = (ROOT / "src" / "lihont" / "two" / "ghost" / "Ghost.java").read_text(encoding="utf-8") self.assertIn("public static boolean stories()", source) self.assertIn("public static boolean messages()", source) + self.assertIn("public static boolean keepRecalled()", source) # ghost mode is a choice: off until the person turns it on - self.assertIn('getBoolean(STORIES, false)', source) - self.assertIn('getBoolean(MESSAGES, false)', source) + self.assertIn("readFlag(context, STORIES)", source) + self.assertIn("readFlag(context, MESSAGES)", source) + self.assertIn("readFlag(context, KEEP_RECALLED)", source) build = (ROOT / "lihont" / "upgrade.py").read_text(encoding="utf-8") self.assertIn('step("ghost_stories", patch_ghost_stories', build) self.assertIn('step("ghost_messages", patch_ghost_messages', build) + self.assertIn('step("keep_recalled", patch_keep_recalled', build) self.assertIn("ghost_patch.runtime_targets()", build) screen = (ROOT / "src" / "lihont" / "two" / "settings" / "LihonTSettingsActivity.java").read_text(encoding="utf-8") self.assertIn("ghostStoriesRow()", screen) self.assertIn("ghostMessagesRow()", screen) + self.assertIn("keepRecalledRow()", screen) # both live in their own section, not in the list of functions self.assertIn('addSection("Приватность", cardPrivacy', screen) self.assertNotIn("cardFunc.addView(ghostStoriesRow())", screen) +RECALLED_SAMPLE = """.class public LX/13m4; +.super Ljava/lang/Object; + +.method public getMessageStatus()LX/13mT; + .registers 2 + iget-object v0, p0, LX/13m4;->messageStatus:LX/13mT; + if-nez v0, :cond_18 + sget-object v0, LX/13mT;->RECALLED:LX/13mT; + return-object v0 + :cond_18 + return-object v0 +.end method + +.method public isRecalled()Z + .registers 3 + invoke-virtual {p0}, LX/13m4;->getExt()Ljava/util/Map; + move-result-object v1 + const-string v0, "s:is_recalled" + const-string v0, "s:recalled" + const/4 v0, 0x0 + return v0 +.end method +""" + + +class KeepRecalledTest(unittest.TestCase): + def test_recalled_returns_false_and_status_returns_available_when_on(self): + text = ghost_patch.rewrite_keep_recalled(RECALLED_SAMPLE) + self.assertIn("invoke-static {}, %s" % ghost_patch.KEEP_RECALLED_HOOK, text) + self.assertIn("sget-object v0, LX/13mT;->AVAILABLE:LX/13mT;", text) + self.assertIn(" .registers 3", text) + self.assertNotIn(" .registers 2", text) + self.assertEqual(text.count("Ghost;"), 2) + + def test_second_pass_is_refused(self): + with self.assertRaises(ValueError): + ghost_patch.rewrite_keep_recalled(ghost_patch.rewrite_keep_recalled(RECALLED_SAMPLE)) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_lihon_ai.py b/tests/test_lihon_ai.py new file mode 100644 index 0000000..4ea4219 --- /dev/null +++ b/tests/test_lihon_ai.py @@ -0,0 +1,283 @@ +"""Unit tests for the Lihon AI web chat (apps/lihon-ai): passwords, codes, sign-up flow.""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import re +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("lihon_ai", ROOT / "apps" / "lihon-ai" / "server.py") +assert SPEC and SPEC.loader +ai = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ai) + + +class PasswordTests(unittest.TestCase): + def test_round_trip(self): + stored = ai.hash_password("correct horse battery") + self.assertTrue(ai.check_password(stored, "correct horse battery")) + self.assertFalse(ai.check_password(stored, "correct horse battery!")) + + def test_salted(self): + self.assertNotEqual(ai.hash_password("same"), ai.hash_password("same")) + + def test_garbage_is_false(self): + self.assertFalse(ai.check_password("", "x")) + self.assertFalse(ai.check_password("md5$a$b$c", "x")) + + +class EmailTests(unittest.TestCase): + def test_good(self): + for value in ("a@b.co", "bobik@lihon.online", "test+tag@example.com"): + self.assertTrue(ai.valid_email(value), value) + + def test_bad(self): + for value in ("", "a@b", "a@@b.co", "a b@c.co", "a@b.c", "@b.co"): + self.assertFalse(ai.valid_email(ai.normalize_email(value)), value) + + def test_normalize(self): + self.assertEqual(ai.normalize_email(" Bobik@Lihon.Online "), "bobik@lihon.online") + + +class CodeTests(unittest.TestCase): + def test_deterministic(self): + self.assertEqual(ai.code_hash("a@b.co", "123456"), ai.code_hash("a@b.co", "123456")) + self.assertNotEqual(ai.code_hash("a@b.co", "123456"), ai.code_hash("a@b.co", "123457")) + self.assertNotEqual(ai.code_hash("a@b.co", "123456"), ai.code_hash("c@d.co", "123456")) + + def test_six_digits(self): + for _ in range(20): + self.assertRegex(ai.new_code(), r"^\d{6}$") + + +class WebSearchTests(unittest.TestCase): + def test_query_uses_last_user_message_and_drops_attachment(self): + messages = [ + {"role": "user", "content": "старый вопрос"}, + {"role": "assistant", "content": "старый ответ"}, + {"role": "user", "content": "курс доллара\n\n[Файл: note.txt]\nсекрет"}, + ] + self.assertEqual(ai.search_query(messages), "курс доллара") + + def test_unwraps_duckduckgo_redirect(self): + self.assertEqual( + ai.unwrap_search_link("//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fa%3Fb%3D1&rut=x"), + "https://example.com/a?b=1", + ) + self.assertEqual(ai.unwrap_search_link("javascript:alert(1)"), "") + + def test_formats_results_and_empty_search(self): + text = ai.search_results_text("запрос", [{"title": "Заголовок", "url": "https://e.example/a", "snippet": "Описание"}]) + self.assertIn("1. Заголовок — https://e.example/a", text) + self.assertIn("Описание", text) + self.assertIn("ничего не нашёл", ai.search_results_text("запрос", [])) + + def test_page_has_web_toggle(self): + page = (ROOT / "apps" / "lihon-ai" / "static" / "index.html").read_text(encoding="utf-8") + self.assertIn('id="web-toggle"', page) + self.assertIn("web: !!S.web", page) + self.assertIn("DuckDuckGo", page) + + def test_page_excerpt_keeps_the_part_with_the_answer(self): + text = ("навигация меню сайта " * 80) + " USD 1 Доллар США 82,2281 " + ("подвал сайта " * 80) + excerpt = ai.page_excerpt(text, "курс доллара к рублю сегодня") + self.assertIn("82,2281", excerpt) + self.assertLessEqual(len(excerpt), 2400) + + def test_official_currency_fact_beats_guessing(self): + page = ("с 19.11.2026 840 USD 1 Доллар США 82,2281 978 EUR 1 Евро 90,3605 " + "978 EUR 1 Евро 90,3605") + results = [ + {"title": "Банк", "url": "https://bankiros.ru/currency/usd", "snippet": "", "page": "82,4529"}, + {"title": "ЦБ РФ", "url": "https://www.cbr.ru/currency_base/daily/", "snippet": "с 19.11.2026", "page": page}, + ] + text = ai.search_results_text("Курс доллара к рублю сегодня", results) + self.assertIn("1 USD = 82,2281 RUB", text) + self.assertIn("19.11.2026", text) + self.assertLess(text.index("https://www.cbr.ru"), text.index("https://bankiros.ru")) + + def test_official_facts_need_the_cbr_page(self): + results = [{"title": "Банк", "url": "https://bankiros.ru/currency/usd", "snippet": "", "page": "82,4529"}] + self.assertEqual(ai.official_currency_facts("курс доллара", results), ([], "")) + self.assertTrue(ai.is_official("https://www.cbr.ru/currency_base/daily/")) + self.assertFalse(ai.is_official("https://cbr.ru.evil.example/")) + + def test_cbr_xml_is_parsed_without_the_web(self): + xml = ('' + 'USD182,2281' + 'EUR190,3605' + '').encode("windows-1251") + + class Reply: + def __enter__(self): + return self + def __exit__(self, *args): + return False + def read(self, _limit=0): + return xml + + from unittest import mock + ai._CBR_CACHE.clear() + with mock.patch.object(ai.urllib.request, "urlopen", return_value=Reply()): + facts = ai.cbr_currency_facts("курс доллара к рублю") + self.assertTrue(any("1 USD = 82,2281 RUB" in fact for fact in facts)) + self.assertTrue(any("19.11.2026" in fact for fact in facts)) + self.assertEqual(ai.cbr_currency_facts("какая погода"), []) + + def test_private_addresses_are_not_fetched(self): + self.assertFalse(ai.safe_public_url("http://127.0.0.1/")) + self.assertFalse(ai.safe_public_url("http://localhost/")) + self.assertFalse(ai.safe_public_url("file:///etc/passwd")) + self.assertFalse(ai.safe_public_url("http://[::1]/")) + + +class SignUpTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.app = ai.App( + database=str(Path(self.tmp.name) / "ai.sqlite3"), + static=str(ROOT / "apps" / "lihon-ai" / "static"), + code_api="http://127.0.0.1:9/never", + api_key="", + sender="Lihon ", + dev=True, + secure_cookie=False, + ) + + def tearDown(self): + self.tmp.cleanup() + + def register(self, email="bobik@lihon.online", password="password-123"): + out = io.StringIO() + with contextlib.redirect_stdout(out): + result = self.app.register(email, password) + code = re.search(r": (\d{6})$", out.getvalue().strip(), re.M) + self.assertIsNotNone(code, out.getvalue()) + return result, code.group(1) + + def test_register_creates_unverified(self): + self.register() + user = self.app.store.user_by_email("bobik@lihon.online") + self.assertEqual(user["verified"], 0) + self.assertNotEqual(user["password"], "password-123") + self.assertTrue(user["password"].startswith("pbkdf2$")) + + def test_confirm_and_login(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.app.register("bobik@lihon.online", "password-123") + code = re.search(r": (\d{6})$", out.getvalue().strip(), re.M).group(1) + result = self.app.confirm("bobik@lihon.online", code) + self.assertTrue(result["ok"]) + self.assertIsNotNone(self.app.store.user_by_token(result["token"])) + self.assertTrue(self.app.login("bobik@lihon.online", "password-123")["ok"]) + + def test_wrong_code_and_limit(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.app.register("bobik@lihon.online", "password-123") + code = re.search(r": (\d{6})$", out.getvalue().strip(), re.M).group(1) + wrong = "000000" if code != "000000" else "111111" + for _ in range(5): + with self.assertRaises(ai.ApiError) as caught: + self.app.confirm("bobik@lihon.online", wrong) + self.assertEqual(caught.exception.status, 400) + with self.assertRaises(ai.ApiError) as caught: + self.app.confirm("bobik@lihon.online", code) + self.assertEqual(caught.exception.status, 429) + + def test_duplicate_verified(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.app.register("bobik@lihon.online", "password-123") + code = re.search(r": (\d{6})$", out.getvalue().strip(), re.M).group(1) + self.app.confirm("bobik@lihon.online", code) + with self.assertRaises(ai.ApiError) as caught: + self.app.register("bobik@lihon.online", "password-123") + self.assertEqual(caught.exception.status, 409) + + def test_weak_password(self): + with self.assertRaises(ai.ApiError) as caught: + self.app.register("bobik@lihon.online", "short") + self.assertEqual(caught.exception.status, 400) + + def test_login_before_confirm(self): + self.register() + with self.assertRaises(ai.ApiError) as caught: + self.app.login("bobik@lihon.online", "password-123") + self.assertEqual(caught.exception.status, 403) + self.assertTrue(caught.exception.extra.get("needs_confirm")) + + def test_rate_limit(self): + for _ in range(5): + self.assertTrue(self.app.allow("203.0.113.9", "register")) + self.assertFalse(self.app.allow("203.0.113.9", "register")) + + +class MarkdownTests(unittest.TestCase): + def test_table(self): + page = ai.render_markdown("| Направление | Что добавить |\n|---|---|\n| **Умения** | `код` |") + self.assertIn("", page) + self.assertIn("", page) + self.assertIn("Умения", page) + self.assertIn("код", page) + + def test_code_and_escaping(self): + page = ai.render_markdown("```python\nprint('')\n```\n") + self.assertIn("
", page)
+        self.assertIn("<x>", page)
+        self.assertNotIn(""},
+        ])
+        page = ai.share_page(self.app.store.get_share(result["id"]), self.app.public)
+        self.assertNotIn("

Заголовок

a & b

") + self.assertIn("Заголовок", text) + self.assertIn("a & b", text) + self.assertNotIn("evil", text) + self.assertTrue(text.startswith("Заголовок страницы: x")) + + +class ThinkTest(AgentTest): + def test_effort_goes_to_the_model_and_thoughts_are_shown(self): + model = FakeModel([(200, {"choices": [{"message": {"content": "ок", "reasoning_content": "сначала подумаю"}}]})]) + sessions = ide.Sessions(Path(self.tmp.name) / "home", model=model) + session = sessions.create(str(self.root)) + session.data["effort"] = "high" + sessions.send(session, "привет") + self.assertTrue(session.idle.wait(5)) + self.assertEqual(model.efforts, ["high"]) + kinds = [i["kind"] for i in session.data["items"]] + self.assertIn("thoughts", kinds) + self.assertLess(kinds.index("thoughts"), kinds.index("assistant")) + self.assertNotIn("reasoning_content", json.dumps(session.data["messages"])) # thoughts are not sent back + + +class StreamingModel(FakeModel): + """Feeds the answer in pieces through on_delta, as the cloud does.""" + + def chat(self, model, messages, effort="medium", on_delta=None): + reply = super().chat(model, messages, effort) + message = reply[1]["choices"][0]["message"] + if on_delta: + text = "" + for piece in (message.get("content") or "").split(" "): + text = (text + " " + piece).strip() + on_delta("content", text) + return reply + + +class MoreTest(AgentTest): + def make(self, model): + sessions = ide.Sessions(Path(self.tmp.name) / "home", model=model) + return sessions, sessions.create(str(self.root), mode="edits") + + def wait(self, session): + self.assertTrue(session.idle.wait(5)) + + def test_streamed_text_grows_in_one_item(self): + sessions, session = self.make(StreamingModel([(200, {"choices": [{"message": {"content": "раз два три"}}]})])) + sessions.send(session, "скажи") + self.wait(session) + answers = [i for i in session.data["items"] if i["kind"] == "assistant"] + self.assertEqual(len(answers), 1) + self.assertEqual(answers[0]["text"], "раз два три") + self.assertFalse(answers[0].get("live")) + + def test_undo_one_change_and_the_later_ones_of_that_file(self): + model = FakeModel([reply(call("edit_file", path="a.txt", old="hello", new="one")), + reply(call("edit_file", path="a.txt", old="one", new="two")), + reply(call("write_file", path="b.txt", content="new"))]) + sessions, session = self.make(model) + sessions.send(session, "правь") + self.wait(session) + self.assertEqual((self.root / "a.txt").read_text(encoding="utf-8"), "two\n") + first = next(i for i in session.data["items"] if i["kind"] == "tool") + self.assertEqual(sessions.undo(session, first["id"]), ["a.txt"]) + self.assertEqual((self.root / "a.txt").read_text(encoding="utf-8"), "hello\n") + self.assertTrue((self.root / "b.txt").exists()) + self.assertEqual(sum(1 for i in session.data["items"] if i.get("status") == "undone"), 2) + sessions.send(session, "дальше") + self.wait(session) + self.assertIn("отменил", json.dumps(session.data["messages"], ensure_ascii=False)) + + def test_roll_back_the_whole_session_removes_new_files(self): + model = FakeModel([reply(call("write_file", path="new/c.txt", content="x")), reply(call("edit_file", path="a.txt", old="hello", new="bye"))]) + sessions, session = self.make(model) + sessions.send(session, "правь") + self.wait(session) + self.assertEqual(sorted(sessions.undo(session)), ["a.txt", "new/c.txt"]) + self.assertFalse((self.root / "new" / "c.txt").exists()) + self.assertEqual((self.root / "a.txt").read_text(encoding="utf-8"), "hello\n") + self.assertEqual(session.data["changed"], []) + + def test_mentioned_files_and_pictures_go_to_the_model(self): + model = FakeModel([]) + sessions, session = self.make(model) + picture = "data:image/png;base64,iVBORw0KGgo=" + sessions.send(session, "глянь @a.txt и @нет.txt", images=[picture, "javascript:alert(1)"]) + self.wait(session) + sent = model.sent[0][-1]["content"] + self.assertIsInstance(sent, list) + self.assertIn("Файл a.txt", sent[0]["text"]) + self.assertEqual([p["image_url"]["url"] for p in sent[1:]], [picture]) + user = next(i for i in session.data["items"] if i["kind"] == "user") + self.assertEqual(user["files"], ["a.txt"]) + sessions.send(session, "ещё") + self.wait(session) + self.assertIsInstance(model.sent[1][-3]["content"], str) # the old picture became a word + + def test_long_talk_is_compressed(self): + model = FakeModel([(200, {"choices": [{"message": {"content": "сводка: всё сделано"}}]})]) + sessions, session = self.make(model) + filler = "x" * 70_000 + session.data["messages"] = [{"role": "user", "content": "раз " + filler}, {"role": "assistant", "content": filler}, + {"role": "user", "content": "два " + filler}, {"role": "assistant", "content": filler}] + sessions.send(session, "три") + self.wait(session) + first = model.sent[1][1]["content"] + self.assertIn("сводка: всё сделано", first) + self.assertLess(len(json.dumps(model.sent[1])), 200_000) + self.assertTrue(any("Контекст сжат" in (i.get("text") or "") for i in session.data["items"])) + + def test_an_empty_answer_is_retried_once_then_reported(self): + empty = (200, {"choices": [{"message": {"content": "", "reasoning_content": "думаю", "finish_reason": "length"}}]}) + model = FakeModel([empty, (200, {"choices": [{"message": {"content": "сделал"}}]})]) + sessions, session = self.make(model) + sessions.send(session, "делай") + self.wait(session) + self.assertEqual(session.data["items"][-1]["text"], "сделал") + self.assertIn("оборвался", model.sent[1][-1]["content"]) + model2 = FakeModel([empty, empty]) + sessions2, session2 = self.make(model2) + sessions2.send(session2, "делай") + self.wait(session2) + self.assertEqual(session2.data["items"][-1]["type"], "empty_answer") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_ltp_sdk.py b/tests/test_ltp_sdk.py index 1291714..e981754 100644 --- a/tests/test_ltp_sdk.py +++ b/tests/test_ltp_sdk.py @@ -411,6 +411,29 @@ class AgreesWithTheApp(unittest.TestCase): java = self.java_says([self.folder_of("fun", manifest, {"star.png": png})]) self.assertEqual(java["fun"], python) + def test_the_number_conditions_get_identical_words_in_both_defenders(self): + p = Plugin("Умная", author="тест", id="lihont.smart-test", license="MIT") + p.video(shorter(15), hide, title="короткие") + p.video(longer(600) & likes(min=1000), hide, title="длинные") + p.video(comments(min=10) & shares(max=5) & plays(min=100), hide, title="числа") + p.video(fresh(7) & followers(min=100000) & verified & photo & liked, hide, title="флаги") + p.video(music("phonk", "jazz") & chance(10), hide, title="музыка") + p.video(always, hide, title="всё") + p.video(hashtag("cats"), keep, title="коты") + manifest, assets, report = build(p) + self.assertIn("видео длительностью не больше 15 секунд", report.text()) + self.assertIn("лайков не меньше 1000", report.text()) + self.assertIn("видео не старше 7 дней", report.text()) + self.assertIn("подписчиков у автора не меньше 100000", report.text()) + self.assertIn("автор с галочкой", report.text()) + self.assertIn("это фото, а не видео", report.text()) + self.assertIn("вы уже лайкнули это видео", report.text()) + self.assertIn("в музыке есть «phonk», «jazz»", report.text()) + self.assertIn("с вероятностью 10%", report.text()) + self.assertIn("оставить видео, даже если другие правила его скрывают", report.text()) + java = self.java_says([self.folder_of("smart", manifest, assets)]) + self.assertEqual(java["smart"], report.text()) + def icons_manifest(self, **icons): return {"ltp": 1, "id": "lihont.icons-test", "name": "Значки", "version": "1.0", "author": "тест", "license": "MIT", "permissions": ["ui.icons"], "icons": icons or {"like": "heart.png"}} @@ -522,6 +545,10 @@ class AgreesWithTheApp(unittest.TestCase): "bad-time": {"title": "t", "when": "feed.item", "if": {"time": "25:00-07:00"}, "do": [{"feed.hide": True}]}, "bad-limit": {"title": "t", "when": "feed.item", "limit": 99, "do": [{"notice": "x"}]}, "two-keys": {"title": "t", "when": "feed.item", "if": {"text": ["a"], "uid": ["b"]}, "do": [{"feed.hide": True}]}, + "bad-likes": {"title": "t", "when": "feed.item", "if": {"likes": [5]}, "do": [{"feed.hide": True}]}, + "bad-chance": {"title": "t", "when": "feed.item", "if": {"chance": 0}, "do": [{"feed.hide": True}]}, + "bad-flag": {"title": "t", "when": "feed.item", "if": {"verified": False}, "do": [{"feed.hide": True}]}, + "bad-bounds": {"title": "t", "when": "feed.item", "if": {"age": [10, 5]}, "do": [{"feed.hide": True}]}, } folders = [] for key, rule in bad.items(): diff --git a/tests/test_members_codegate.py b/tests/test_members_codegate.py new file mode 100644 index 0000000..de789e9 --- /dev/null +++ b/tests/test_members_codegate.py @@ -0,0 +1,251 @@ +import importlib.util +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path + +MEMBERS = Path(__file__).resolve().parents[1] / "services" / "members" +sys.path.insert(0, str(MEMBERS)) +SPEC = importlib.util.spec_from_file_location("members_server_code", MEMBERS / "server.py") +server = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(server) +import lihonc # noqa: E402 (the copy next to server.py, as on the server) + +INSTALL, INSTALL2, INSTALL3 = "a" * 64, "b" * 64, "c" * 64 +DEVICE, DEVICE2 = "d" * 64, "e" * 64 + + +class FakeResponse: + def __init__(self, payload, lines=None): + self.data = json.dumps(payload).encode() + self.lines = iter(lines or []) + + def read(self): + return self.data + + def __iter__(self): + return self.lines + + def close(self): + pass + + +class FakeRouter(lihonc.Router): + """Answers without a network: `script` maps a provider to an HTTP status (200 by default).""" + + def __init__(self): + super().__init__({spec["key"]: "k" for spec in lihonc.PROVIDERS.values()}) + self.script = {} + self.seen = [] + + def open(self, provider, model, body): + self.seen.append((provider, model, body)) + status = self.script.get(provider, 200) + if status != 200: + if status in (402, 429): + self.cool(provider) + raise lihonc.UpstreamError(provider, status, "nope") + if body.get("stream"): + pieces = [{"model": model, "choices": [{"index": 0, "delta": {"content": part}}]} for part in ("при", "вет")] + pieces.append({"model": model, "choices": [], "usage": {"total_tokens": 800}}) + return FakeResponse({}, [b"data: " + json.dumps(c).encode() + b"\n" for c in pieces] + [b"data: [DONE]\n"]) + return FakeResponse({"model": model, "usage": {"total_tokens": 1000}, + "choices": [{"message": {"role": "assistant", "content": provider}}]}) + + +class CodeGateTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.now = 1_790_000_000 + self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now) + self.gate = self.registry.codegate + self.router = FakeRouter() + self.gate.router = self.router + + def chat(self, model="LihonC-1-auto", installation=INSTALL, device=DEVICE, ip="1.1.1.1", **extra): + return self.gate.call("code_chat", {"installation": installation, "device": device, "_ip": ip, "model": model, + "messages": [{"role": "user", "content": "hi"}], **extra}) + + def status(self, installation=INSTALL, device=DEVICE, ip="1.1.1.1"): + return self.gate.call("code_status", {"installation": installation, "device": device, "_ip": ip}) + + def exhaust(self, installation=INSTALL, device=DEVICE, ip="1.1.1.1"): + who = self.gate._who({"installation": installation, "device": device, "_ip": ip}) + self.gate._spend(who, server.codegate.DEVICE_TOKENS) + + def test_needs_installation_and_device(self): + for bad in ({"installation": "x"}, {"device": "short"}, {"device": None}): + payload = {"installation": INSTALL, "device": DEVICE, "model": "LihonC-1-auto", "messages": [{"role": "user", "content": "x"}], **bad} + with self.assertRaises(ValueError): + self.gate.call("code_chat", payload) + + def test_auto_answers_with_our_name_and_falls_through(self): + self.router.script = {"groq": 429} + reply = self.chat() + self.assertEqual(reply["completion"]["model"], "LihonC-1-auto") + self.assertEqual(reply["completion"]["choices"][0]["message"]["content"], "gemini") + + def test_tools_and_fields_pass_but_nothing_else(self): + tools = [{"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}}] + self.chat(tools=tools, max_tokens=50, evil="x", stream="yes") + body = self.router.seen[-1][2] + self.assertEqual(body["tools"], tools) + self.assertFalse(body["stream"]) + self.assertNotIn("evil", body) + + def test_bad_input(self): + for bad in ({"model": "gpt-9"}, {"messages": []}, {"messages": [{"role": "hacker"}]}, {"messages": "x"}): + payload = {"installation": INSTALL, "device": DEVICE, "model": "LihonC-1-auto", "messages": [{"role": "user", "content": "x"}], **bad} + with self.assertRaises(ValueError): + self.gate.call("code_chat", payload) + + def test_arena_consent_then_answer(self): + self.assertEqual(self.chat("LihonC-1-deepseek:arena")["error"]["type"], "arena_consent_required") + self.gate.call("code_consent", {"installation": INSTALL, "device": DEVICE, "accept": True}) + reply = self.chat("LihonC-1-deepseek:arena") + self.assertEqual(reply["completion"]["model"], "LihonC-1-deepseek:arena") + self.assertEqual(self.router.seen[-1][1], "deepseek-v4-1-flash-1017") + self.assertTrue(self.status()["arena_consent"]) + + def test_arena_down_offers_auto_or_falls_back(self): + self.gate.call("code_consent", {"installation": INSTALL, "device": DEVICE, "accept": True}) + self.router.script = {"coarena": 402} + reply = self.chat("LihonC-1-deepseek:arena") + self.assertEqual(reply["error"]["type"], "arena_unavailable") + self.assertEqual(reply["error"]["switch_to"], "LihonC-1-auto") + reply = self.chat("LihonC-1-deepseek:arena", fallback="auto") + self.assertTrue(reply["switched"]) + self.assertEqual(self.status()["today"]["calls"], 1) # only the answered call is counted + + def test_all_busy_is_not_counted(self): + self.router.script = {name: 503 for name in lihonc.PROVIDERS} + self.assertEqual(self.chat()["error"]["type"], "all_providers_busy") + self.assertEqual(self.status()["today"]["tokens"], 0) + + def test_effort_is_passed_and_weighs_more(self): + self.chat(effort="high") + self.assertEqual(self.router.seen[-1][2]["reasoning_effort"], "high") + self.assertEqual(self.status()["today"]["tokens"], 3000) + self.chat(effort="low") + self.assertEqual(self.status()["today"]["tokens"], 4000) + self.chat(effort="extreme") + self.assertEqual(self.router.seen[-1][2]["reasoning_effort"], "medium") + + def test_effort_words_per_provider(self): + body = {"messages": [], "reasoning_effort": "low"} + self.assertEqual(lihonc.clean_body(body, "groq", "m")["reasoning_effort"], "low") + self.assertEqual(lihonc.clean_body(body, "coarena", "m")["reasoning_effort"], "none") + self.assertEqual(lihonc.clean_body(body, "openrouter", "m")["reasoning"], {"effort": "low"}) + self.assertNotIn("reasoning_effort", lihonc.clean_body(body, "cohere", "m")) + self.assertEqual(lihonc.clean_body(body, "zhipu", "m")["thinking"], {"type": "disabled"}) + self.assertNotIn("reasoning_effort", lihonc.clean_body(body, "zhipu", "m")) + + def test_daily_limit_on_the_same_network_is_only_a_limit(self): + self.exhaust() + for _ in range(5): + self.assertEqual(self.chat()["error"]["type"], "daily_limit") + self.assertIsNone(self.status()["banned_until"]) + + def test_going_around_warns_once_then_bans_everything(self): + self.exhaust() + self.assertEqual(self.chat()["error"]["type"], "daily_limit") + self.assertEqual(self.chat(ip="2.2.2.2")["error"]["type"], "device_limit") # another network: a warning + self.assertEqual(self.chat(ip="2.2.2.2")["error"]["type"], "daily_limit") # the same one again: no new strike + self.assertEqual(self.chat(installation=INSTALL2, ip="2.2.2.2")["error"]["type"], "banned") # a new installation: shut out + # the device, its installations and its addresses are out; another computer behind one of those addresses too, for a day + self.assertEqual(self.chat(installation=INSTALL3, device=DEVICE2, ip="1.1.1.1")["error"]["type"], "banned") + self.now += 86400 + 60 # the next day: the addresses are free again, the device is not + self.assertIn("completion", self.chat(installation=INSTALL3, device=DEVICE2, ip="1.1.1.1")) + self.assertEqual(self.chat(ip="3.3.3.3")["error"]["type"], "banned") + self.assertEqual(self.gate.unban(self.gate._hash("d", DEVICE)[2:10]), 1) + self.assertIn("completion", self.chat(ip="3.3.3.3")) + + def test_a_shared_address_has_its_own_bigger_budget(self): + who = self.gate._who({"installation": INSTALL2, "device": DEVICE2, "_ip": "5.5.5.5"}) + self.gate._spend(who, server.codegate.ADDRESS_TOKENS) + self.assertEqual(self.chat(ip="5.5.5.5")["error"]["type"], "address_limit") + self.assertIn("completion", self.chat(ip="6.6.6.6")) + + def test_server_ceiling(self): + who = self.gate._who({"installation": INSTALL2, "device": DEVICE2, "_ip": "9.9.9.9"}) + self.gate._spend(who, server.codegate.SERVER_TOKENS) + self.assertEqual(self.chat()["error"]["type"], "server_limit") + + def test_owner_device_is_not_limited(self): + os.environ["CODE_OWNER_DEVICES"] = DEVICE + self.addCleanup(os.environ.pop, "CODE_OWNER_DEVICES", None) + self.exhaust() + self.assertIn("completion", self.chat(ip="7.7.7.7")) + + def test_nothing_raw_is_stored(self): + self.chat(ip="8.8.4.4") + with self.registry.connect() as db: + dump = "\n".join(str(row) for table in ("code_use", "code_seen") for row in db.execute("SELECT * FROM %s" % table)) + for raw in ("8.8.4.4", INSTALL, DEVICE): + self.assertNotIn(raw, dump) + + def test_stream_sends_pieces_with_our_name_and_charges_at_the_end(self): + stream = self.chat(stream=True, effort="low") + self.assertIsInstance(stream, server.codegate.Stream) + events = list(stream) + text = "".join(c["choices"][0]["delta"]["content"] for c in events if c.get("choices")) + self.assertEqual(text, "привет") + self.assertTrue(all(c["model"] == "LihonC-1-auto" for c in events if "choices" in c)) + self.assertTrue(events[-1]["lihonc_done"]) + self.assertEqual(self.status()["today"]["tokens"], 800) + self.assertTrue(self.router.seen[-1][2]["stream"]) + + def test_stream_that_never_starts_falls_through(self): + self.router.script = {"groq": 429} + events = list(self.chat(stream=True)) + self.assertEqual(self.router.seen[-1][0], "gemini") + self.assertTrue(events[-1]["lihonc_done"]) + + def test_pictures_go_to_a_provider_that_sees_them(self): + picture = {"role": "user", "content": [{"type": "text", "text": "что тут?"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}]} + self.gate.call("code_chat", {"installation": INSTALL, "device": DEVICE, "_ip": "1.1.1.1", "model": "LihonC-1-auto", "messages": [picture]}) + self.assertEqual(self.router.seen[-1][0], "gemini") + + def test_paid_reserve_stops_at_its_daily_ceiling(self): + os.environ["LIHONC_ALLOW_PAID"] = "1" + self.addCleanup(os.environ.pop, "LIHONC_ALLOW_PAID", None) + free = [name for name, spec in lihonc.PROVIDERS.items() if not spec.get("paid") and name != "coarena"] + self.router.script = {name: 503 for name in free} + reply = self.chat() + self.assertEqual(self.router.seen[-1][0], "apinet") + self.router.cooling.clear() + self.router.charge("apinet", lihonc.PROVIDERS["apinet"]["daily_tokens"]) + self.chat() + self.assertEqual(self.router.seen[-1][0], "nordrouter") + self.router.cooling.clear() + self.router.charge("nordrouter", lihonc.PROVIDERS["nordrouter"]["daily_tokens"]) + self.assertEqual(self.chat()["error"]["type"], "all_providers_busy") + self.router.charge("groq", 10**9) # free ones are never capped here + self.assertTrue(self.router.available("groq") or "groq" in self.router.cooling) + + def test_paid_reserves_are_off_by_default(self): + os.environ.pop("LIHONC_ALLOW_PAID", None) + names = [provider for provider, _ in self.router.chain("LihonC-1-auto", {"messages": []})] + self.assertNotIn("apinet", names) + self.assertNotIn("nordrouter", names) + self.assertEqual(names[:3], ["groq", "gemini", "cohere"]) + + def test_a_hidden_address_is_neither_counted_nor_banned(self): + self.exhaust(ip="127.0.0.1") + self.assertEqual(self.chat(ip="127.0.0.1")["error"]["type"], "daily_limit") + self.chat(installation=INSTALL2, ip="127.0.0.1") + self.chat(installation=INSTALL3, ip="127.0.0.1") # going around: the device is banned... + self.assertEqual(self.chat(ip="127.0.0.1")["error"]["type"], "banned") + # ...but another person behind the same hidden address is not + self.assertIn("completion", self.chat(installation="f" * 64, device=DEVICE2, ip="127.0.0.1")) + + def test_routes_exist_in_the_server(self): + for operation in ("code_status", "code_chat", "code_consent"): + self.assertIn(operation, server.OPERATIONS) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_new_features.py b/tests/test_new_features.py new file mode 100644 index 0000000..15f6c8c --- /dev/null +++ b/tests/test_new_features.py @@ -0,0 +1,106 @@ +import unittest +from pathlib import Path + +from lihont import play_patch + +ROOT = Path(__file__).resolve().parents[1] +SETTINGS = ROOT / "src" / "lihont" / "two" / "settings" / "LihonTSettingsActivity.java" +TRANSLATOR = ROOT / "src" / "lihont" / "two" / "comments" / "CommentTranslator.java" +FONTS = ROOT / "src" / "lihont" / "two" / "look" / "FontsAndEmoji.java" +CLEANER = ROOT / "src" / "lihont" / "two" / "account" / "AccountCleaner.java" +PLAY = ROOT / "src" / "lihont" / "two" / "play" / "PlayControl.java" + +BG_GATE = """.class public final LX/08LC; +.super Ljava/lang/Object; + +.method public static LIZ()I + .registers 1 + const/4 v0, 0x0 + return v0 +.end method + +.method public static LIZIZ()Z + .registers 2 + const/4 v0, 0x0 + return v0 +.end method +""" + +PIP_GATE = """.class public final LX/116m; +.super Ljava/lang/Object; + +.method public static LIZ()Z + .registers 2 + const/4 v0, 0x0 + return v0 +.end method +""" + +MAIN = """.class public Lcom/ss/android/ugc/aweme/main/MainActivity; +.super LX/0tPX; + +.method public onResume()V + .registers 1 + return-void +.end method +""" + + +class NewFeaturesTest(unittest.TestCase): + def test_play_patch_gates_and_leave_hint(self): + bg = play_patch.rewrite_bg_gate(BG_GATE) + self.assertIn(play_patch.HOOK_BG_MODE, bg) + self.assertIn(play_patch.HOOK_BG_BOOL, bg) + with self.assertRaises(ValueError): + play_patch.rewrite_bg_gate(bg) + + pip = play_patch.rewrite_pip_gate(PIP_GATE) + self.assertIn(play_patch.HOOK_PIP, pip) + with self.assertRaises(ValueError): + play_patch.rewrite_pip_gate(pip) + + main = play_patch.rewrite_main_leave(MAIN) + self.assertIn(".method protected onUserLeaveHint()V", main) + self.assertIn("invoke-super {p0}, LX/0tPX;->onUserLeaveHint()V", main) + self.assertIn(play_patch.HOOK_LEAVE, main) + with self.assertRaises(ValueError): + play_patch.rewrite_main_leave(main) + + def test_settings_rows_and_classes_exist(self): + settings = SETTINGS.read_text(encoding="utf-8") + for needle in ( + "pipRow()", + "bgPlayRow()", + "fontsEmojiRow()", + "cleanerRow()", + "dialogOptionRow(", + "REQUEST_FONT", + "REQUEST_EMOJI", + ): + self.assertIn(needle, settings) + for src in (FONTS, CLEANER, PLAY): + self.assertTrue(src.is_file(), f"Missing {src}") + self.assertIn("CustomFallbackBuilder", FONTS.read_text(encoding="utf-8")) + self.assertIn("tiktok/v1/upvote/delete", CLEANER.read_text(encoding="utf-8")) + self.assertIn("enterPictureInPictureMode", PLAY.read_text(encoding="utf-8")) + + def test_profile_music_and_agent_dub_wiring(self): + music = (ROOT / "src" / "lihont" / "two" / "profile" / "ProfileMusic.java").read_text(encoding="utf-8") + self.assertIn("music_lookup", music) + self.assertIn("music_upload", music) + self.assertIn("removeIfPresent", music) + self.assertNotIn("AlertDialog", music) + self.assertNotIn("itunes.apple.com", music) + + client = (ROOT / "src" / "lihont" / "two" / "agent" / "AgentClient.java").read_text(encoding="utf-8") + self.assertIn("dubStart", client) + self.assertIn("dubStatus", client) + + chat = (ROOT / "src" / "lihont" / "two" / "settings" / "AgentChat.java").read_text(encoding="utf-8") + self.assertIn("dubVideo", chat) + self.assertIn("[DUB_VIDEO:", chat) + self.assertIn("MediaStore.Video.Media", chat) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_plugins.py b/tests/test_plugins.py index b4a75da..655e69d 100644 --- a/tests/test_plugins.py +++ b/tests/test_plugins.py @@ -60,6 +60,9 @@ class PluginCoreTest(unittest.TestCase): def test_conditions(self): self.run_scenario("conditions") + def test_numbers_and_the_white_list(self): + self.run_scenario("numbers") + def test_name_rules(self): self.run_scenario("names") diff --git a/tests/test_profile_music_server.py b/tests/test_profile_music_server.py new file mode 100644 index 0000000..30b56ad --- /dev/null +++ b/tests/test_profile_music_server.py @@ -0,0 +1,116 @@ +import base64 +import hashlib +import importlib.util +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +MEMBERS_DIR = ROOT / "services" / "members" +if str(MEMBERS_DIR) not in sys.path: + sys.path.insert(0, str(MEMBERS_DIR)) + +SPEC = importlib.util.spec_from_file_location("members_server", MEMBERS_DIR / "server.py") +try: + server = importlib.util.module_from_spec(SPEC) + SPEC.loader.exec_module(server) +except ModuleNotFoundError: + server = None + +MODBOT_PATH = MEMBERS_DIR / "modbot.py" +modbot = None +if MODBOT_PATH.is_file(): + MODBOT_SPEC = importlib.util.spec_from_file_location("members_modbot", MODBOT_PATH) + modbot = importlib.util.module_from_spec(MODBOT_SPEC) + MODBOT_SPEC.loader.exec_module(modbot) + +UID = "6812345678901234" +UID2 = "6812345678909999" +INST = "a" * 64 + + +class FakeTelegram: + def __init__(self): + self.calls = [] + self.updates = [] + + def call(self, method, fields=None, files=None, timeout=40): + self.calls.append((method, fields or {}, files or {})) + if method == "getUpdates": + u = list(self.updates) + self.updates.clear() + return u + return {"message_id": 77} + + +@unittest.skipIf(server is None, "private moderation module excluded") +class ProfileMusicServerTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.now = 1_790_000_000 + self.bio = "" + self.registry = server.Registry( + Path(self.tmp.name) / "r.sqlite3", + clock=lambda: self.now, + fetcher=lambda uid_name: (UID, self.bio), + ) + # Stub normalize_mp3 so test runs without needing ffmpeg binary. + self.registry.music.normalize = lambda raw: (b"ID3test-mp3-data-" + raw, 18) + + def _prove(self): + digest = hashlib.sha256(INST.encode("ascii")).hexdigest() + self.bio = "bio " + self.registry.code(UID, digest) + + def test_upload_moderation_lookup_and_clear(self): + # Empty lookup before any upload -> track is None. + self.assertIsNone(self.registry.music.lookup(unique_id="alice")["track"]) + + # First upload asks for bio proof. + mp3_b64 = base64.b64encode(b"\xff\xfb\x90\x00" + b"0" * 300).decode("ascii") + first = self.registry.music.upload(UID, INST, "Alice", "Midnight", "DJ Alice", mp3_b64) + self.assertFalse(first["published"]) + self.assertTrue(first["code"].startswith("LT-")) + + # Prove account and upload. + self._prove() + res = self.registry.music.upload(UID, INST, "@Alice", "Midnight", "DJ Alice", mp3_b64) + self.assertTrue(res["published"]) + tid = res["track"]["id"] + self.assertEqual("new", res["track"]["status"]) + + # While pending moderation, visitors still get track: None! + self.assertIsNone(self.registry.music.lookup(unique_id="alice")["track"]) + + # Moderator bot picks it up via sendAudio and owner clicks Accept (when private modbot is present). + if modbot is not None: + tg = FakeTelegram() + bot = modbot.Moderator(self.registry, tg, owner_id=12345) + bot.sweep() + send_audio = [c for c in tg.calls if c[0] == "sendAudio"] + self.assertEqual(1, len(send_audio)) + self.assertIn("Midnight", send_audio[0][1]["title"]) + bot.handle({"callback_query": {"id": "cb1", "from": {"id": 12345}, "data": "ma:" + tid, "message": {"message_id": 77}}}) + else: + self.registry.music.decide(tid, "approved", "owner") + + # Approved + active: lookup by handle (mixed case / @) and by uid both return track. + got = self.registry.music.lookup(unique_id="@ALICE")["track"] + self.assertIsNotNone(got) + self.assertEqual("Midnight", got["title"]) + self.assertEqual("DJ Alice", got["artist"]) + self.assertEqual(18, got["duration"]) + self.assertEqual("music/" + tid + ".mp3", got["path"]) + self.assertEqual(got["id"], self.registry.music.lookup(uid=UID)["track"]["id"]) + self.assertIsNotNone(self.registry.music.bytes(tid, approved_only=True)) + + # Owner clears music -> lookup returns None again, can re-select later. + self.registry.music.clear(UID, INST) + self.assertIsNone(self.registry.music.lookup(unique_id="alice")["track"]) + self.registry.music.select(UID, INST, tid) + self.assertEqual(tid, self.registry.music.lookup(unique_id="alice")["track"]["id"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sound.py b/tests/test_sound.py new file mode 100644 index 0000000..d033c86 --- /dev/null +++ b/tests/test_sound.py @@ -0,0 +1,52 @@ +import unittest +from pathlib import Path + +from lihont import sound_patch + +ROOT = Path(__file__).resolve().parents[1] +SETTINGS = ROOT / "src" / "lihont" / "two" / "settings" / "LihonTSettingsActivity.java" +SOUND = ROOT / "src" / "lihont" / "two" / "sound" / "Sound.java" + +SAMPLE = """.class public final Lcom/ss/android/ugc/aweme/feed/model/AwemeStatus$VideoMuteInfo; +.super Ljava/lang/Object; +.source "AwemeStatus.java" + +.method public final isMute()Z + .registers 2 + + .prologue + .line 0 + iget-boolean v0, p0, Lcom/ss/android/ugc/aweme/feed/model/AwemeStatus$VideoMuteInfo;->isMute:Z + + .line 1 + return v0 +.end method +""" + + +class SoundPatchTest(unittest.TestCase): + def test_the_getter_goes_through_the_switch(self): + patched = sound_patch.rewrite(SAMPLE) + self.assertIn(sound_patch.MARKER, patched) + self.assertIn("Llihont/two/sound/Sound;->unmute(Z)Z", patched) + self.assertIn("->isMute:Z", patched) + self.assertIn("return v0", patched) + + def test_it_refuses_to_patch_twice(self): + patched = sound_patch.rewrite(SAMPLE) + with self.assertRaises(ValueError): + sound_patch.rewrite(patched) + + def test_the_settings_screen_has_the_switch(self): + text = SETTINGS.read_text(encoding="utf-8") + self.assertIn("soundRow()", text) + self.assertIn("Sound.setEnabled(this, value)", text) + + def test_the_switch_defaults_to_on(self): + text = SOUND.read_text(encoding="utf-8") + self.assertIn("getBoolean(KEY, true)", text) + self.assertIn("return enabled() ? false : original", text) + + +if __name__ == "__main__": + unittest.main()
Направление