LihonT 3 Luna pre-alpha: the streak pet becomes an animal
A pair of people can have a kitten, a puppy or a lion cub in place of TikTok's streak creature: it grows with the days of the streak (cub, teen, adult, elder), goes grey while the streak is about to burn out, can be dragged in the chat and is also shown on the big streak screen. An animal is given by a link (lihont.space/pet) that the friend accepts. The drawings are made by scripts/make_pet_designs.py and served as strips of frames. Also here: the promo video scripts (make_pet_video.py on top of make_store_video.py), a retry pause for strips that failed to load, stricter checks in the answer to a gift. Work in progress: the gift service is not switched on for everyone yet and there is no public build with the animals. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@@ -23,7 +23,7 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import List, Sequence
|
||||
|
||||
from . import manifest as manifest_module
|
||||
from . import dead_slots, manifest as manifest_module
|
||||
from .apkzip import Apk, STORED
|
||||
from .arsc import Arsc, TYPE_STRING
|
||||
from .axml import Axml
|
||||
@@ -121,14 +121,28 @@ def load_catalog(directory: Path) -> List[Icon]:
|
||||
return icons
|
||||
|
||||
|
||||
def slot_path(old_path: str, index: int) -> str:
|
||||
"""A path in the same folder, with a file name of exactly the same length."""
|
||||
def slot_path(old_path: str, index: int, taken=None) -> str:
|
||||
"""A path in the same folder, with a file name of exactly the same length. `taken(path)` says whether a file is already there:
|
||||
then the next free name of that length is used (a two-letter name may collide in a build with short names)."""
|
||||
folder, _, name = old_path.rpartition("/")
|
||||
stem, dot, extension = name.rpartition(".")
|
||||
fresh = ("li%x" % index).ljust(len(stem), "x")
|
||||
# "li0" and so on; a two-letter name (TikTok 47.7.2 has such files) gets "l0"
|
||||
fresh = ("l%x" % index if len(stem) == 2 else "li%x" % index).ljust(len(stem), "x")
|
||||
if len(fresh) != len(stem):
|
||||
raise IconError("slot path %r leaves no room for a new name" % old_path)
|
||||
return "%s/%s%s%s" % (folder, fresh, dot, extension)
|
||||
path = "%s/%s%s%s" % (folder, fresh, dot, extension)
|
||||
if taken is not None and taken(path):
|
||||
letters = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
for number in range(len(letters) ** len(stem)):
|
||||
digits = []
|
||||
for _ in stem:
|
||||
number, rest = divmod(number, len(letters))
|
||||
digits.append(letters[rest])
|
||||
candidate = "%s/%s%s%s" % (folder, "".join(reversed(digits)), dot, extension)
|
||||
if not taken(candidate):
|
||||
return candidate
|
||||
raise IconError("no free file name in %s" % folder)
|
||||
return path
|
||||
|
||||
|
||||
def alias_name(slug: str) -> str:
|
||||
@@ -166,7 +180,10 @@ def apply(apk: Apk, xml: Axml, icons: Sequence[Icon]) -> dict:
|
||||
version = manifest_module.version_name(xml)
|
||||
slots = SLOTS_BY_VERSION.get(version)
|
||||
if slots is None:
|
||||
raise IconError("no dead slots are pinned for TikTok %s (run scripts/port_dead_slots.py)" % version)
|
||||
# a version nobody pinned: the dead slots are found in the build itself, nothing is written by hand
|
||||
slots = dead_slots.find(apk, arsc, len(icons), min_stem=2)
|
||||
if len(slots) < len(icons):
|
||||
raise IconError("TikTok %s has only %d dead drawables, %d are needed" % (version, len(slots), len(icons)))
|
||||
report = {
|
||||
"icons": len(icons), "original_entry": entry, "target": target,
|
||||
"stock": {"alias": alias_name(STOCK_SLUG), "resource": "0x%08x" % stock_icon},
|
||||
@@ -175,7 +192,7 @@ def apply(apk: Apk, xml: Axml, icons: Sequence[Icon]) -> dict:
|
||||
for index, icon in enumerate(icons):
|
||||
res_id, old_path = slots[index]
|
||||
pool_index = verify_slot(arsc, res_id, old_path)
|
||||
new_path = slot_path(old_path, index)
|
||||
new_path = slot_path(old_path, index, apk.has)
|
||||
if apk.has(new_path):
|
||||
raise IconError("%s already exists in the apk" % new_path)
|
||||
arsc.replace_string(pool_index, new_path)
|
||||
|
||||
@@ -57,6 +57,7 @@ ATTR_IDS = {
|
||||
"value": 0x01010024,
|
||||
"scheme": 0x01010027,
|
||||
"host": 0x01010028,
|
||||
"pathPrefix": 0x0101002B,
|
||||
"layout_width": 0x010100F4,
|
||||
"layout_height": 0x010100F5,
|
||||
"id": 0x010100D0,
|
||||
|
||||
46
lihont/dead_slots.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""Dead drawables of a TikTok build: pictures that nothing reads, whose file the mod can reuse as a launcher icon.
|
||||
|
||||
A drawable is dead when its id (four bytes, little endian) occurs in no dex, no binary XML and nowhere else in the resource table, and its
|
||||
single value is a path to a picture file. Finding them from the build itself means a new TikTok version needs no table of slots written by
|
||||
hand: lihont/app_icons.py keeps its pinned tables only as a checked shortcut for versions that were looked at before.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import List, Sequence, Tuple
|
||||
|
||||
from .arsc import Arsc, TYPE_STRING
|
||||
|
||||
PICTURES = (".png", ".webp")
|
||||
|
||||
|
||||
def find(apk, arsc: Arsc, need: int, kind: str = "drawable", exts: Sequence[str] = PICTURES, min_stem: int = 0) -> List[Tuple[int, str]]:
|
||||
"""The first `need` dead slots of the build as (resource id, file path), in the order of their ids.
|
||||
|
||||
`min_stem` keeps only files whose name (without extension) is that long: a renamed slot needs room for its new name.
|
||||
`apk` is a lihont.apkzip.Apk (or anything with names() and read()). Fewer than `need` come back when the build has fewer.
|
||||
"""
|
||||
package = arsc.package(0x7F)
|
||||
type_id = next(i + 1 for i in range(len(package.type_names)) if package.type_names.get(i) == kind)
|
||||
candidates = {}
|
||||
for entry in range(0, 0x10000):
|
||||
res_id = 0x7F000000 | (type_id << 16) | entry
|
||||
values = arsc.values(res_id)
|
||||
if len(values) != 1 or values[0].kind != TYPE_STRING:
|
||||
continue
|
||||
path = arsc.file_path(values[0])
|
||||
if path and path.endswith(tuple(exts)):
|
||||
candidates[res_id] = path
|
||||
# every 4-byte little-endian id of this type that occurs anywhere a reference could be
|
||||
pattern = re.compile(rb"(?s)(?=(..)" + bytes([type_id]) + rb"\x7f)")
|
||||
referenced = set()
|
||||
for name in apk.names():
|
||||
if not (re.fullmatch(r"classes\d*\.dex", name) or name == "resources.arsc" or name == "AndroidManifest.xml"
|
||||
or (name.startswith("res/") and name.endswith(".xml"))):
|
||||
continue
|
||||
for match in pattern.finditer(apk.read(name)):
|
||||
referenced.add(0x7F000000 | (type_id << 16) | int.from_bytes(match.group(1), "little"))
|
||||
dead = [(i, p) for i, p in sorted(candidates.items())
|
||||
if i not in referenced and apk.has(p) and len(p.rpartition("/")[2].rpartition(".")[0]) >= min_stem]
|
||||
return dead[:need]
|
||||
@@ -68,7 +68,7 @@ def rewrite_story_view(text: str) -> str:
|
||||
if "Ghost;" in method:
|
||||
raise ValueError("Ghost hook already present in LX/0RDS;->LIZJ")
|
||||
# The shape that identifies it: it posts the view through StoryApi.reportStoryViewed and nothing else of ours.
|
||||
if "StoryApi;->reportStoryViewed(" not in method or ".registers 8" not in method:
|
||||
if "StoryApi;->reportStoryViewed(" not in method or not re.search(r"\.registers \d+", method):
|
||||
raise ValueError("LX/0RDS;->LIZJ has an unexpected shape")
|
||||
first = _FIRST.search(method)
|
||||
if first is None:
|
||||
|
||||
@@ -21,6 +21,9 @@ from .axml import (
|
||||
)
|
||||
|
||||
MAIN_ACTION = "android.intent.action.MAIN"
|
||||
VIEW_ACTION = "android.intent.action.VIEW"
|
||||
DEFAULT_CATEGORY = "android.intent.category.DEFAULT"
|
||||
BROWSABLE_CATEGORY = "android.intent.category.BROWSABLE"
|
||||
LAUNCHER_CATEGORY = "android.intent.category.LAUNCHER"
|
||||
# meta-data on an icon alias: what the picker calls it (read back by the runtime)
|
||||
ICON_TITLE_KEY = "lihont.title"
|
||||
@@ -347,9 +350,11 @@ def add_icon_alias(axml: Axml, name: str, target: str, icon: int,
|
||||
|
||||
def add_activity(axml: Axml, class_name: str, label: str, theme: int,
|
||||
affinity: str = None, launcher: bool = False,
|
||||
exported: bool = False) -> None:
|
||||
exported: bool = False, links: tuple = ()) -> None:
|
||||
"""Declare an activity, last child of ``<application>``.
|
||||
|
||||
`links` are web links the activity opens, as (scheme, host, path prefix): one intent filter with a data element for each.
|
||||
|
||||
With `launcher` it also gets an entry on the home screen -- and then it
|
||||
needs a task affinity of its own, because without one it shares the app's,
|
||||
and tapping its icon while TikTok is running does what tapping a launcher
|
||||
@@ -372,6 +377,27 @@ def add_activity(axml: Axml, class_name: str, label: str, theme: int,
|
||||
axml.set_attr_string(activity, "name", class_name)
|
||||
axml.set_attr_bool(activity, "exported", exported)
|
||||
|
||||
if links and not launcher:
|
||||
subtree = [activity]
|
||||
for scheme, host, prefix in links:
|
||||
intent_filter = axml.make_element("intent-filter")
|
||||
parts = [intent_filter]
|
||||
for kind, name in (("action", VIEW_ACTION), ("category", DEFAULT_CATEGORY), ("category", BROWSABLE_CATEGORY)):
|
||||
element = axml.make_element(kind)
|
||||
axml.set_attr_string(element, "name", name)
|
||||
parts += [element, axml.close_element(element)]
|
||||
data = axml.make_element("data")
|
||||
axml.set_attr_string(data, "scheme", scheme)
|
||||
if host:
|
||||
axml.set_attr_string(data, "host", host)
|
||||
if prefix:
|
||||
axml.set_attr_string(data, "pathPrefix", prefix)
|
||||
parts += [data, axml.close_element(data), axml.close_element(intent_filter)]
|
||||
subtree += parts
|
||||
subtree.append(axml.close_element(activity))
|
||||
axml.insert_into(application(axml), subtree)
|
||||
return
|
||||
|
||||
if not launcher:
|
||||
axml.insert_into(application(axml), [activity, axml.close_element(activity)])
|
||||
return
|
||||
|
||||
@@ -76,7 +76,7 @@ GATE = "Llihont/two/media/DownloadMenu;->gate(Ljava/lang/Object;Landroid/content
|
||||
GATE_PHOTO = ("Llihont/two/media/DownloadMenu;->gatePhoto("
|
||||
"Ljava/lang/Object;Landroid/content/Context;Ljava/lang/Object;)Z")
|
||||
|
||||
_SAVE_ACTION = re.compile(r"^\.method public final LJ\(Landroid/content/Context;LX/0qvX;\)V\n( \.registers \d+\n)", re.M)
|
||||
_SAVE_ACTION = re.compile(r"^\.method public final \w+\(Landroid/content/Context;LX/0qvX;\)V\n( \.registers \d+\n)", re.M)
|
||||
_PHOTO_CLICK = re.compile(
|
||||
r"^\.method public final LJIILIIL\(Landroid/content/Context;"
|
||||
r"Lcom/ss/android/ugc/aweme/share/base/model/BaseSharePackage;LX/0qrm;Landroid/view/View;LX/01h3;\)"
|
||||
@@ -121,7 +121,7 @@ def _gate(text: str, pattern, code: str, what: str) -> str:
|
||||
|
||||
def rewrite_save(text: str) -> str:
|
||||
"""Put the download menu in front of a Save action (LJ(Context, X.0qvX)): the gate may take it over."""
|
||||
return _gate(text, _SAVE_ACTION, SAVE_GATE, "Save action LJ(Context, X.0qvX)")
|
||||
return _gate(text, _SAVE_ACTION, SAVE_GATE, "Save action (Context, X.0qvX)V")
|
||||
|
||||
|
||||
def rewrite_photo(text: str) -> str:
|
||||
|
||||
813
lihont/portmaps/47.7.2.json
Normal file
@@ -0,0 +1,813 @@
|
||||
{
|
||||
"from": "47.1.3",
|
||||
"to": "47.7.2",
|
||||
"classes": {
|
||||
"LX/01h3;": "LX/03va;",
|
||||
"LX/0KwU;": "LX/01Bv;",
|
||||
"LX/0Kzn;": "LX/01H3;",
|
||||
"LX/0L5k;": "LX/00h4;",
|
||||
"LX/0LAr;": "LX/0lhl;",
|
||||
"LX/0LB8;": "LX/0lvP;",
|
||||
"LX/0LDf;": "LX/0lq3;",
|
||||
"LX/0LDm;": "LX/0lqA;",
|
||||
"LX/0LGU;": "LX/06n6;",
|
||||
"LX/0LQf;": "LX/02DC;",
|
||||
"LX/0LRh;": "LX/00Ow;",
|
||||
"LX/0LYA;": "LX/0099;",
|
||||
"LX/0Lis;": "LX/0mFx;",
|
||||
"LX/0Lk9;": "LX/0m9u;",
|
||||
"LX/0M1d;": "LX/009t;",
|
||||
"LX/0M8m;": "LX/01Hb;",
|
||||
"LX/0MIo;": "LX/0mAA;",
|
||||
"LX/0RDS;": "LX/09UI;",
|
||||
"LX/0Uiz;": "LX/0CaA;",
|
||||
"LX/0qrm;": "LX/0Hxr;",
|
||||
"LX/0qv6;": "LX/178d;",
|
||||
"LX/0qvH;": "LX/178W;",
|
||||
"LX/0qvL;": "LX/0IMP;",
|
||||
"LX/0qvX;": "LX/1795;",
|
||||
"LX/0qvu;": "LX/178l;",
|
||||
"LX/0qwE;": "LX/06Bh;",
|
||||
"LX/13pM;": "LX/0D61;",
|
||||
"LX/1Azi;": "LX/08IY;",
|
||||
"LX/1Bem;": "LX/09yL;",
|
||||
"LX/1DHB;": "LX/03NI;",
|
||||
"LX/1DHU;": "LX/06V7;",
|
||||
"LX/1DuR;": "LX/0mQf;",
|
||||
"LX/1DvK;": "LX/0mQd;",
|
||||
"LX/1Dvf;": "LX/0mQl;",
|
||||
"LX/1MiX;": "LX/06jx;",
|
||||
"LX/13uW;": "LX/0CfW;",
|
||||
"LX/13xe;": "LX/0Cdu;",
|
||||
"LX/13zu;": "LX/0Csl;",
|
||||
"LX/13oK;": "LX/0Cua;",
|
||||
"LX/13pS;": "LX/0gpa;",
|
||||
"LX/0L9u;": "LX/01LJ;",
|
||||
"LX/0LQx;": "LX/01Kx;",
|
||||
"LX/1Baf;": "LX/0CJ5;",
|
||||
"LX/0Bl3;": "LX/12lH;",
|
||||
"LX/0LLI;": "LX/009B;",
|
||||
"LX/0MN8;": "LX/01XF;",
|
||||
"LX/0MNM;": "LX/01XE;",
|
||||
"LX/0MNz;": "LX/008h;",
|
||||
"LX/0MNJ;": "LX/01XD;",
|
||||
"LX/0MOB;": "LX/0236;",
|
||||
"LX/0LYD;": "LX/010L;",
|
||||
"LX/0MOb;": "LX/0096;",
|
||||
"LX/0MNv;": "LX/01X9;",
|
||||
"LX/0LDi;": "LX/0lq6;",
|
||||
"LX/01sS;": "LX/01XT;",
|
||||
"LX/0LDj;": "LX/0lq7;",
|
||||
"LX/1Dw4;": "LX/01HW;",
|
||||
"LX/0Lqw;": "LX/01RH;",
|
||||
"LX/0LDk;": "LX/0lq8;",
|
||||
"LX/0LDv;": "LX/0lqG;",
|
||||
"LX/0LFj;": "LX/06mj;",
|
||||
"LX/0LAT;": "LX/06mT;",
|
||||
"LX/0LDN;": "LX/06n2;",
|
||||
"LX/0LAb;": "LX/06lM;",
|
||||
"LX/0FL9;": "LX/0axV;",
|
||||
"LX/0yw4;": "LX/03NG;",
|
||||
"LX/14wU;": "LX/1BCc;",
|
||||
"LX/1552;": "LX/0ao5;",
|
||||
"LX/0FKH;": "LX/0ao5;",
|
||||
"LX/14g9;": "LX/1BCR;",
|
||||
"LX/1EjA;": "LX/02I2;",
|
||||
"LX/1A6P;": "LX/0edY;",
|
||||
"LX/0wWx;": "LX/1PYp;",
|
||||
"LX/1BCf;": "LX/02cn;",
|
||||
"LX/1B41;": "LX/01Vu;",
|
||||
"LX/11LV;": "LX/01Oi;",
|
||||
"LX/11OD;": "LX/01OT;",
|
||||
"LX/11Li;": "LX/01Ou;",
|
||||
"LX/0fU0;": "LX/0MRK;",
|
||||
"LX/15or;": "LX/0MDR;",
|
||||
"LX/0fTx;": "LX/0MRL;",
|
||||
"LX/0H5D;": "LX/19xh;",
|
||||
"LX/15nZ;": "LX/19xN;",
|
||||
"LX/0fTy;": "LX/0aNj;",
|
||||
"LX/0Y23;": "LX/032w;",
|
||||
"LX/1aei;": "LX/1nx4;",
|
||||
"LX/1CCz;": "LX/1RMt;",
|
||||
"LX/1CvC;": "LX/04VK;",
|
||||
"LX/18Wg;": "LX/1H96;",
|
||||
"LX/0HtY;": "LX/1BCO;",
|
||||
"LX/0Hsy;": "LX/1BCM;",
|
||||
"LX/0ugf;": "LX/032S;",
|
||||
"LX/0zyI;": "LX/1D2s;",
|
||||
"LX/17f5;": "LX/08em;",
|
||||
"LX/0WBa;": "LX/1Fum;",
|
||||
"LX/17Yf;": "LX/1Grx;",
|
||||
"LX/17YC;": "LX/1GrP;",
|
||||
"LX/17Yy;": "LX/1Grf;",
|
||||
"LX/0dLQ;": "LX/1GrT;",
|
||||
"LX/1R5f;": "LX/1K6f;",
|
||||
"LX/1Qdi;": "LX/1dyq;",
|
||||
"LX/0ra6;": "LX/1d1P;",
|
||||
"LX/1Cd0;": "LX/0Gmd;",
|
||||
"LX/1YOU;": "LX/0Gmd;",
|
||||
"LX/13Zf;": "LX/1lQ2;",
|
||||
"LX/1TGx;": "LX/128H;",
|
||||
"LX/1Cfj;": "LX/0I9x;",
|
||||
"LX/0FLG;": "LX/0I9x;",
|
||||
"LX/1Ccy;": "LX/1fyQ;",
|
||||
"LX/0uge;": "LX/0oxw;",
|
||||
"LX/0rZU;": "LX/1OqO;",
|
||||
"LX/0HrT;": "LX/0ZDi;",
|
||||
"LX/0fUX;": "LX/0ZDi;",
|
||||
"LX/0FL8;": "LX/0ZE5;",
|
||||
"LX/0H4b;": "LX/0acx;",
|
||||
"LX/1CE4;": "LX/032T;",
|
||||
"LX/0qvZ;": "LX/1796;",
|
||||
"LX/0CWi;": "LX/0mQZ;",
|
||||
"LX/1Dfo;": "LX/1W1g;",
|
||||
"LX/17JA;": "LX/1PRA;",
|
||||
"LX/1Dfq;": "LX/1W1W;",
|
||||
"LX/1Dgp;": "LX/1W1c;",
|
||||
"LX/0poF;": "LX/1DbK;",
|
||||
"LX/17DO;": "LX/0mQk;",
|
||||
"LX/1Dfp;": "LX/1W1f;",
|
||||
"LX/1Dgo;": "LX/1W1d;",
|
||||
"LX/1Kga;": "LX/0A5o;",
|
||||
"LX/0Qro;": "LX/05fz;",
|
||||
"LX/172G;": "LX/035o;",
|
||||
"LX/0Sl3;": "LX/08BR;",
|
||||
"LX/0RDW;": "LX/0vDw;",
|
||||
"LX/0r14;": "LX/0Hy5;",
|
||||
"LX/0LBx;": "LX/0lpy;",
|
||||
"LX/0LBu;": "LX/0lpu;",
|
||||
"LX/0LwC;": "LX/01R4;",
|
||||
"LX/0MIq;": "LX/01KT;",
|
||||
"LX/0L2A;": "LX/00qi;",
|
||||
"LX/0LR4;": "LX/02EH;",
|
||||
"LX/0LQM;": "LX/01H1;",
|
||||
"LX/0LQl;": "LX/01LM;",
|
||||
"LX/0CX2;": "LX/0mA1;",
|
||||
"LX/0kmX;": "LX/03Om;",
|
||||
"LX/1Dit;": "LX/1SEc;",
|
||||
"LX/0CWm;": "LX/0mQm;",
|
||||
"LX/1Azk;": "LX/08Vf;",
|
||||
"LX/1AJh;": "LX/08Ik;",
|
||||
"LX/0DAh;": "LX/0IAm;",
|
||||
"LX/0qqp;": "LX/0IN9;",
|
||||
"LX/0qeC;": "LX/171r;",
|
||||
"LX/0Syf;": "LX/05fG;",
|
||||
"LX/0DMR;": "LX/0mFw;",
|
||||
"LX/0M0Y;": "LX/01o5;",
|
||||
"LX/13pt;": "LX/0D8L;",
|
||||
"LX/13m4;": "LX/0Cm9;",
|
||||
"LX/13q1;": "LX/0D85;",
|
||||
"LX/13ps;": "LX/0D8Y;",
|
||||
"LX/17f4;": "LX/08en;",
|
||||
"LX/0Why;": "LX/02p1;",
|
||||
"LX/17fJ;": "LX/040J;",
|
||||
"LX/17fL;": "LX/0I7M;",
|
||||
"LX/17Zq;": "LX/0HUD;",
|
||||
"LX/17dg;": "LX/09FZ;",
|
||||
"LX/17dl;": "LX/08eu;",
|
||||
"LX/0WT5;": "LX/1G7G;",
|
||||
"LX/0WT1;": "LX/1G7H;",
|
||||
"LX/0kRg;": "LX/1H9a;",
|
||||
"LX/0Loy;": "LX/01K5;",
|
||||
"LX/17YB;": "LX/1GrO;",
|
||||
"LX/17YD;": "LX/1GsF;",
|
||||
"LX/17YE;": "LX/1GsG;",
|
||||
"LX/0dzr;": "LX/1GrS;",
|
||||
"LX/17Yx;": "LX/1Grk;",
|
||||
"LX/13zr;": "LX/0CdN;",
|
||||
"LX/01TD;": "LX/035f;",
|
||||
"LX/13pa;": "LX/0CdR;",
|
||||
"LX/13vv;": "LX/0CbP;",
|
||||
"LX/14AY;": "LX/0D4b;",
|
||||
"LX/13xb;": "LX/0CdY;",
|
||||
"LX/13wf;": "LX/0Cdy;",
|
||||
"LX/13uN;": "LX/0D4P;",
|
||||
"LX/1428;": "LX/0CdT;",
|
||||
"LX/1B4c;": "LX/005P;",
|
||||
"LX/0M8J;": "LX/02BE;",
|
||||
"LX/0MNI;": "LX/009W;",
|
||||
"LX/0MNR;": "LX/01X7;",
|
||||
"LX/0MO9;": "LX/01gx;",
|
||||
"LX/0MLr;": "LX/01X0;",
|
||||
"LX/0R1i;": "LX/09eo;",
|
||||
"LX/0MN7;": "LX/023H;",
|
||||
"LX/0MNA;": "LX/008W;",
|
||||
"LX/11Mu;": "LX/01OR;",
|
||||
"LX/13pT;": "LX/0gpO;",
|
||||
"LX/13pV;": "LX/0DF5;",
|
||||
"LX/0r8d;": "LX/0Hzh;",
|
||||
"LX/0MO6;": "LX/009j;",
|
||||
"LX/0MOd;": "LX/009J;",
|
||||
"LX/1J86;": "LX/02So;",
|
||||
"LX/1J87;": "LX/02h4;",
|
||||
"LX/180M;": "LX/00HD;",
|
||||
"LX/0sVI;": "LX/00Db;",
|
||||
"LX/0Lr6;": "LX/00VL;",
|
||||
"LX/0M0P;": "LX/00Vo;",
|
||||
"LX/0MEu;": "LX/00Va;",
|
||||
"LX/0Lu4;": "LX/00lp;",
|
||||
"LX/0Lu0;": "LX/01Ku;",
|
||||
"LX/0LwD;": "LX/021S;",
|
||||
"LX/0LwH;": "LX/021Z;",
|
||||
"LX/0LwN;": "LX/01RK;",
|
||||
"LX/0LzF;": "LX/00lk;",
|
||||
"LX/0MNu;": "LX/0097;",
|
||||
"LX/0LSJ;": "LX/01HC;",
|
||||
"LX/1CDH;": "LX/1BCe;",
|
||||
"LX/1Bxp;": "LX/1R9a;",
|
||||
"LX/1CCt;": "LX/1RMv;",
|
||||
"LX/1CD6;": "LX/1BCf;",
|
||||
"LX/1CD0;": "LX/1RMu;",
|
||||
"LX/0a5O;": "LX/029H;",
|
||||
"LX/0LLm;": "LX/00yA;",
|
||||
"LX/0bCj;": "LX/0MDY;",
|
||||
"LX/0MNE;": "LX/008f;",
|
||||
"LX/0MNi;": "LX/009P;",
|
||||
"LX/0MNS;": "LX/009N;",
|
||||
"LX/1Agh;": "LX/04Lj;",
|
||||
"LX/1Aey;": "LX/04Ml;",
|
||||
"LX/0Aam;": "LX/02xX;",
|
||||
"LX/0LUC;": "LX/01L1;",
|
||||
"LX/0Low;": "LX/01Qw;",
|
||||
"LX/0LU8;": "LX/01KI;",
|
||||
"LX/0Loz;": "LX/021J;",
|
||||
"LX/1BCe;": "LX/004m;",
|
||||
"LX/1BAW;": "LX/004d;",
|
||||
"LX/1BAJ;": "LX/004c;",
|
||||
"LX/0Vsn;": "LX/00De;",
|
||||
"LX/0WbC;": "LX/00wN;",
|
||||
"LX/1B6a;": "LX/01Gp;",
|
||||
"LX/1B6g;": "LX/01Go;",
|
||||
"LX/1B5P;": "LX/01W3;",
|
||||
"LX/0WPj;": "LX/05UA;",
|
||||
"LX/0MIk;": "LX/01iQ;",
|
||||
"LX/0MOD;": "LX/008b;",
|
||||
"LX/17Vq;": "LX/1G2N;",
|
||||
"LX/0MBa;": "LX/02B7;",
|
||||
"LX/0MMs;": "LX/009a;",
|
||||
"LX/13mT;": "LX/0DNW;",
|
||||
"LX/12rB;": "LX/0h4w;",
|
||||
"LX/1BAG;": "LX/01VF;",
|
||||
"LX/1Aiu;": "LX/05mo;",
|
||||
"LX/17YH;": "LX/1Gs1;",
|
||||
"LX/17Yi;": "LX/1Gs2;",
|
||||
"LX/1BAU;": "LX/01VD;",
|
||||
"LX/0WbD;": "LX/00wO;",
|
||||
"LX/01rr;": "LX/02pZ;",
|
||||
"LX/0MHx;": "LX/00YK;",
|
||||
"LX/0MI9;": "LX/01gu;",
|
||||
"LX/0hSJ;": "LX/05ni;",
|
||||
"LX/0M1U;": "LX/00Vq;",
|
||||
"LX/0LwT;": "LX/00lS;",
|
||||
"LX/0LwO;": "LX/00lx;",
|
||||
"LX/0Lxc;": "LX/01ix;",
|
||||
"LX/0Lwf;": "LX/01RJ;",
|
||||
"LX/0LwV;": "LX/00lv;",
|
||||
"LX/1J84;": "LX/026f;",
|
||||
"LX/0MOv;": "LX/01it;",
|
||||
"LX/0Lox;": "LX/02aq;",
|
||||
"LX/0LXx;": "LX/01LP;",
|
||||
"LX/1J88;": "LX/00hb;",
|
||||
"LX/17oY;": "LX/00HC;",
|
||||
"LX/180P;": "LX/01Lj;",
|
||||
"LX/0vhC;": "LX/061e;",
|
||||
"LX/0vyE;": "LX/05nc;",
|
||||
"LX/0LwM;": "LX/01RE;",
|
||||
"LX/0LUI;": "LX/01HC;",
|
||||
"LX/0LQJ;": "LX/01KH;",
|
||||
"LX/0LwK;": "LX/00lz;",
|
||||
"LX/0Lwa;": "LX/00m3;",
|
||||
"LX/0MIR;": "LX/00qB;",
|
||||
"LX/13Al;": "LX/0h50;",
|
||||
"LX/1B5b;": "LX/01Vc;",
|
||||
"LX/13pb;": "LX/0Cbn;",
|
||||
"LX/0LRy;": "LX/01KM;",
|
||||
"LX/1Atg;": "LX/01W2;",
|
||||
"LX/1B68;": "LX/01D9;",
|
||||
"LX/1B6b;": "LX/005v;",
|
||||
"LX/1B6S;": "LX/005q;",
|
||||
"LX/13yI;": "LX/0Cbr;",
|
||||
"LX/13oX;": "LX/0CbW;",
|
||||
"LX/13za;": "LX/0Cc0;",
|
||||
"LX/13w8;": "LX/0CbT;",
|
||||
"LX/13qy;": "LX/0Cbh;",
|
||||
"LX/147H;": "LX/0CbR;",
|
||||
"LX/0MDS;": "LX/01yC;",
|
||||
"LX/0MCI;": "LX/009t;",
|
||||
"LX/0Le8;": "LX/00CE;",
|
||||
"LX/0MBf;": "LX/01sl;",
|
||||
"LX/0M5F;": "LX/000O;",
|
||||
"LX/0MBp;": "LX/010g;",
|
||||
"LX/0MBG;": "LX/011V;",
|
||||
"LX/0MI3;": "LX/00bU;",
|
||||
"LX/0MAp;": "LX/01sm;",
|
||||
"LX/0MIT;": "LX/008y;",
|
||||
"LX/0MOe;": "LX/008g;",
|
||||
"LX/0MOu;": "LX/026A;",
|
||||
"LX/0MI6;": "LX/01gv;",
|
||||
"LX/13w2;": "LX/0CeA;",
|
||||
"LX/13Jx;": "LX/0Csg;",
|
||||
"LX/17Ya;": "LX/1Gru;",
|
||||
"LX/0vyD;": "LX/05ns;",
|
||||
"LX/1BAP;": "LX/01VE;",
|
||||
"LX/0uo6;": "LX/01CI;",
|
||||
"LX/0lib;": "LX/0Cbj;",
|
||||
"LX/12k8;": "LX/05SI;",
|
||||
"LX/1B5a;": "LX/01Vf;",
|
||||
"LX/1B5l;": "LX/0058;",
|
||||
"LX/0MZn;": "LX/00lJ;",
|
||||
"LX/1J82;": "LX/02QU;",
|
||||
"LX/1J8I;": "LX/00lG;",
|
||||
"LX/1J8C;": "LX/00ha;",
|
||||
"LX/0MIS;": "LX/008e;",
|
||||
"LX/09wY;": "LX/06yf;",
|
||||
"LX/0LLJ;": "LX/00BN;",
|
||||
"LX/0MCo;": "LX/015g;",
|
||||
"LX/0MGG;": "LX/015l;",
|
||||
"LX/0GS9;": "LX/015o;",
|
||||
"LX/0Lsf;": "LX/00Ah;",
|
||||
"LX/0Lx3;": "LX/00Am;",
|
||||
"LX/0MGy;": "LX/01AB;",
|
||||
"LX/0MD7;": "LX/01xK;",
|
||||
"LX/0LnI;": "LX/00VZ;",
|
||||
"LX/0MCa;": "LX/00VW;",
|
||||
"LX/0LQD;": "LX/01Ks;",
|
||||
"LX/0L00;": "LX/00bX;",
|
||||
"LX/0MCs;": "LX/00d1;",
|
||||
"LX/0MBU;": "LX/00yq;",
|
||||
"LX/0Lal;": "LX/00vg;",
|
||||
"LX/0MFi;": "LX/00jC;",
|
||||
"LX/0MAh;": "LX/01LR;",
|
||||
"LX/0ME3;": "LX/01He;",
|
||||
"LX/0MBn;": "LX/010a;",
|
||||
"LX/0LNA;": "LX/00BL;",
|
||||
"LX/0Lrm;": "LX/00Yp;",
|
||||
"LX/0LsT;": "LX/00BZ;",
|
||||
"LX/0LdI;": "LX/00B3;",
|
||||
"LX/0TCv;": "LX/0h61;",
|
||||
"LX/1B5e;": "LX/022s;",
|
||||
"LX/1B6A;": "LX/0057;",
|
||||
"LX/1B5n;": "LX/01C3;",
|
||||
"LX/1B5s;": "LX/00qs;",
|
||||
"LX/0M2e;": "LX/01HN;",
|
||||
"LX/0MBA;": "LX/00vn;",
|
||||
"LX/0M5G;": "LX/000Q;",
|
||||
"LX/0uo7;": "LX/01CM;",
|
||||
"LX/0XoB;": "LX/060j;",
|
||||
"LX/0MBj;": "LX/01XZ;",
|
||||
"LX/0M5d;": "LX/00yp;",
|
||||
"LX/0Lan;": "LX/01pw;",
|
||||
"LX/0LqG;": "LX/01Kh;",
|
||||
"LX/0MGv;": "LX/01AF;",
|
||||
"LX/1B67;": "LX/01Ve;",
|
||||
"LX/0MHJ;": "LX/01gq;",
|
||||
"LX/0MFI;": "LX/01Et;",
|
||||
"LX/0MDA;": "LX/01xN;",
|
||||
"LX/0MCr;": "LX/01xJ;",
|
||||
"LX/0LaX;": "LX/02TJ;",
|
||||
"LX/0M3N;": "LX/00vq;",
|
||||
"LX/0BYm;": "LX/00Bl;",
|
||||
"LX/0XjN;": "LX/01g2;",
|
||||
"LX/0Lql;": "LX/00jm;",
|
||||
"LX/0MGF;": "LX/011N;",
|
||||
"LX/0LvV;": "LX/00Ab;",
|
||||
"LX/0Lrd;": "LX/00Yg;",
|
||||
"LX/0MF5;": "LX/02DE;",
|
||||
"LX/0M9V;": "LX/01gd;",
|
||||
"LX/0MDO;": "LX/01Hc;",
|
||||
"LX/0Lsj;": "LX/00Yk;",
|
||||
"LX/0MGz;": "LX/01AA;",
|
||||
"LX/0Lsk;": "LX/01Rq;",
|
||||
"LX/09Pr;": "LX/0HT2;",
|
||||
"LX/0kmK;": "LX/06cu;",
|
||||
"LX/0kmL;": "LX/0BwL;",
|
||||
"LX/0L1b;": "LX/06n3;",
|
||||
"LX/0NPd;": "LX/03zH;"
|
||||
},
|
||||
"doubtful": {
|
||||
"LX/09Pr;": [
|
||||
"LX/1PZt;",
|
||||
"LX/1PQh;"
|
||||
],
|
||||
"LX/0CWi;": [
|
||||
"LX/0mSg;",
|
||||
"LX/0mSa;"
|
||||
],
|
||||
"LX/0L1b;": [
|
||||
"LX/1ZSS;",
|
||||
"LX/1Xrk;"
|
||||
],
|
||||
"LX/0LQx;": [
|
||||
"LX/042o;",
|
||||
"LX/01Kx;"
|
||||
],
|
||||
"LX/0NPd;": [
|
||||
"LX/1VCf;",
|
||||
"LX/1VCc;"
|
||||
],
|
||||
"LX/0kmK;": [
|
||||
"LX/0g2J;",
|
||||
"LX/0BwL;"
|
||||
],
|
||||
"LX/0kmL;": [
|
||||
"LX/0g2J;",
|
||||
"LX/0BwL;"
|
||||
]
|
||||
},
|
||||
"dex": {
|
||||
"LX/0099;": "classes.dex",
|
||||
"LX/009t;": "classes.dex",
|
||||
"LX/00Ow;": "classes.dex",
|
||||
"LX/00h4;": "classes.dex",
|
||||
"LX/01Bv;": "classes.dex",
|
||||
"LX/01H3;": "classes.dex",
|
||||
"LX/01Hb;": "classes.dex",
|
||||
"LX/02DC;": "classes.dex",
|
||||
"LX/03NI;": "classes2.dex",
|
||||
"LX/03va;": "classes3.dex",
|
||||
"LX/06Bh;": "classes4.dex",
|
||||
"LX/06V7;": "classes4.dex",
|
||||
"LX/06jx;": "classes4.dex",
|
||||
"LX/06n6;": "classes4.dex",
|
||||
"LX/08IY;": "classes5.dex",
|
||||
"LX/09UI;": "classes6.dex",
|
||||
"LX/09yL;": "classes6.dex",
|
||||
"LX/0CaA;": "classes7.dex",
|
||||
"LX/0D61;": "classes8.dex",
|
||||
"LX/0Hxr;": "classes10.dex",
|
||||
"LX/0IMP;": "classes10.dex",
|
||||
"LX/0lhl;": "classes23.dex",
|
||||
"LX/0lq3;": "classes23.dex",
|
||||
"LX/0lqA;": "classes23.dex",
|
||||
"LX/0lvP;": "classes23.dex",
|
||||
"LX/0m9u;": "classes23.dex",
|
||||
"LX/0mAA;": "classes23.dex",
|
||||
"LX/0mFx;": "classes23.dex",
|
||||
"LX/0mQd;": "classes23.dex",
|
||||
"LX/0mQf;": "classes23.dex",
|
||||
"LX/0mQl;": "classes23.dex",
|
||||
"LX/178W;": "classes33.dex",
|
||||
"LX/178d;": "classes33.dex",
|
||||
"LX/178l;": "classes33.dex",
|
||||
"LX/1795;": "classes33.dex"
|
||||
},
|
||||
"inferred": {
|
||||
"LX/13uW;": "LX/0CfW;",
|
||||
"LX/13xe;": "LX/0Cdu;",
|
||||
"LX/13zu;": "LX/0Csl;",
|
||||
"LX/13oK;": "LX/0Cua;",
|
||||
"LX/13pS;": "LX/0gpa;",
|
||||
"LX/0L9u;": "LX/01LJ;",
|
||||
"LX/0LQx;": "LX/01Kx;",
|
||||
"LX/1Baf;": "LX/0CJ5;",
|
||||
"LX/0Bl3;": "LX/12lH;",
|
||||
"LX/0LLI;": "LX/009B;",
|
||||
"LX/0MN8;": "LX/01XF;",
|
||||
"LX/0MNM;": "LX/01XE;",
|
||||
"LX/0MNz;": "LX/008h;",
|
||||
"LX/0MNJ;": "LX/01XD;",
|
||||
"LX/0MOB;": "LX/0236;",
|
||||
"LX/0LYD;": "LX/010L;",
|
||||
"LX/0MOb;": "LX/0096;",
|
||||
"LX/0MNv;": "LX/01X9;",
|
||||
"LX/0LDi;": "LX/0lq6;",
|
||||
"LX/01sS;": "LX/01XT;",
|
||||
"LX/0LDj;": "LX/0lq7;",
|
||||
"LX/1Dw4;": "LX/01HW;",
|
||||
"LX/0Lqw;": "LX/01RH;",
|
||||
"LX/0LDk;": "LX/0lq8;",
|
||||
"LX/0LDv;": "LX/0lqG;",
|
||||
"LX/0LFj;": "LX/06mj;",
|
||||
"LX/0LAT;": "LX/06mT;",
|
||||
"LX/0LDN;": "LX/06n2;",
|
||||
"LX/0LAb;": "LX/06lM;",
|
||||
"LX/0FL9;": "LX/0axV;",
|
||||
"LX/0yw4;": "LX/03NG;",
|
||||
"LX/14wU;": "LX/1BCc;",
|
||||
"LX/1552;": "LX/0ao5;",
|
||||
"LX/0FKH;": "LX/0ao5;",
|
||||
"LX/14g9;": "LX/1BCR;",
|
||||
"LX/1EjA;": "LX/02I2;",
|
||||
"LX/1A6P;": "LX/0edY;",
|
||||
"LX/0wWx;": "LX/1PYp;",
|
||||
"LX/1BCf;": "LX/02cn;",
|
||||
"LX/1B41;": "LX/01Vu;",
|
||||
"LX/11LV;": "LX/01Oi;",
|
||||
"LX/11OD;": "LX/01OT;",
|
||||
"LX/11Li;": "LX/01Ou;",
|
||||
"LX/0fU0;": "LX/0MRK;",
|
||||
"LX/15or;": "LX/0MDR;",
|
||||
"LX/0fTx;": "LX/0MRL;",
|
||||
"LX/0H5D;": "LX/19xh;",
|
||||
"LX/15nZ;": "LX/19xN;",
|
||||
"LX/0fTy;": "LX/0aNj;",
|
||||
"LX/0Y23;": "LX/032w;",
|
||||
"LX/1aei;": "LX/1nx4;",
|
||||
"LX/1CCz;": "LX/1RMt;",
|
||||
"LX/1CvC;": "LX/04VK;",
|
||||
"LX/18Wg;": "LX/1H96;",
|
||||
"LX/0HtY;": "LX/1BCO;",
|
||||
"LX/0Hsy;": "LX/1BCM;",
|
||||
"LX/0ugf;": "LX/032S;",
|
||||
"LX/0zyI;": "LX/1D2s;",
|
||||
"LX/17f5;": "LX/08em;",
|
||||
"LX/0WBa;": "LX/1Fum;",
|
||||
"LX/17Yf;": "LX/1Grx;",
|
||||
"LX/17YC;": "LX/1GrP;",
|
||||
"LX/17Yy;": "LX/1Grf;",
|
||||
"LX/0dLQ;": "LX/1GrT;",
|
||||
"LX/1R5f;": "LX/1K6f;",
|
||||
"LX/1Qdi;": "LX/1dyq;",
|
||||
"LX/0ra6;": "LX/1d1P;",
|
||||
"LX/1Cd0;": "LX/0Gmd;",
|
||||
"LX/1YOU;": "LX/0Gmd;",
|
||||
"LX/13Zf;": "LX/1lQ2;",
|
||||
"LX/1TGx;": "LX/128H;",
|
||||
"LX/1Cfj;": "LX/0I9x;",
|
||||
"LX/0FLG;": "LX/0I9x;",
|
||||
"LX/1Ccy;": "LX/1fyQ;",
|
||||
"LX/0uge;": "LX/0oxw;",
|
||||
"LX/0rZU;": "LX/1OqO;",
|
||||
"LX/0HrT;": "LX/0ZDi;",
|
||||
"LX/0fUX;": "LX/0ZDi;",
|
||||
"LX/0FL8;": "LX/0ZE5;",
|
||||
"LX/0H4b;": "LX/0acx;",
|
||||
"LX/1CE4;": "LX/032T;",
|
||||
"LX/0qvZ;": "LX/1796;",
|
||||
"LX/0CWi;": "LX/0mQZ;",
|
||||
"LX/1Dfo;": "LX/1W1g;",
|
||||
"LX/17JA;": "LX/1PRA;",
|
||||
"LX/1Dfq;": "LX/1W1W;",
|
||||
"LX/1Dgp;": "LX/1W1c;",
|
||||
"LX/0poF;": "LX/1DbK;",
|
||||
"LX/17DO;": "LX/0mQk;",
|
||||
"LX/1Dfp;": "LX/1W1f;",
|
||||
"LX/1Dgo;": "LX/1W1d;",
|
||||
"LX/1Kga;": "LX/0A5o;",
|
||||
"LX/0Qro;": "LX/05fz;",
|
||||
"LX/172G;": "LX/035o;",
|
||||
"LX/0Sl3;": "LX/08BR;",
|
||||
"LX/0RDW;": "LX/0vDw;",
|
||||
"LX/0r14;": "LX/0Hy5;",
|
||||
"LX/0LBx;": "LX/0lpy;",
|
||||
"LX/0LBu;": "LX/0lpu;",
|
||||
"LX/0LwC;": "LX/01R4;",
|
||||
"LX/0MIq;": "LX/01KT;",
|
||||
"LX/0L2A;": "LX/00qi;",
|
||||
"LX/0LR4;": "LX/02EH;",
|
||||
"LX/0LQM;": "LX/01H1;",
|
||||
"LX/0LQl;": "LX/01LM;",
|
||||
"LX/0CX2;": "LX/0mA1;",
|
||||
"LX/0kmX;": "LX/03Om;",
|
||||
"LX/1Dit;": "LX/1SEc;",
|
||||
"LX/0CWm;": "LX/0mQm;",
|
||||
"LX/1Azk;": "LX/08Vf;",
|
||||
"LX/1AJh;": "LX/08Ik;",
|
||||
"LX/0DAh;": "LX/0IAm;",
|
||||
"LX/0qqp;": "LX/0IN9;",
|
||||
"LX/0qeC;": "LX/171r;",
|
||||
"LX/0Syf;": "LX/05fG;",
|
||||
"LX/0DMR;": "LX/0mFw;",
|
||||
"LX/0M0Y;": "LX/01o5;",
|
||||
"LX/13pt;": "LX/0D8L;",
|
||||
"LX/13m4;": "LX/0Cm9;",
|
||||
"LX/13q1;": "LX/0D85;",
|
||||
"LX/13ps;": "LX/0D8Y;",
|
||||
"LX/17f4;": "LX/08en;",
|
||||
"LX/0Why;": "LX/02p1;",
|
||||
"LX/17fJ;": "LX/040J;",
|
||||
"LX/17fL;": "LX/0I7M;",
|
||||
"LX/17Zq;": "LX/0HUD;",
|
||||
"LX/17dg;": "LX/09FZ;",
|
||||
"LX/17dl;": "LX/08eu;",
|
||||
"LX/0WT5;": "LX/1G7G;",
|
||||
"LX/0WT1;": "LX/1G7H;",
|
||||
"LX/0kRg;": "LX/1H9a;",
|
||||
"LX/0Loy;": "LX/01K5;",
|
||||
"LX/17YB;": "LX/1GrO;",
|
||||
"LX/17YD;": "LX/1GsF;",
|
||||
"LX/17YE;": "LX/1GsG;",
|
||||
"LX/0dzr;": "LX/1GrS;",
|
||||
"LX/17Yx;": "LX/1Grk;",
|
||||
"LX/13zr;": "LX/0CdN;",
|
||||
"LX/01TD;": "LX/035f;",
|
||||
"LX/13pa;": "LX/0CdR;",
|
||||
"LX/13vv;": "LX/0CbP;",
|
||||
"LX/14AY;": "LX/0D4b;",
|
||||
"LX/13xb;": "LX/0CdY;",
|
||||
"LX/13wf;": "LX/0Cdy;",
|
||||
"LX/13uN;": "LX/0D4P;",
|
||||
"LX/1428;": "LX/0CdT;",
|
||||
"LX/1B4c;": "LX/005P;",
|
||||
"LX/0M8J;": "LX/02BE;",
|
||||
"LX/0MNI;": "LX/009W;",
|
||||
"LX/0MNR;": "LX/01X7;",
|
||||
"LX/0MO9;": "LX/01gx;",
|
||||
"LX/0MLr;": "LX/01X0;",
|
||||
"LX/0R1i;": "LX/09eo;",
|
||||
"LX/0MN7;": "LX/023H;",
|
||||
"LX/0MNA;": "LX/008W;",
|
||||
"LX/11Mu;": "LX/01OR;",
|
||||
"LX/13pT;": "LX/0gpO;",
|
||||
"LX/13pV;": "LX/0DF5;",
|
||||
"LX/0r8d;": "LX/0Hzh;",
|
||||
"LX/0MO6;": "LX/009j;",
|
||||
"LX/0MOd;": "LX/009J;",
|
||||
"LX/1J86;": "LX/02So;",
|
||||
"LX/1J87;": "LX/02h4;",
|
||||
"LX/180M;": "LX/00HD;",
|
||||
"LX/0sVI;": "LX/00Db;",
|
||||
"LX/0Lr6;": "LX/00VL;",
|
||||
"LX/0M0P;": "LX/00Vo;",
|
||||
"LX/0MEu;": "LX/00Va;",
|
||||
"LX/0Lu4;": "LX/00lp;",
|
||||
"LX/0Lu0;": "LX/01Ku;",
|
||||
"LX/0LwD;": "LX/021S;",
|
||||
"LX/0LwH;": "LX/021Z;",
|
||||
"LX/0LwN;": "LX/01RK;",
|
||||
"LX/0LzF;": "LX/00lk;",
|
||||
"LX/0MNu;": "LX/0097;",
|
||||
"LX/0LSJ;": "LX/01HC;",
|
||||
"LX/1CDH;": "LX/1BCe;",
|
||||
"LX/1Bxp;": "LX/1R9a;",
|
||||
"LX/1CCt;": "LX/1RMv;",
|
||||
"LX/1CD6;": "LX/1BCf;",
|
||||
"LX/1CD0;": "LX/1RMu;",
|
||||
"LX/0a5O;": "LX/029H;",
|
||||
"LX/0LLm;": "LX/00yA;",
|
||||
"LX/0bCj;": "LX/0MDY;",
|
||||
"LX/0MNE;": "LX/008f;",
|
||||
"LX/0MNi;": "LX/009P;",
|
||||
"LX/0MNS;": "LX/009N;",
|
||||
"LX/1Agh;": "LX/04Lj;",
|
||||
"LX/1Aey;": "LX/04Ml;",
|
||||
"LX/0Aam;": "LX/02xX;",
|
||||
"LX/0LUC;": "LX/01L1;",
|
||||
"LX/0Low;": "LX/01Qw;",
|
||||
"LX/0LU8;": "LX/01KI;",
|
||||
"LX/0Loz;": "LX/021J;",
|
||||
"LX/1BCe;": "LX/004m;",
|
||||
"LX/1BAW;": "LX/004d;",
|
||||
"LX/1BAJ;": "LX/004c;",
|
||||
"LX/0Vsn;": "LX/00De;",
|
||||
"LX/0WbC;": "LX/00wN;",
|
||||
"LX/1B6a;": "LX/01Gp;",
|
||||
"LX/1B6g;": "LX/01Go;",
|
||||
"LX/1B5P;": "LX/01W3;",
|
||||
"LX/0WPj;": "LX/05UA;",
|
||||
"LX/0MIk;": "LX/01iQ;",
|
||||
"LX/0MOD;": "LX/008b;",
|
||||
"LX/17Vq;": "LX/1G2N;",
|
||||
"LX/0MBa;": "LX/02B7;",
|
||||
"LX/0MMs;": "LX/009a;",
|
||||
"LX/13mT;": "LX/0DNW;",
|
||||
"LX/12rB;": "LX/0h4w;",
|
||||
"LX/1BAG;": "LX/01VF;",
|
||||
"LX/1Aiu;": "LX/05mo;",
|
||||
"LX/17YH;": "LX/1Gs1;",
|
||||
"LX/17Yi;": "LX/1Gs2;",
|
||||
"LX/1BAU;": "LX/01VD;",
|
||||
"LX/0WbD;": "LX/00wO;",
|
||||
"LX/01rr;": "LX/02pZ;",
|
||||
"LX/0MHx;": "LX/00YK;",
|
||||
"LX/0MI9;": "LX/01gu;",
|
||||
"LX/0hSJ;": "LX/05ni;",
|
||||
"LX/0M1U;": "LX/00Vq;",
|
||||
"LX/0LwT;": "LX/00lS;",
|
||||
"LX/0LwO;": "LX/00lx;",
|
||||
"LX/0Lxc;": "LX/01ix;",
|
||||
"LX/0Lwf;": "LX/01RJ;",
|
||||
"LX/0LwV;": "LX/00lv;",
|
||||
"LX/1J84;": "LX/026f;",
|
||||
"LX/0MOv;": "LX/01it;",
|
||||
"LX/0Lox;": "LX/02aq;",
|
||||
"LX/0LXx;": "LX/01LP;",
|
||||
"LX/1J88;": "LX/00hb;",
|
||||
"LX/17oY;": "LX/00HC;",
|
||||
"LX/180P;": "LX/01Lj;",
|
||||
"LX/0vhC;": "LX/061e;",
|
||||
"LX/0vyE;": "LX/05nc;",
|
||||
"LX/0LwM;": "LX/01RE;",
|
||||
"LX/0LUI;": "LX/01HC;",
|
||||
"LX/0LQJ;": "LX/01KH;",
|
||||
"LX/0LwK;": "LX/00lz;",
|
||||
"LX/0Lwa;": "LX/00m3;",
|
||||
"LX/0MIR;": "LX/00qB;",
|
||||
"LX/13Al;": "LX/0h50;",
|
||||
"LX/1B5b;": "LX/01Vc;",
|
||||
"LX/13pb;": "LX/0Cbn;",
|
||||
"LX/0LRy;": "LX/01KM;",
|
||||
"LX/1Atg;": "LX/01W2;",
|
||||
"LX/1B68;": "LX/01D9;",
|
||||
"LX/1B6b;": "LX/005v;",
|
||||
"LX/1B6S;": "LX/005q;",
|
||||
"LX/13yI;": "LX/0Cbr;",
|
||||
"LX/13oX;": "LX/0CbW;",
|
||||
"LX/13za;": "LX/0Cc0;",
|
||||
"LX/13w8;": "LX/0CbT;",
|
||||
"LX/13qy;": "LX/0Cbh;",
|
||||
"LX/147H;": "LX/0CbR;",
|
||||
"LX/0MDS;": "LX/01yC;",
|
||||
"LX/0MCI;": "LX/009t;",
|
||||
"LX/0Le8;": "LX/00CE;",
|
||||
"LX/0MBf;": "LX/01sl;",
|
||||
"LX/0M5F;": "LX/000O;",
|
||||
"LX/0MBp;": "LX/010g;",
|
||||
"LX/0MBG;": "LX/011V;",
|
||||
"LX/0MI3;": "LX/00bU;",
|
||||
"LX/0MAp;": "LX/01sm;",
|
||||
"LX/0MIT;": "LX/008y;",
|
||||
"LX/0MOe;": "LX/008g;",
|
||||
"LX/0MOu;": "LX/026A;",
|
||||
"LX/0MI6;": "LX/01gv;",
|
||||
"LX/13w2;": "LX/0CeA;",
|
||||
"LX/13Jx;": "LX/0Csg;",
|
||||
"LX/17Ya;": "LX/1Gru;",
|
||||
"LX/0vyD;": "LX/05ns;",
|
||||
"LX/1BAP;": "LX/01VE;",
|
||||
"LX/0uo6;": "LX/01CI;",
|
||||
"LX/0lib;": "LX/0Cbj;",
|
||||
"LX/12k8;": "LX/05SI;",
|
||||
"LX/1B5a;": "LX/01Vf;",
|
||||
"LX/1B5l;": "LX/0058;",
|
||||
"LX/0MZn;": "LX/00lJ;",
|
||||
"LX/1J82;": "LX/02QU;",
|
||||
"LX/1J8I;": "LX/00lG;",
|
||||
"LX/1J8C;": "LX/00ha;",
|
||||
"LX/0MIS;": "LX/008e;",
|
||||
"LX/09wY;": "LX/06yf;",
|
||||
"LX/0LLJ;": "LX/00BN;",
|
||||
"LX/0MCo;": "LX/015g;",
|
||||
"LX/0MGG;": "LX/015l;",
|
||||
"LX/0GS9;": "LX/015o;",
|
||||
"LX/0Lsf;": "LX/00Ah;",
|
||||
"LX/0Lx3;": "LX/00Am;",
|
||||
"LX/0MGy;": "LX/01AB;",
|
||||
"LX/0MD7;": "LX/01xK;",
|
||||
"LX/0LnI;": "LX/00VZ;",
|
||||
"LX/0MCa;": "LX/00VW;",
|
||||
"LX/0LQD;": "LX/01Ks;",
|
||||
"LX/0L00;": "LX/00bX;",
|
||||
"LX/0MCs;": "LX/00d1;",
|
||||
"LX/0MBU;": "LX/00yq;",
|
||||
"LX/0Lal;": "LX/00vg;",
|
||||
"LX/0MFi;": "LX/00jC;",
|
||||
"LX/0MAh;": "LX/01LR;",
|
||||
"LX/0ME3;": "LX/01He;",
|
||||
"LX/0MBn;": "LX/010a;",
|
||||
"LX/0LNA;": "LX/00BL;",
|
||||
"LX/0Lrm;": "LX/00Yp;",
|
||||
"LX/0LsT;": "LX/00BZ;",
|
||||
"LX/0LdI;": "LX/00B3;",
|
||||
"LX/0TCv;": "LX/0h61;",
|
||||
"LX/1B5e;": "LX/022s;",
|
||||
"LX/1B6A;": "LX/0057;",
|
||||
"LX/1B5n;": "LX/01C3;",
|
||||
"LX/1B5s;": "LX/00qs;",
|
||||
"LX/0M2e;": "LX/01HN;",
|
||||
"LX/0MBA;": "LX/00vn;",
|
||||
"LX/0M5G;": "LX/000Q;",
|
||||
"LX/0uo7;": "LX/01CM;",
|
||||
"LX/0XoB;": "LX/060j;",
|
||||
"LX/0MBj;": "LX/01XZ;",
|
||||
"LX/0M5d;": "LX/00yp;",
|
||||
"LX/0Lan;": "LX/01pw;",
|
||||
"LX/0LqG;": "LX/01Kh;",
|
||||
"LX/0MGv;": "LX/01AF;",
|
||||
"LX/1B67;": "LX/01Ve;",
|
||||
"LX/0MHJ;": "LX/01gq;",
|
||||
"LX/0MFI;": "LX/01Et;",
|
||||
"LX/0MDA;": "LX/01xN;",
|
||||
"LX/0MCr;": "LX/01xJ;",
|
||||
"LX/0LaX;": "LX/02TJ;",
|
||||
"LX/0M3N;": "LX/00vq;",
|
||||
"LX/0BYm;": "LX/00Bl;",
|
||||
"LX/0XjN;": "LX/01g2;",
|
||||
"LX/0Lql;": "LX/00jm;",
|
||||
"LX/0MGF;": "LX/011N;",
|
||||
"LX/0LvV;": "LX/00Ab;",
|
||||
"LX/0Lrd;": "LX/00Yg;",
|
||||
"LX/0MF5;": "LX/02DE;",
|
||||
"LX/0M9V;": "LX/01gd;",
|
||||
"LX/0MDO;": "LX/01Hc;",
|
||||
"LX/0Lsj;": "LX/00Yk;",
|
||||
"LX/0MGz;": "LX/01AA;",
|
||||
"LX/0Lsk;": "LX/01Rq;"
|
||||
},
|
||||
"disagree": {},
|
||||
"ambiguous": {},
|
||||
"provisional": {},
|
||||
"manual": {
|
||||
"LX/09Pr;": "LX/0HT2;",
|
||||
"LX/0kmK;": "LX/06cu;",
|
||||
"LX/0kmL;": "LX/0BwL;",
|
||||
"LX/0qvX;": "LX/1795;",
|
||||
"LX/0L1b;": "LX/06n3;",
|
||||
"LX/0NPd;": "LX/03zH;"
|
||||
},
|
||||
"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()"
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ SEEKBAR_CLASS = "LX/1Azi;"
|
||||
HOOK = "Llihont/two/look/Seekbar;->type(I)I"
|
||||
|
||||
_METHOD = re.compile(r"^\.method public final setSeekBarShowType\(I\)V\n.*?^\.end method", re.M | re.S)
|
||||
_FIRST = re.compile(r"^ iget v0, p0, LX/1Azi;->LLJJJJJIL:I\n", re.M)
|
||||
_FIRST = re.compile(r"^ iget v0, p0, LX/1Azi;->\w+:I\n", re.M)
|
||||
|
||||
|
||||
def runtime_targets():
|
||||
|
||||
@@ -50,7 +50,7 @@ SECTION_CLASS = "LX/0Lis;"
|
||||
_LABEL_METHOD = re.compile(
|
||||
r"^\.method public static final LIZJ\(Ljava/lang/String;ZZZLkotlin/jvm/functions/Function0;LX/0LYA;II\)V\n"
|
||||
r".*?^\.end method", re.M | re.S)
|
||||
_LABEL_COLOUR = re.compile(r"^ iget-wide ([vp]\d+), ([vp]\d+), LX/1MiX;->d4:J\n", re.M)
|
||||
_TOKEN_READ = re.compile(r"^ iget-wide ([vp]\d+), ([vp]\d+), LX/1MiX;->(\w+):J\n", re.M)
|
||||
|
||||
|
||||
def section_targets():
|
||||
@@ -72,9 +72,15 @@ def rewrite_section_label(text: str) -> str:
|
||||
method = match.group()
|
||||
if "sectionLabel" in method:
|
||||
raise ValueError("Section label hook already present in LX/0Lis;->LIZJ")
|
||||
if len(_LABEL_COLOUR.findall(method)) != 2:
|
||||
raise ValueError("LX/0Lis;->LIZJ must read the d4 token exactly twice")
|
||||
patched = _LABEL_COLOUR.sub(
|
||||
# the token field has another obfuscated name in every build: it is the one colour token this method reads exactly twice
|
||||
counts = {}
|
||||
for read in _TOKEN_READ.finditer(method):
|
||||
counts[read.group(3)] = counts.get(read.group(3), 0) + 1
|
||||
twice = [name for name, count in counts.items() if count == 2]
|
||||
if len(twice) != 1:
|
||||
raise ValueError("LX/0Lis;->LIZJ must read exactly one colour token twice (the secondary-text token), found %s" % counts)
|
||||
label_colour = re.compile(r"^ iget-wide ([vp]\d+), ([vp]\d+), LX/1MiX;->" + re.escape(twice[0]) + r":J\n", re.M)
|
||||
patched = label_colour.sub(
|
||||
lambda read: " invoke-static/range {%s .. %s}, %s\n\n move-result-wide %s\n"
|
||||
% (read.group(2), read.group(2), SECTION_HOOK, read.group(1)),
|
||||
method)
|
||||
|
||||
@@ -26,6 +26,7 @@ SETTINGS_ACTIVITY = "lihont.two.settings.LihonTSettingsActivity"
|
||||
# activity draws its own Nothing-inspired surface.
|
||||
SETTINGS_THEME = 0x7F120364
|
||||
STORE_LOGIN_ACTIVITY = "lihont.two.store.LoginActivity"
|
||||
GIFT_ACTIVITY = "lihont.two.pet.GiftActivity"
|
||||
NO_DISPLAY_THEME = 0x01030055 # android:style/Theme.NoDisplay: the login screen has no window, it only answers
|
||||
|
||||
# dex -> list of class descriptors patched for the region feature
|
||||
@@ -600,6 +601,12 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict:
|
||||
manifest_module.add_activity(xml, STORE_LOGIN_ACTIVITY, "LihonT Store", NO_DISPLAY_THEME, exported=True)
|
||||
apk.replace("AndroidManifest.xml", xml.build())
|
||||
report["manifest"]["store_login_activity"] = STORE_LOGIN_ACTIVITY
|
||||
# The link that gives a pair its animal (lihont.space/pet?kind=cat&from=...) opens the gift screen, which asks before it does anything.
|
||||
if not manifest_module.has_activity(xml, GIFT_ACTIVITY):
|
||||
manifest_module.add_activity(xml, GIFT_ACTIVITY, "LihonT", SETTINGS_THEME, exported=True,
|
||||
links=(("https", "lihont.space", "/pet"), ("lihont", "pet", None)))
|
||||
apk.replace("AndroidManifest.xml", xml.build())
|
||||
report["manifest"]["gift_activity"] = GIFT_ACTIVITY
|
||||
# The launcher icons the settings screen offers: one disabled alias per catalog icon.
|
||||
from . import app_icons
|
||||
report["app_icons"] = step("app_icons", app_icons.apply, apk, xml, app_icons.load_catalog(Path("src/icons")))
|
||||
|
||||
@@ -78,6 +78,103 @@ class WidgetError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Ids:
|
||||
"""What the patch has to know about one TikTok build. It is found in the build itself (discover), never typed in per version."""
|
||||
layout: int # the layout of the small Stories widget
|
||||
layout_file: str
|
||||
picture: int # its picture view
|
||||
flipper: int # the id the new ViewFlipper takes
|
||||
frames: tuple # the ids of the three more picture views
|
||||
badge: int # the number tile of that layout (hidden by our widget)
|
||||
label: int # its text (hidden by our widget)
|
||||
providers: tuple # the provider file of each of SIZES, in order
|
||||
|
||||
|
||||
DEFAULT = Ids(LAYOUT, LAYOUT_FILE, PICTURE, FLIPPER_VIEW, FRAME_VIEWS, 0x7F0A881C, 0x7F0A8829, tuple(s.provider for s in SIZES))
|
||||
IDS_ASSET = "assets/lihont_widget_ids.txt" # read by lihont.two.widget.WidgetIds at run time
|
||||
|
||||
|
||||
def _provider_resource(xml: Axml, receiver) -> int:
|
||||
"""The resource id of the provider description a receiver declares in its <meta-data android.appwidget.provider>."""
|
||||
depth = 0
|
||||
for node in xml.nodes[xml.nodes.index(receiver):]:
|
||||
if node.kind == RES_XML_START_ELEMENT:
|
||||
depth += 1
|
||||
if xml.pool.get(node.name) == "meta-data" and xml.attr_string(node, "name") == "android.appwidget.provider":
|
||||
attr = xml.attr(node, "resource")
|
||||
if attr is None or attr.kind != TYPE_REFERENCE:
|
||||
break
|
||||
return attr.data
|
||||
elif node.kind == RES_XML_END_ELEMENT:
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
break
|
||||
raise WidgetError("the receiver declares no widget provider description")
|
||||
|
||||
|
||||
def _file_of(table: Arsc, res_id: int, what: str) -> str:
|
||||
for value in table.values(res_id):
|
||||
path = table.file_path(value)
|
||||
if path:
|
||||
return path
|
||||
raise WidgetError("%s 0x%08x is not a file of the apk" % (what, res_id))
|
||||
|
||||
|
||||
def discover(apk, xml: Axml, table: Arsc) -> Ids:
|
||||
"""Everything a build-dependent number was typed in for, read from the build: the provider files from the manifest, the layout from
|
||||
the provider of the 2x2 Stories widget, the views from that layout, and the neighbours of its picture view as the free ids."""
|
||||
providers = []
|
||||
for size in SIZES:
|
||||
receiver = _receiver(xml, size.original)
|
||||
if receiver is None:
|
||||
raise WidgetError("receiver %s not found" % size.original)
|
||||
providers.append(_file_of(table, _provider_resource(xml, receiver), "provider description"))
|
||||
story = Axml.parse(apk.read(providers[[s.cells for s in SIZES].index(2)]))
|
||||
found = [n for n in story.nodes if n.kind == RES_XML_START_ELEMENT and story.pool.get(n.name) == "appwidget-provider"]
|
||||
attr = story.attr(found[0], "initialLayout") if found else None
|
||||
if attr is None or attr.kind != TYPE_REFERENCE:
|
||||
raise WidgetError("the Stories widget has no initial layout")
|
||||
layout_file = _file_of(table, attr.data, "layout")
|
||||
layout = Axml.parse(apk.read(layout_file))
|
||||
root, picture_node = _picture(layout, None)
|
||||
picture = _attr_by_id(layout, picture_node, ATTR_ID).data
|
||||
badge = label = None
|
||||
for node in (n for n in layout.nodes if n.kind == RES_XML_START_ELEMENT):
|
||||
ident = _attr_by_id(layout, node, ATTR_ID)
|
||||
name = layout.pool.get(node.name)
|
||||
if ident is None:
|
||||
continue
|
||||
if name == "FrameLayout" and badge is None:
|
||||
badge = ident.data
|
||||
elif name == "TextView" and label is None:
|
||||
label = ident.data
|
||||
if badge is None or label is None:
|
||||
raise WidgetError("the widget layout has no number tile")
|
||||
free = [picture - 1] + [picture + k for k in (1, 2, 3)]
|
||||
for res_id in free:
|
||||
if not table.values(res_id) or _attr_by_id_in(layout, res_id):
|
||||
raise WidgetError("view id 0x%08x next to the picture is not free" % res_id)
|
||||
return Ids(attr.data, layout_file, picture, free[0], tuple(free[1:]), badge, label, tuple(providers))
|
||||
|
||||
|
||||
def _attr_by_id_in(layout: Axml, res_id: int) -> bool:
|
||||
"""Whether some element of the layout already has this id."""
|
||||
for node in layout.nodes:
|
||||
if node.kind == RES_XML_START_ELEMENT:
|
||||
ident = _attr_by_id(layout, node, ATTR_ID)
|
||||
if ident is not None and ident.data == res_id:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def ids_text(ids: Ids) -> str:
|
||||
"""The file the widget class reads: one `name=0xID` per line, frames separated by commas."""
|
||||
lines = ["layout=0x%08X" % ids.layout, "picture=0x%08X" % ids.picture, "badge=0x%08X" % ids.badge, "label=0x%08X" % ids.label,
|
||||
"frames=" + ",".join("0x%08X" % f for f in ids.frames)]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def dp(value: int) -> int:
|
||||
"""A dimension in dp as the binary XML stores it."""
|
||||
return (value << 8) | 0x01
|
||||
@@ -125,7 +222,7 @@ def retarget_manifest(xml: Axml, theme: int) -> Dict[str, object]:
|
||||
return {"receivers": done, "label": LABEL, "configure": CONFIG_CLASS}
|
||||
|
||||
|
||||
def rewrite_provider(provider: Axml, cells: int) -> None:
|
||||
def rewrite_provider(provider: Axml, cells: int, layout: int = LAYOUT) -> None:
|
||||
"""The provider description side: size, layout, resizing and the configuration screen."""
|
||||
found = [n for n in provider.nodes
|
||||
if n.kind == RES_XML_START_ELEMENT and provider.pool.get(n.name) == "appwidget-provider"]
|
||||
@@ -148,7 +245,7 @@ def rewrite_provider(provider: Axml, cells: int) -> None:
|
||||
provider.set_attr(node, "maxResizeWidth", TYPE_DIMENSION, dp(MAX_RESIZE_DP))
|
||||
provider.set_attr(node, "maxResizeHeight", TYPE_DIMENSION, dp(MAX_RESIZE_DP))
|
||||
provider.set_attr(node, "updatePeriodMillis", TYPE_INT_DEC, UPDATE_PERIOD_MS)
|
||||
provider.set_attr_ref(node, "initialLayout", LAYOUT)
|
||||
provider.set_attr_ref(node, "initialLayout", layout)
|
||||
provider.set_attr_string(node, "configure", CONFIG_CLASS)
|
||||
|
||||
|
||||
@@ -160,8 +257,8 @@ def _attr_by_id(xml: Axml, node, resource_id: int):
|
||||
return None
|
||||
|
||||
|
||||
def _picture(layout: Axml):
|
||||
"""The root element and the picture view of the widget layout, or a WidgetError."""
|
||||
def _picture(layout: Axml, picture: int = PICTURE):
|
||||
"""The root element and the picture view of the widget layout, or a WidgetError. With picture None the first ImageView that has an id is it."""
|
||||
elements = [n for n in layout.nodes if n.kind == RES_XML_START_ELEMENT]
|
||||
if not elements or layout.pool.get(elements[0].name) != "RelativeLayout":
|
||||
raise WidgetError("the widget layout does not start with a RelativeLayout")
|
||||
@@ -169,12 +266,12 @@ def _picture(layout: Axml):
|
||||
if layout.pool.get(node.name) != "ImageView":
|
||||
continue
|
||||
ident = _attr_by_id(layout, node, ATTR_ID)
|
||||
if ident is not None and ident.data == PICTURE:
|
||||
if ident is not None and (picture is None or ident.data == picture):
|
||||
return elements[0], node
|
||||
raise WidgetError("the picture view is not in the widget layout")
|
||||
|
||||
|
||||
def animate_layout(layout: Axml) -> None:
|
||||
def animate_layout(layout: Axml, picture_id: int = PICTURE, flipper_id: int = FLIPPER_VIEW, frame_ids: tuple = FRAME_VIEWS) -> None:
|
||||
"""Put the picture view into a ViewFlipper with three more picture views behind it.
|
||||
|
||||
A widget cannot run code of its own, but its host can flip a ViewFlipper by itself: the widget fills the four
|
||||
@@ -182,13 +279,13 @@ def animate_layout(layout: Axml) -> None:
|
||||
each into the next. Frame 0 is the old picture view, so a widget that draws only that one still works.
|
||||
Run after fill_layout: the new pictures copy the size the first one has.
|
||||
"""
|
||||
_, picture = _picture(layout)
|
||||
_, picture = _picture(layout, picture_id)
|
||||
start = layout.nodes.index(picture)
|
||||
if layout.nodes[start + 1].kind != RES_XML_END_ELEMENT:
|
||||
raise WidgetError("the picture view of the widget layout has children")
|
||||
|
||||
flipper = layout.make_element("ViewFlipper")
|
||||
layout.set_attr(flipper, "id", TYPE_REFERENCE, FLIPPER_VIEW)
|
||||
layout.set_attr(flipper, "id", TYPE_REFERENCE, flipper_id)
|
||||
layout.set_attr(flipper, "layout_width", TYPE_INT_DEC, MATCH_PARENT)
|
||||
layout.set_attr(flipper, "layout_height", TYPE_INT_DEC, MATCH_PARENT)
|
||||
layout.set_attr_bool(flipper, "autoStart", True)
|
||||
@@ -199,7 +296,7 @@ def animate_layout(layout: Axml) -> None:
|
||||
flipper_end = layout.close_element(flipper)
|
||||
|
||||
frames = []
|
||||
for view_id in FRAME_VIEWS:
|
||||
for view_id in frame_ids:
|
||||
copy = Node(RES_XML_START_ELEMENT, picture.line, picture.comment)
|
||||
copy.ns, copy.name = picture.ns, picture.name
|
||||
copy.id_index, copy.class_index, copy.style_index = picture.id_index, picture.class_index, picture.style_index
|
||||
@@ -213,14 +310,14 @@ def animate_layout(layout: Axml) -> None:
|
||||
layout.nodes[start:start] = [flipper]
|
||||
|
||||
|
||||
def fill_layout(layout: Axml) -> None:
|
||||
def fill_layout(layout: Axml, picture_id: int = PICTURE) -> None:
|
||||
"""Make the layout the widgets draw into as large as the widget it sits in.
|
||||
|
||||
TikTok's small Stories widget fixes both its root and its picture at 132dp. In a smaller cell (one
|
||||
cell is about 70dp) the launcher showed only the middle of that square, so the flower's petals were
|
||||
cut away and the number ran out of the tile; in a bigger one the picture floated in the middle.
|
||||
"""
|
||||
root, picture = _picture(layout)
|
||||
root, picture = _picture(layout, picture_id)
|
||||
for node in (root, picture):
|
||||
for resource_id in (ATTR_LAYOUT_WIDTH, ATTR_LAYOUT_HEIGHT):
|
||||
attr = _attr_by_id(layout, node, resource_id)
|
||||
@@ -253,24 +350,27 @@ def apply(apk, xml: Axml, theme: int) -> Dict[str, object]:
|
||||
In 47.1.3 only the four provider files and the layouts of those same widgets point at them, so the files take
|
||||
the flower of preview_asset() instead; every provider gets the same picture.
|
||||
"""
|
||||
report = retarget_manifest(xml, theme)
|
||||
table = Arsc(apk.read("resources.arsc"))
|
||||
ids = discover(apk, xml, table) # before the receivers are renamed: they are looked up by TikTok's names
|
||||
report = retarget_manifest(xml, theme)
|
||||
previews = set()
|
||||
for size in SIZES:
|
||||
provider = Axml.parse(apk.read(size.provider))
|
||||
for size, path in zip(SIZES, ids.providers):
|
||||
provider = Axml.parse(apk.read(path))
|
||||
previews.update(preview_files(provider, table)) # read before the rewrite keeps or drops anything
|
||||
rewrite_provider(provider, size.cells)
|
||||
apk.replace(size.provider, provider.build())
|
||||
layout = Axml.parse(apk.read(LAYOUT_FILE))
|
||||
fill_layout(layout)
|
||||
animate_layout(layout)
|
||||
apk.replace(LAYOUT_FILE, layout.build())
|
||||
rewrite_provider(provider, size.cells, ids.layout)
|
||||
apk.replace(path, provider.build())
|
||||
layout = Axml.parse(apk.read(ids.layout_file))
|
||||
fill_layout(layout, ids.picture)
|
||||
animate_layout(layout, ids.picture, ids.flipper, ids.frames)
|
||||
apk.replace(ids.layout_file, layout.build())
|
||||
apk.add(IDS_ASSET, ids_text(ids).encode("ascii"))
|
||||
picture = preview_asset().read_bytes()
|
||||
for path in sorted(previews):
|
||||
apk.replace(path, picture)
|
||||
apk.replace("AndroidManifest.xml", xml.build())
|
||||
report["providers"] = [size.provider for size in SIZES]
|
||||
report["layout"] = LAYOUT_FILE
|
||||
report["providers"] = list(ids.providers)
|
||||
report["layout"] = ids.layout_file
|
||||
report["ids"] = {"layout": "0x%08X" % ids.layout, "picture": "0x%08X" % ids.picture, "badge": "0x%08X" % ids.badge, "label": "0x%08X" % ids.label}
|
||||
report["previews"] = sorted(previews)
|
||||
return report
|
||||
|
||||
|
||||
@@ -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", "community.py", "moderation.py", "modbot.py", "catalog.py") if (SOURCE / name).is_file())
|
||||
FILES = tuple(name for name in ("server.py", "community.py", "moderation.py", "modbot.py", "catalog.py", "report.py", "accounts.py", "authbot.py") if (SOURCE / name).is_file())
|
||||
SSH = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", HOST]
|
||||
|
||||
|
||||
|
||||
114
scripts/make_pet_cards.py
Normal file
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Cards for the post "everything works again + animals of the Серийчик": 1080x1350 PNGs in work/promo/cards_pets/.
|
||||
Needs work/pets/*.png (py scripts/make_pet_designs.py first).
|
||||
|
||||
usage (from the repository root): py -B scripts/make_pet_cards.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import make_lihont_promo as P # noqa: E402
|
||||
import make_lihont_cards as C # noqa: E402
|
||||
|
||||
BRAND = "LihonT 3 · Luna pre-alpha · @lihont"
|
||||
|
||||
|
||||
def footer(layer: Image.Image) -> None:
|
||||
P.draw_text(layer, (C.CW / 2, C.CH - 44), BRAND, 32, P.MUTED + (255,), bold=False)
|
||||
|
||||
|
||||
def soon(layer: Image.Image, y: int = 350) -> None:
|
||||
P.chip(layer, C.CW / 2, y, "Скоро в LihonT 3", 1.0, size=34, fill=P.PRIMARY, fg=P.BG)
|
||||
|
||||
|
||||
PETS = P.ROOT / "work" / "pets"
|
||||
OUT_DIR = P.ROOT / "work" / "promo" / "cards_pets"
|
||||
|
||||
|
||||
def pet(kind: str, stage: str, grey: bool = False) -> Image.Image:
|
||||
return Image.open(PETS / ("%s_%s%s.png" % (kind, stage, "_grey" if grey else ""))).convert("RGBA")
|
||||
|
||||
|
||||
def card_fixed() -> Image.Image:
|
||||
img = C.backdrop(21)
|
||||
layer = Image.new("RGBA", (C.CW, C.CH), (0, 0, 0, 0))
|
||||
P.place(layer, P.ASSETS["blobs"][1], C.CW / 2, 450, 1.4)
|
||||
P.place(layer, P.ASSETS["logo"], C.CW / 2, 450, 0.5)
|
||||
P.draw_text(layer, (C.CW / 2, 800), "Всё снова работает", 96, P.ON + (255,))
|
||||
P.draw_text(layer, (C.CW / 2, 910), "Сайт, магазин и сервера на новом адресе", 42, P.PRIMARY + (255,), bold=False)
|
||||
P.chip(layer, C.CW / 2, 1030, "Обновлять ничего не нужно", 1.0, size=44, fill=P.PRIMARY, fg=P.BG)
|
||||
P.chip(layer, C.CW / 2, 1140, "Всё само подхватится", 1.0, size=40)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_animals() -> Image.Image:
|
||||
img = C.backdrop(22)
|
||||
layer = Image.new("RGBA", (C.CW, C.CH), (0, 0, 0, 0))
|
||||
C.head(layer, "Серийчик теперь зверь", "Котёнок, щенок или львёнок")
|
||||
soon(layer)
|
||||
for x, kind, tilt in ((220, "cat", -5), (540, "dog", 3), (860, "lion", -3)):
|
||||
P.place(layer, pet(kind, "teen"), x, 700, 0.9, tilt)
|
||||
P.chip(layer, 220, 1000, "Кот", 1.0, size=40)
|
||||
P.chip(layer, 540, 1000, "Пёс", 1.0, size=40)
|
||||
P.chip(layer, 860, 1000, "Лев", 1.0, size=40)
|
||||
P.chip(layer, C.CW / 2, 1150, "Машут хвостом, дёргают ушами, моргают", 1.0, size=34)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_growth() -> Image.Image:
|
||||
img = C.backdrop(23)
|
||||
layer = Image.new("RGBA", (C.CW, C.CH), (0, 0, 0, 0))
|
||||
C.head(layer, "Растёт вместе с серией", "От малыша до старичка")
|
||||
soon(layer)
|
||||
stages = (("cub", "0–6 дней"), ("teen", "7–29"), ("adult", "30–99"), ("elder", "100+"))
|
||||
for i, (stage, label) in enumerate(stages):
|
||||
x = 170 + i * 247
|
||||
P.place(layer, pet("cat", stage), x, 640, 0.52)
|
||||
P.chip(layer, x, 880, label, 1.0, size=30)
|
||||
P.draw_text(layer, (C.CW / 2, 1010), "А если серия вот-вот сгорит,", 40, P.MUTED + (255,), bold=False)
|
||||
P.draw_text(layer, (C.CW / 2, 1066), "зверь становится серым и грустным", 40, P.MUTED + (255,), bold=False)
|
||||
P.place(layer, pet("cat", "adult", True), 540, 1200, 0.38)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_gift() -> Image.Image:
|
||||
img = C.backdrop(24)
|
||||
layer = Image.new("RGBA", (C.CW, C.CH), (0, 0, 0, 0))
|
||||
C.head(layer, "Подари зверя другу", "Ссылкой, в один тап")
|
||||
soon(layer)
|
||||
P.place(layer, P.ASSETS["blobs"][2], C.CW / 2, 640, 1.2)
|
||||
P.place(layer, pet("cat", "cub"), C.CW / 2, 640, 0.75, -3)
|
||||
P.chip(layer, C.CW / 2, 960, "1. «Серийчик» → выбираешь зверя", 1.0, size=36)
|
||||
P.chip(layer, C.CW / 2, 1050, "2. Отправляешь другу ссылку", 1.0, size=36)
|
||||
P.chip(layer, C.CW / 2, 1140, "3. Друг жмёт «Принять»", 1.0, size=36)
|
||||
P.chip(layer, C.CW / 2, 1230, "Зверь живёт в вашем общем чате", 1.0, size=34, fill=P.PRIMARY, fg=P.BG)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def main() -> None:
|
||||
P.init_assets()
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
for name, make in (("1_fixed", card_fixed), ("2_animals", card_animals), ("3_growth", card_growth), ("4_gift", card_gift)):
|
||||
path = OUT_DIR / ("pet_%s.png" % name)
|
||||
make().convert("RGB").save(path)
|
||||
print(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
334
scripts/make_pet_designs.py
Normal file
@@ -0,0 +1,334 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
The Серийчик animals of LihonT: a kitten, a puppy and a lion cub that grow with the days of a streak (cub, teen, adult, elder) and go grey
|
||||
and sad when the streak is about to burn out. They are drawn here from circles and curves (Pillow only, supersampled), so they are ours.
|
||||
|
||||
py -X utf8 -B scripts/make_pet_designs.py # work/pets/preview.png and work/pets/<animal>_<stage>[_grey].png
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "work" / "pets"
|
||||
S = 3 # supersampling
|
||||
SIZE = 512 # final side of one picture
|
||||
W = SIZE * S
|
||||
INK = (58, 40, 52)
|
||||
WHITE = (255, 255, 255)
|
||||
|
||||
PALETTES = {
|
||||
"cat": {"fur": (255, 170, 82), "dark": (226, 120, 40), "belly": (255, 232, 200), "ear": (255, 150, 160)},
|
||||
"dog": {"fur": (232, 188, 132), "dark": (150, 98, 60), "belly": (255, 240, 214), "ear": (150, 98, 60)},
|
||||
"lion": {"fur": (255, 206, 96), "dark": (222, 140, 40), "belly": (255, 236, 190), "ear": (255, 170, 120)},
|
||||
}
|
||||
STAGES = ["cub", "teen", "adult", "elder"]
|
||||
STAGE_NAMES = {"cub": "малыш", "teen": "подросток", "adult": "взрослый", "elder": "старший"}
|
||||
# head size, body size, eye size, body height relative to the head (all relative to the picture)
|
||||
LOOK = {"cub": (0.34, 0.20, 1.25, 0.18), "teen": (0.29, 0.25, 1.05, 0.30), "adult": (0.25, 0.30, 0.9, 0.38), "elder": (0.25, 0.30, 0.9, 0.38)}
|
||||
|
||||
|
||||
FRAMES = 24 # one loop: 24 frames at 12 per second
|
||||
|
||||
|
||||
def rot(point, origin, degrees):
|
||||
a = math.radians(degrees)
|
||||
dx, dy = point[0] - origin[0], point[1] - origin[1]
|
||||
return (origin[0] + dx * math.cos(a) - dy * math.sin(a), origin[1] + dx * math.sin(a) + dy * math.cos(a))
|
||||
|
||||
|
||||
def motion(frame):
|
||||
"""(tail angle, left ear angle, right ear angle, blink 0..1, bob) of one frame of the loop."""
|
||||
tail = 13 * math.sin(math.tau * frame / 12) # the tail wags twice in a loop
|
||||
left = -16 * math.sin(math.pi * (frame - 5) / 4) if 5 <= frame <= 9 else 0.0 # the left ear twitches
|
||||
right = 16 * math.sin(math.pi * (frame - 15) / 4) if 15 <= frame <= 19 else 0.0 # the right ear, a little later
|
||||
blink = 1.0 if frame in (12, 13) else 0.0
|
||||
bob = 0.004 * math.sin(math.tau * frame / 24)
|
||||
return tail, left, right, blink, bob
|
||||
|
||||
|
||||
def grey(color):
|
||||
g = int(0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2])
|
||||
return (int(g * 0.9 + 60 * 0.1), int(g * 0.9 + 60 * 0.1), int(g * 0.95 + 70 * 0.1))
|
||||
|
||||
|
||||
class Canvas:
|
||||
def __init__(self, sad):
|
||||
self.img = Image.new("RGBA", (W, W), (0, 0, 0, 0))
|
||||
self.d = ImageDraw.Draw(self.img)
|
||||
self.sad = sad
|
||||
|
||||
K = 0.74
|
||||
|
||||
def t(self, x, y):
|
||||
return (0.46 + (x - 0.5) * self.K) * W, (0.54 + (y - 0.5) * self.K) * W
|
||||
|
||||
def c(self, color):
|
||||
return grey(color) if self.sad else color
|
||||
|
||||
def ell(self, cx, cy, rx, ry, fill, outline=True, width=0.012):
|
||||
(cx, cy), rx, ry = self.t(cx, cy), rx * W * self.K, ry * W * self.K
|
||||
if outline:
|
||||
o = width * W
|
||||
self.d.ellipse([cx - rx - o, cy - ry - o, cx + rx + o, cy + ry + o], fill=INK)
|
||||
self.d.ellipse([cx - rx, cy - ry, cx + rx, cy + ry], fill=self.c(fill))
|
||||
|
||||
def poly(self, pts, fill, outline=True, width=0.012):
|
||||
pts = [self.t(x, y) for x, y in pts]
|
||||
if outline:
|
||||
self.d.line(pts + [pts[0]], fill=INK, width=int(width * 2 * W), joint="curve")
|
||||
self.d.polygon(pts, fill=self.c(fill))
|
||||
|
||||
def line(self, pts, width, color=INK):
|
||||
self.d.line([self.t(x, y) for x, y in pts], fill=color, width=int(width * W * self.K), joint="curve")
|
||||
|
||||
def arc(self, cx, cy, rx, ry, a0, a1, width, color=INK):
|
||||
(x0, y0), (x1, y1) = self.t(cx - rx, cy - ry), self.t(cx + rx, cy + ry)
|
||||
self.d.arc([x0, y0, x1, y1], a0, a1, fill=color, width=int(width * W * self.K))
|
||||
|
||||
|
||||
def tube(cv, p0, c1, c2, p3, w0, w1, fill, tip=None, tuft=None):
|
||||
"""A tail: a cubic curve that gets thinner towards its end, with round ends and an outline. `tip` colours the last fifth; `tuft` puts a
|
||||
leaf-shaped brush of that colour at the end, pointing the way the tail points."""
|
||||
pts = []
|
||||
for i in range(61):
|
||||
t = i / 60
|
||||
u = 1 - t
|
||||
pts.append((u ** 3 * p0[0] + 3 * u * u * t * c1[0] + 3 * u * t * t * c2[0] + t ** 3 * p3[0],
|
||||
u ** 3 * p0[1] + 3 * u * u * t * c1[1] + 3 * u * t * t * c2[1] + t ** 3 * p3[1]))
|
||||
for outline in (True, False):
|
||||
for i, (x, y) in enumerate(pts):
|
||||
t = i / 60
|
||||
w = w0 + (w1 - w0) * t + (0.026 if outline else 0)
|
||||
(cx, cy) = cv.t(x, y)
|
||||
r = w * W * cv.K / 2
|
||||
color = INK if outline else cv.c(tip if tip is not None and t > 0.8 else fill)
|
||||
cv.d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=color)
|
||||
if tuft is not None: # a brush of three round tufts
|
||||
x1, y1 = pts[-1]
|
||||
for dx, dy, r in ((0.0, 0.0, 0.042), (-0.034, 0.03, 0.034), (0.034, 0.03, 0.034)):
|
||||
cv.ell(x1 + dx, y1 + dy, r, r, tuft)
|
||||
|
||||
|
||||
def scarf(cv, cx, head_cy, head, body_cy):
|
||||
"""A scarf round the neck with one end hanging down; drawn before the head so the chin lies over it."""
|
||||
red, dark = (232, 72, 92), (186, 44, 70)
|
||||
cv.ell(cx, head_cy + head * 0.86, head * 0.82, head * 0.2, red)
|
||||
x = cx + head * 0.42
|
||||
top = head_cy + head * 0.95
|
||||
cv.poly([(x - head * 0.17, top), (x + head * 0.17, top), (x + head * 0.2, top + head * 0.82), (x - head * 0.2, top + head * 0.82)], red)
|
||||
cv.poly([(x - head * 0.185, top + head * 0.5), (x + head * 0.19, top + head * 0.5), (x + head * 0.2, top + head * 0.62),
|
||||
(x - head * 0.2, top + head * 0.62)], dark, outline=False)
|
||||
|
||||
|
||||
def eyes(cv, cx, cy, spread, size, sad, blink=0.0):
|
||||
def box(x0, y0, x1, y1, fill):
|
||||
(a, b), (c, d) = cv.t(x0, y0), cv.t(x1, y1)
|
||||
cv.d.ellipse([a, b, c, d], fill=fill)
|
||||
|
||||
for sign in (-1, 1):
|
||||
x = cx + sign * spread
|
||||
if blink > 0.5: # a closed eye is a small arc
|
||||
cv.arc(x, cy + size * 0.2, size * 0.95, size * 0.7, 200, 340, 0.011)
|
||||
continue
|
||||
box(x - size, cy - size * 1.15, x + size, cy + size * 1.15, INK)
|
||||
box(x - size * 0.78, cy - size * 0.95, x + size * 0.78, cy + size * 0.95, (70, 42, 40) if not sad else (80, 80, 90))
|
||||
box(x - size * 0.35, cy - size * 0.7, x + size * 0.12, cy - size * 0.2, WHITE)
|
||||
box(x + size * 0.08, cy + size * 0.1, x + size * 0.38, cy + size * 0.4, WHITE)
|
||||
if sad: # a drooping brow
|
||||
cv.line([(x - size * 1.1, cy - size * (1.55 + 0.3 * sign)), (x + size * 1.1, cy - size * (1.55 - 0.3 * sign))], 0.012)
|
||||
|
||||
|
||||
def face(cv, animal, cx, cy, head, sad, stage, blink=0.0):
|
||||
pal = PALETTES[animal]
|
||||
size = LOOK[stage][2] * 0.032
|
||||
eyes(cv, cx, cy - head * 0.02, head * 0.42, size, sad, blink)
|
||||
cv.ell(cx - head * 0.62, cy + head * 0.22, head * 0.16, head * 0.1, (255, 150, 150), outline=False)
|
||||
cv.ell(cx + head * 0.62, cy + head * 0.22, head * 0.16, head * 0.1, (255, 150, 150), outline=False)
|
||||
nose = (cx, cy + head * 0.2)
|
||||
if animal == "dog":
|
||||
cv.ell(nose[0], nose[1], head * 0.14, head * 0.1, (70, 50, 52), outline=False)
|
||||
else:
|
||||
cv.poly([(nose[0] - head * 0.1, nose[1] - head * 0.05), (nose[0] + head * 0.1, nose[1] - head * 0.05), (nose[0], nose[1] + head * 0.06)],
|
||||
(255, 128, 140), outline=False)
|
||||
my = nose[1] + head * 0.1
|
||||
if sad:
|
||||
cv.arc(cx - head * 0.1, my + head * 0.12, head * 0.1, head * 0.08, 200, 340, 0.011)
|
||||
cv.arc(cx + head * 0.1, my + head * 0.12, head * 0.1, head * 0.08, 200, 340, 0.011)
|
||||
else:
|
||||
cv.arc(cx - head * 0.1, my, head * 0.1, head * 0.1, 10, 170, 0.011)
|
||||
cv.arc(cx + head * 0.1, my, head * 0.1, head * 0.1, 10, 170, 0.011)
|
||||
if animal == "dog" and stage != "elder":
|
||||
cv.ell(cx, my + head * 0.17, head * 0.09, head * 0.1, (255, 120, 135), width=0.008)
|
||||
if animal == "cat":
|
||||
for sign in (-1, 1):
|
||||
for k, dy in enumerate((-0.02, 0.06)):
|
||||
cv.line([(cx + sign * head * 0.38, cy + head * (0.28 + dy)), (cx + sign * head * 0.95, cy + head * (0.2 + dy * 2.2 + 0.08 * k))], 0.005, (90, 70, 80))
|
||||
|
||||
|
||||
def animal(kind, stage, sad=False, frame=0):
|
||||
tail_a, ear_l, ear_r, blink, bob = motion(frame) if frame is not None else (0, 0, 0, 0.0, 0.0)
|
||||
if sad: # a sad animal sways little
|
||||
tail_a, ear_l, ear_r = tail_a * 0.3, ear_l * 0.5, ear_r * 0.5
|
||||
cv = Canvas(sad)
|
||||
pal = PALETTES[kind]
|
||||
head, body, _, height = LOOK[stage]
|
||||
cx = 0.5
|
||||
bottom = 0.93
|
||||
body_h = height + 0.10
|
||||
body_cy = bottom - body_h * 0.5 - 0.02
|
||||
head_cy = body_cy - body_h * 0.5 - head * 0.45 + (0.1 if stage == "cub" else 0.0)
|
||||
if stage == "cub":
|
||||
head_cy = bottom - 0.02 - body_h * 0.55 - head * 0.55
|
||||
head_cy -= bob
|
||||
# tail (it swings about its root)
|
||||
fx = cx + body
|
||||
|
||||
def swing(points):
|
||||
root = points[0]
|
||||
return [rot(q, root, tail_a) for q in points]
|
||||
|
||||
if kind == "cat": # out to the side, up, and curling back at the end like a question mark
|
||||
q = swing([(fx - 0.02, body_cy + body_h * 0.3), (fx + 0.36, body_cy + body_h * 0.55), (fx + 0.42, body_cy - body_h * 0.75),
|
||||
(fx + 0.12, body_cy - body_h * 0.72)])
|
||||
tube(cv, q[0], q[1], q[2], q[3], 0.075, 0.045, pal["fur"], tip=pal["dark"])
|
||||
elif kind == "dog": # a short curl
|
||||
q = swing([(fx - 0.02, body_cy + body_h * 0.1), (fx + 0.2, body_cy + body_h * 0.2), (fx + 0.22, body_cy - body_h * 0.4),
|
||||
(fx + 0.06, body_cy - body_h * 0.4)])
|
||||
tube(cv, q[0], q[1], q[2], q[3], 0.07, 0.05, pal["fur"])
|
||||
else: # a lion's tail swings out and down with a brush at the end
|
||||
q = swing([(fx - 0.02, body_cy + body_h * 0.3), (fx + 0.25, body_cy + body_h * 0.05), (fx + 0.36, body_cy + body_h * 0.6),
|
||||
(fx + 0.2, body_cy + body_h * 0.62)])
|
||||
tube(cv, q[0], q[1], q[2], q[3], 0.05, 0.035, pal["fur"], tuft=pal["dark"])
|
||||
# body, belly, legs
|
||||
cv.ell(cx, body_cy, body, body_h * 0.5, pal["fur"])
|
||||
cv.ell(cx, body_cy + body_h * 0.08, body * 0.62, body_h * 0.34, pal["belly"], outline=False)
|
||||
for sign in (-1, 1):
|
||||
cv.ell(cx + sign * body * 0.52, bottom - 0.035, 0.07, 0.045, pal["fur"])
|
||||
cv.ell(cx + sign * body * 0.52, bottom - 0.02, 0.045, 0.02, pal["belly"], outline=False)
|
||||
# arms
|
||||
for sign in (-1, 1):
|
||||
cv.ell(cx + sign * (body + 0.012), body_cy - body_h * 0.05, 0.035, 0.07, pal["fur"])
|
||||
if stage == "elder" and kind != "lion":
|
||||
scarf(cv, cx, head_cy, head, body_cy)
|
||||
# mane of the lion behind the head
|
||||
if kind == "lion" and stage != "cub":
|
||||
rings = {"teen": 0.6, "adult": 1.0, "elder": 1.15}[stage]
|
||||
for k in range(14):
|
||||
a = k * math.tau / 14
|
||||
r = head * (1.0 + 0.1 * rings)
|
||||
cv.ell(cx + math.cos(a) * r, head_cy + math.sin(a) * r * 0.95, head * 0.3 * rings + head * 0.1, head * 0.3 * rings + head * 0.1, pal["dark"])
|
||||
# ears
|
||||
if kind == "cat":
|
||||
for sign in (-1, 1):
|
||||
base = (cx + sign * head * 0.55, head_cy - head * 0.5)
|
||||
a = ear_l if sign < 0 else ear_r
|
||||
outer = [rot(q, base, a) for q in [(cx + sign * head * 0.28, head_cy - head * 0.7), (cx + sign * head * 0.98, head_cy - head * 1.12),
|
||||
(cx + sign * head * 0.92, head_cy - head * 0.2)]]
|
||||
inner = [rot(q, base, a) for q in [(cx + sign * head * 0.42, head_cy - head * 0.68), (cx + sign * head * 0.84, head_cy - head * 0.92),
|
||||
(cx + sign * head * 0.8, head_cy - head * 0.38)]]
|
||||
cv.poly(outer, pal["fur"])
|
||||
cv.poly(inner, pal["ear"], outline=False)
|
||||
elif kind == "dog":
|
||||
for sign in (-1, 1):
|
||||
root = (cx + sign * head * 0.8, head_cy - head * 0.4)
|
||||
a = ear_l if sign < 0 else ear_r
|
||||
ex, ey = rot((cx + sign * head * 0.92, head_cy - head * 0.1 + (head * 0.15 if stage != "cub" else head * 0.28)), root, a)
|
||||
cv.ell(ex, ey, head * 0.3, head * 0.55, pal["ear"])
|
||||
else:
|
||||
for sign in (-1, 1):
|
||||
root = (cx + sign * head * 0.55, head_cy - head * 0.6)
|
||||
a = ear_l if sign < 0 else ear_r
|
||||
ex, ey = rot((cx + sign * head * 0.72, head_cy - head * 0.78), root, a * 1.5)
|
||||
cv.ell(ex, ey, head * 0.2, head * 0.2, pal["fur"])
|
||||
cv.ell(ex, ey, head * 0.1, head * 0.1, pal["ear"], outline=False)
|
||||
# head
|
||||
cv.ell(cx, head_cy, head * 1.05, head * 0.92, pal["fur"])
|
||||
if kind == "cat": # stripes on the forehead
|
||||
for dx in (-0.16, 0, 0.16):
|
||||
cv.line([(cx + head * dx, head_cy - head * 0.88), (cx + head * dx * 1.1, head_cy - head * 0.5)], 0.012, cv.c(pal["dark"]))
|
||||
cv.ell(cx, head_cy + head * 0.32, head * 0.55, head * 0.4, pal["belly"], outline=False)
|
||||
face(cv, kind, cx, head_cy + head * 0.02, head, sad, stage, blink)
|
||||
# what an elder wears (the crown of a lion; the scarf of the others was put on before the head)
|
||||
if stage == "elder" and kind == "lion":
|
||||
cv.poly([(cx - head * 0.55, head_cy - head * 0.95), (cx - head * 0.4, head_cy - head * 1.45), (cx - head * 0.15, head_cy - head * 1.15),
|
||||
(cx, head_cy - head * 1.55), (cx + head * 0.15, head_cy - head * 1.15), (cx + head * 0.4, head_cy - head * 1.45),
|
||||
(cx + head * 0.55, head_cy - head * 0.95)], (255, 214, 64))
|
||||
return cv.img.resize((SIZE, SIZE), Image.LANCZOS)
|
||||
|
||||
|
||||
def sheet(images, path):
|
||||
cell = SIZE // 2
|
||||
pad = 18
|
||||
cols = len(STAGES)
|
||||
rows = len(images) // cols
|
||||
out = Image.new("RGB", (cols * (cell + pad) + pad, rows * (cell + pad + 28) + pad), (252, 248, 240))
|
||||
d = ImageDraw.Draw(out)
|
||||
try:
|
||||
font = ImageFont.truetype("segoeuib.ttf", 22)
|
||||
except OSError:
|
||||
font = ImageFont.load_default()
|
||||
for i, (name, img) in enumerate(images):
|
||||
r, c = divmod(i, cols)
|
||||
x, y = pad + c * (cell + pad), pad + r * (cell + pad + 28)
|
||||
out.paste(img.resize((cell, cell), Image.LANCZOS), (x, y), img.resize((cell, cell), Image.LANCZOS))
|
||||
d.text((x + cell // 2, y + cell + 8), name, fill=(70, 60, 70), font=font, anchor="mt")
|
||||
out.save(path)
|
||||
|
||||
|
||||
def animated(path):
|
||||
"""One GIF with every animal of every stage moving at once."""
|
||||
cell = 200
|
||||
pad = 12
|
||||
cols, rows = len(STAGES), 3
|
||||
frames = []
|
||||
ground = (252, 248, 240)
|
||||
for f in range(FRAMES):
|
||||
sheet_img = Image.new("RGB", (cols * (cell + pad) + pad, rows * (cell + pad) + pad), ground)
|
||||
for r, kind in enumerate(("cat", "dog", "lion")):
|
||||
for c, stage in enumerate(STAGES):
|
||||
img = animal(kind, stage, frame=f).resize((cell, cell), Image.LANCZOS)
|
||||
sheet_img.paste(img, (pad + c * (cell + pad), pad + r * (cell + pad)), img)
|
||||
frames.append(sheet_img.quantize(colors=96, method=Image.MEDIANCUT, dither=Image.Dither.NONE))
|
||||
frames[0].save(path, save_all=True, append_images=frames[1:], duration=83, loop=0, disposal=1, optimize=False)
|
||||
|
||||
|
||||
def strips(folder):
|
||||
"""The sheets the mod downloads: for each animal, stage and state one strip of 8 frames (every third frame of the loop), 160 px each."""
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
cell = 160
|
||||
for kind in ("cat", "dog", "lion"):
|
||||
for stage in STAGES:
|
||||
for sad, state in ((False, "lit"), (True, "grey")):
|
||||
sheet_img = Image.new("RGBA", (cell * 8, cell), (0, 0, 0, 0))
|
||||
for i in range(8):
|
||||
sheet_img.paste(animal(kind, stage, sad=sad, frame=i * 3).resize((cell, cell), Image.LANCZOS), (i * cell, 0))
|
||||
sheet_img.save(folder / ("%s_%s_%s.png" % (kind, stage, state)), optimize=True)
|
||||
|
||||
|
||||
def main():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
images = []
|
||||
for kind in ("cat", "dog", "lion"):
|
||||
for stage in STAGES:
|
||||
img = animal(kind, stage)
|
||||
img.save(OUT / ("%s_%s.png" % (kind, stage)))
|
||||
animal(kind, stage, sad=True).save(OUT / ("%s_%s_grey.png" % (kind, stage)))
|
||||
images.append(({"cat": "кот", "dog": "пёс", "lion": "лев"}[kind] + ": " + STAGE_NAMES[stage], img))
|
||||
sheet(images, OUT / "preview.png")
|
||||
animated(OUT / "preview_anim.gif")
|
||||
sad = [("грустный " + n, animal(k, "teen", True)) for n, k in (("кот", "cat"), ("пёс", "dog"), ("лев", "lion"))]
|
||||
sad.append(("", Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))))
|
||||
sheet(sad, OUT / "preview_grey.png")
|
||||
strips(ROOT / "src" / "web" / "assets" / "pets" / "strips")
|
||||
print(OUT / "preview.png")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
445
scripts/make_pet_video.py
Normal file
@@ -0,0 +1,445 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
LihonT 3 · Luna pre-alpha: the promo video of the Серийчик animals, in the same white, light style as the Store video
|
||||
(scripts/make_store_video.py, whose drawing helpers and soundtrack it uses; the events here fall on the same moments as the sounds of
|
||||
work/music/store.mp3: click, drop, ticking, ding, pop, tiles, boing and mew, riser, three blups, sparkle, three word lines, title, logo).
|
||||
|
||||
Only our own material: the animals drawn by scripts/make_pet_designs.py, invented screens with no names and no message text.
|
||||
|
||||
py -X utf8 -B scripts/make_pet_video.py # work/pet-video/lihont3_pets.mp4
|
||||
py -X utf8 -B scripts/make_pet_video.py --still 7.9 16 # single frames
|
||||
py -X utf8 -B scripts/make_pet_video.py --sheet # a contact sheet
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from functools import lru_cache
|
||||
from multiprocessing import Pool
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFilter
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import make_pet_designs as D # noqa: E402
|
||||
import make_store_video as V # noqa: E402
|
||||
from make_store_video import (GREY, INK, VIOLET, burst, card, clamp, cursor_sprite, disc, draw_check, font, in_out, lerp, out_back, # noqa: E402
|
||||
out_cubic, pill, put, put_c, ripple, rr, seg, text)
|
||||
|
||||
OUT_DIR = V.ROOT / "work" / "pet-video"
|
||||
SPRITES = OUT_DIR / "sprites"
|
||||
BASE = 720 # the side the animals are drawn at
|
||||
W, H, FPS = 1920, 1080, 30
|
||||
CX, CY = W // 2, H // 2
|
||||
VERT = False
|
||||
|
||||
|
||||
def set_format(vertical: bool) -> None:
|
||||
"""Landscape 1920x1080 or portrait 1080x1920: the scenes read the size, the middle and VERT from here."""
|
||||
global W, H, CX, CY, VERT
|
||||
VERT = bool(vertical)
|
||||
W, H = (1080, 1920) if VERT else (1920, 1080)
|
||||
CX, CY = W // 2, H // 2
|
||||
V.set_format(VERT)
|
||||
|
||||
|
||||
PASTEL = {"cat": (255, 232, 214), "dog": (222, 234, 255), "lion": (255, 242, 204)}
|
||||
NAMES = {"cat": "Котёнок", "dog": "Щенок", "lion": "Львёнок"}
|
||||
PINK = (255, 99, 150)
|
||||
# every animal that is shown: (kind, stage, grey)
|
||||
CAST = [("cat", "cub", False), ("dog", "cub", False), ("lion", "cub", False), ("cat", "teen", False), ("cat", "adult", False),
|
||||
("cat", "elder", False), ("cat", "elder", True)]
|
||||
S: list = []
|
||||
|
||||
|
||||
def prepare() -> None:
|
||||
"""Draws every frame of every animal of the cast once, large, into work/pet-video/sprites."""
|
||||
SPRITES.mkdir(parents=True, exist_ok=True)
|
||||
D.SIZE, D.W = BASE, BASE * D.S
|
||||
for kind, stage, sad in CAST:
|
||||
for frame in range(D.FRAMES):
|
||||
path = SPRITES / ("%s_%s_%d_%02d.png" % (kind, stage, int(sad), frame))
|
||||
if not path.exists():
|
||||
D.animal(kind, stage, sad=sad, frame=frame).save(path)
|
||||
|
||||
|
||||
@lru_cache(maxsize=40)
|
||||
def sprite(kind: str, stage: str, sad: bool, frame: int) -> Image.Image:
|
||||
return Image.open(SPRITES / ("%s_%s_%d_%02d.png" % (kind, stage, int(sad), frame))).convert("RGBA")
|
||||
|
||||
|
||||
def pet(t: float, kind: str, stage: str = "cub", sad: bool = False) -> Image.Image:
|
||||
return sprite(kind, stage, sad, int(t * 12) % D.FRAMES)
|
||||
|
||||
|
||||
@lru_cache(maxsize=8)
|
||||
def ground_shadow(w: int) -> Image.Image:
|
||||
layer = Image.new("RGBA", (w + 80, w // 4 + 80), (0, 0, 0, 0))
|
||||
ImageDraw.Draw(layer).ellipse([40, 40, w + 40, w // 4 + 40], fill=(30, 20, 50, 60))
|
||||
return layer.filter(ImageFilter.GaussianBlur(16))
|
||||
|
||||
|
||||
def put_pet(img, t, kind, stage, cx, cy, size, alpha=1.0, sad=False, shadow=True, angle=0.0):
|
||||
"""An animal `size` pixels high with its middle at (cx, cy), standing on a soft shadow."""
|
||||
if size < 8 or alpha <= 0.003:
|
||||
return
|
||||
if shadow:
|
||||
put_c(img, ground_shadow(360), cx, cy + size * 0.4, size / 620, alpha)
|
||||
put_c(img, pet(t, kind, stage, sad), cx, cy, size / BASE, alpha, angle)
|
||||
|
||||
|
||||
@lru_cache(maxsize=4)
|
||||
def gift_box(size: int) -> Image.Image:
|
||||
k = 3
|
||||
s = size * k
|
||||
layer = Image.new("RGBA", (s, s), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(layer)
|
||||
d.rounded_rectangle([s * 0.14, s * 0.4, s * 0.86, s * 0.92], radius=s * 0.07, fill=PINK + (255,))
|
||||
d.rounded_rectangle([s * 0.08, s * 0.26, s * 0.92, s * 0.44], radius=s * 0.06, fill=(255, 130, 172, 255))
|
||||
d.rectangle([s * 0.44, s * 0.26, s * 0.56, s * 0.92], fill=(255, 214, 90, 255))
|
||||
for sx in (-1, 1): # the bow
|
||||
d.ellipse([s * 0.5 + sx * s * 0.02 - (s * 0.2 if sx < 0 else 0), s * 0.08, s * 0.5 + sx * s * 0.02 + (s * 0.2 if sx > 0 else 0), s * 0.28],
|
||||
fill=(255, 214, 90, 255))
|
||||
d.ellipse([s * 0.44, s * 0.15, s * 0.56, s * 0.27], fill=(240, 180, 50, 255))
|
||||
return layer.resize((size, size), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def arc(img, cx, cy, r, k, color, width=16):
|
||||
"""A ring that fills clockwise from the top up to k."""
|
||||
q = 3
|
||||
side = (r * 2 + width * 2) * q
|
||||
layer = Image.new("RGBA", (side, side), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(layer)
|
||||
box = [width * q, width * q, side - width * q, side - width * q]
|
||||
d.arc(box, 0, 360, fill=(232, 232, 238, 255), width=width * q)
|
||||
if k > 0.005:
|
||||
d.arc(box, -90, -90 + 360 * clamp(k), fill=tuple(color) + (255,), width=width * q)
|
||||
small = layer.resize((side // q, side // q), Image.Resampling.LANCZOS)
|
||||
put(img, small, cx - small.width / 2, cy - small.height / 2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- scenes
|
||||
|
||||
def scene_link(img, t):
|
||||
"""A pill in which the gift link types itself; the cursor comes and clicks it on the strong beat."""
|
||||
click = S[1]
|
||||
if t >= click + 0.45:
|
||||
return
|
||||
intro = out_back(seg(t, 0.1, 0.7))
|
||||
gone = seg(t, click + 0.1, click + 0.45)
|
||||
press = 1 - 0.06 * clamp(1 - abs(t - click) / 0.1)
|
||||
w, h = 820, 120
|
||||
full = "lihont.space/pet · котёнок для друга"
|
||||
shown = full[:int(len(full) * seg(t, 0.7, 2.2))]
|
||||
layer = Image.new("RGBA", (w + 120, h + 120), (0, 0, 0, 0))
|
||||
layer.alpha_composite(card(w, h, h // 2, (255, 255, 255), blur=30, dy=12, alpha=44))
|
||||
d = ImageDraw.Draw(layer)
|
||||
cx0, cy0 = 60 + 70, 60 + h // 2
|
||||
d.ellipse([cx0 - 38, cy0 - 38, cx0 + 38, cy0 + 38], fill=PINK + (255,))
|
||||
layer.alpha_composite(gift_box(52), (cx0 - 26, cy0 - 28))
|
||||
d.text((60 + 150, 60 + h // 2 - 1), shown, font=font(40, "semi"), fill=INK + (255,), anchor="lm")
|
||||
if len(shown) < len(full) and int(t * 3) % 2 == 0: # the caret
|
||||
x = 60 + 150 + d.textlength(shown, font=font(40, "semi")) + 4
|
||||
d.line([(x, 60 + 32), (x, 60 + h - 32)], fill=INK + (255,), width=3)
|
||||
ks = 0.88 if VERT else 1.0
|
||||
put_c(img, layer, CX, CY, lerp(0.9, 1.0, intro) * press * (1 + 0.25 * gone) * ks, clamp(intro * 1.3) * (1 - gone))
|
||||
ripple(img, CX + 50, CY + 20, t, click, PINK, 120)
|
||||
k = in_out(seg(t, 1.9, click - 0.1))
|
||||
cx, cy = lerp(W - 120, CX + 50, k) - math.sin(k * math.pi) * 90, lerp(H - 160 if VERT else H + 80, CY + 26, k)
|
||||
put_c(img, cursor_sprite(), cx + 10, cy + 16, 1.0 - 0.08 * clamp(1 - abs(t - click) / 0.1), out_cubic(seg(t, 1.8, 2.2)))
|
||||
|
||||
|
||||
def scene_gift(img, t): # noqa: C901
|
||||
"""The gift window: "Принять" is pressed, the ring fills, a check is drawn, the window slides down and the kitten pops out."""
|
||||
a, press_t, drop, ding = S[1] + 0.2, S[1] + 1.25, S[2], S[3]
|
||||
if t < a or t > S[4] + 0.75:
|
||||
return
|
||||
down = in_out(seg(t, ding + 0.5, ding + 1.2))
|
||||
grow = out_back(seg(t, a, a + 0.55), 1.2)
|
||||
w, h = 640, 720
|
||||
wy = CY + down * (H * 0.75)
|
||||
if down < 1:
|
||||
put_c(img, card(w, h, 56, (255, 255, 255), blur=44, dy=22, alpha=56), CX, wy, lerp(0.4, 1.0, grow), clamp(grow * 1.4))
|
||||
show = seg(t, a + 0.3, a + 0.6)
|
||||
text(img, (CX, wy - 270), "Вам дарят котёнка", 46, "bold", INK, "mm", alpha=show)
|
||||
text(img, (CX, wy - 212), "он поселится в вашем общем чате", 28, "reg", GREY, "mm", alpha=show)
|
||||
mid = wy - 30
|
||||
if t < drop: # the box, shaking after the press
|
||||
shake = math.sin((t - press_t) * 40) * 7 * seg(t, press_t, press_t + 0.2) if t > press_t else 0
|
||||
put_c(img, gift_box(300), CX, mid + math.sin(t * 3) * 6, out_back(show) * (1 - 0.3 * seg(t, drop - 0.12, drop)), show, shake)
|
||||
elif t < ding: # the ring fills while the mallets tick
|
||||
arc(img, CX, mid, 110, in_out(seg(t, drop, ding - 0.05)), PINK)
|
||||
put_pet(img, t, "cat", "cub", CX, mid, 150 * out_back(seg(t, drop, drop + 0.3)), shadow=False)
|
||||
burst(img, CX, mid, t, drop, seed=3, n=18, power=300, life=0.7)
|
||||
else: # the check
|
||||
pop = out_back(seg(t, ding, ding + 0.3))
|
||||
put_c(img, disc(240, PINK), CX, mid, pop)
|
||||
draw_check(img, CX, mid + 4, 110, out_cubic(seg(t, ding + 0.05, ding + 0.4)))
|
||||
burst(img, CX, mid, t, ding + 0.05, seed=5, n=46, power=640, life=1.2)
|
||||
# the button
|
||||
by = wy + 250
|
||||
pressed = 1 - 0.07 * clamp(1 - abs(t - press_t) / 0.12)
|
||||
if t < drop:
|
||||
pill(img, CX, by, "Принять", fill=INK, size=34, alpha=show, scale=pressed)
|
||||
elif t < ding:
|
||||
pill(img, CX, by, "Зверь уже едет…", fill=(240, 240, 243), color=GREY, size=30)
|
||||
else:
|
||||
pill(img, CX, by, "v Принято", fill=(226, 247, 232), color=(40, 140, 80), size=32, scale=out_back(seg(t, ding, ding + 0.3)))
|
||||
ripple(img, CX + 20, by + 6, t, press_t, PINK, 100)
|
||||
# the cursor: to the button, a press, away
|
||||
k = in_out(seg(t, a + 0.3, press_t - 0.1))
|
||||
away = in_out(seg(t, press_t + 0.3, drop))
|
||||
cx = lerp(lerp(CX + 50, CX + 26, k), CX + (380 if VERT else 520), away)
|
||||
cy = lerp(lerp(CY + 26, by + 10, k), by + 220, away) + down * (H * 0.75)
|
||||
put_c(img, cursor_sprite(), cx + 10, cy + 16, 1.0 - 0.08 * clamp(1 - abs(t - press_t) / 0.1), 1 - seg(t, drop - 0.2, drop + 0.2))
|
||||
# the kitten
|
||||
pop_t = ding + 0.9
|
||||
if t >= pop_t:
|
||||
leave = in_out(seg(t, S[4] + 0.35, S[4] + 0.75))
|
||||
k = out_back(seg(t, pop_t, pop_t + 0.5), 2.0)
|
||||
put_pet(img, t, "cat", "cub", lerp(CX, CX - (0 if VERT else 470), leave), CY - 20 + (1 - k) * 80, 520 * k * lerp(1, 0.6, leave), 1 - seg(t, S[4] + 0.6, S[4] + 0.75))
|
||||
burst(img, CX, CY - 20, t, pop_t + 0.05, seed=7, n=44, power=620, life=1.3)
|
||||
text(img, (CX, CY + 300), "Серийчик стал зверем", 54, "bold", INK, "mm", alpha=seg(t, pop_t + 0.35, pop_t + 0.7) * (1 - seg(t, S[4] + 0.1, S[4] + 0.4)))
|
||||
|
||||
|
||||
def tile(kind: str, t: float, size: int) -> Image.Image:
|
||||
pad = 80
|
||||
layer = Image.new("RGBA", (size + 2 * pad, size + 2 * pad), (0, 0, 0, 0))
|
||||
layer.alpha_composite(card(size, size, size // 7, PASTEL[kind], blur=40, dy=18, alpha=50), (pad - 80, pad - 80))
|
||||
p = pet(t, kind).resize((int(size * 0.92), int(size * 0.92)), Image.Resampling.BICUBIC)
|
||||
layer.alpha_composite(p, (pad + (size - p.width) // 2, pad + (size - p.height) // 2 + size // 30))
|
||||
return layer
|
||||
|
||||
|
||||
def scene_kinds(img, t):
|
||||
"""Three tiles glide in (kitten, puppy, lion cub), fan out, then gather and turn into one kitten with a mew."""
|
||||
a, fan, gather = S[4] + 0.45, S[6], S[7]
|
||||
if t < a or t > S[8] + 0.2:
|
||||
return
|
||||
kinds = ("cat", "dog", "lion")
|
||||
if t < gather + 0.3:
|
||||
size = 300 if VERT else 400
|
||||
wide, close = (335, 215) if VERT else (470, 300)
|
||||
g = in_out(seg(t, gather - 0.3, gather))
|
||||
f = in_out(seg(t, fan, fan + 0.5)) * (1 - g)
|
||||
squash = 1 - 0.5 * seg(t, gather, gather + 0.3)
|
||||
for i in (0, 2, 1):
|
||||
come = out_cubic(seg(t, a + 0.25 + i * 0.22, a + 0.9 + i * 0.22))
|
||||
bump = 1 + 0.07 * clamp(1 - abs(t - S[5]) / 0.18)
|
||||
x = CX + (i - 1) * lerp(wide, close, f) * (1 - g) + (1 - come) * 1500 - (t - a) * (0 if VERT else 6) * (1 - f) * (1 - g)
|
||||
y = CY - 30 + abs(i - 1) * 50 * f
|
||||
angle = -(i - 1) * 9 * f
|
||||
alpha = 1 - seg(t, gather + 0.15, gather + 0.3) if i == 0 else 1 - seg(t, gather - 0.05, gather + 0.1)
|
||||
put_c(img, tile(kinds[i], t, size), x, y, bump * squash * lerp(1.0, 1.08 if i == 1 else 1.0, f), alpha * clamp(come * 3), angle)
|
||||
label = seg(t, a + 0.7 + i * 0.22, a + 1.0 + i * 0.22) * (1 - seg(t, fan - 0.2, fan + 0.1))
|
||||
text(img, (x, CY + (180 if VERT else 230)), NAMES[kinds[i]], 34 if VERT else 40, "semi", INK, "mm", alpha=label)
|
||||
head = seg(t, S[5], S[5] + 0.35) * (1 - seg(t, gather - 0.3, gather))
|
||||
text(img, (CX, CY - (300 if VERT else 360)), "Машут хвостом, дёргают ушами, моргают", 40 if VERT else 44, "semi", GREY, "mm", alpha=head)
|
||||
if t >= gather + 0.25:
|
||||
k = out_back(seg(t, gather + 0.25, gather + 0.75), 2.2)
|
||||
put_pet(img, t, "cat", "cub", CX, CY - 10 + (1 - k) * 60, 560 * k)
|
||||
burst(img, CX, CY - 10, t, gather + 0.3, seed=9, n=46, power=660, life=1.3)
|
||||
|
||||
|
||||
STAGES = [("cub", 0, "Малыш"), ("teen", 7, "Подросток"), ("adult", 30, "Взрослый"), ("elder", 100, "Старший")]
|
||||
|
||||
|
||||
def scene_grow(img, t):
|
||||
"""The kitten grows with the days of the streak, goes grey when the streak is about to burn out, lights up again."""
|
||||
a = S[8] + 0.2
|
||||
if t < a or t > S[12] - 0.05:
|
||||
return
|
||||
marks = [a, S[8] + 1.0, S[9], S[10]]
|
||||
index = max(i for i in range(4) if t >= marks[i])
|
||||
stage, days, name = STAGES[index]
|
||||
since = t - marks[index]
|
||||
cold_t, warm_t = S[10] + 1.1, S[11]
|
||||
cold = cold_t <= t < warm_t
|
||||
leave = seg(t, S[12] - 0.4, S[12] - 0.05)
|
||||
zoom = lerp(1.0, 1.16, in_out(seg(t, S[8], S[8] + 0.9)))
|
||||
pop = 1 + 0.16 * clamp(1 - since / 0.25) if index else 1.0
|
||||
pop *= 1 + 0.1 * clamp(1 - abs(t - warm_t - 0.08) / 0.2)
|
||||
cx, cyc = (CX, CY - 330) if VERT else (CX - 330, CY + 10)
|
||||
put_pet(img, t, "cat", stage, cx, cyc, 600 * zoom * pop * (1 - 0.3 * leave), 1 - leave, sad=cold)
|
||||
for i in (1, 2, 3):
|
||||
burst(img, cx, cyc, t, marks[i], seed=20 + i, n=26, power=480, life=0.9)
|
||||
burst(img, cx, cyc, t, warm_t + 0.02, seed=31, n=60, power=760, life=1.4)
|
||||
# the right side: the days, the name of the age, four dots
|
||||
show = seg(t, a + 0.3, a + 0.7) * (1 - leave)
|
||||
rx, ry = (CX, CY + 330) if VERT else (CX + 380, CY)
|
||||
if index and since < 0.5: # the number runs up to the new age
|
||||
days = int(lerp(STAGES[index - 1][1], days, out_cubic(since / 0.5)))
|
||||
number = "%d" % days
|
||||
text(img, (rx, ry - 120), number, 230, "black", (190, 190, 198) if cold else INK, "mm", alpha=show)
|
||||
text(img, (rx, ry + 30), "дней серии" if days != 1 else "день серии", 44, "semi", GREY, "mm", alpha=show)
|
||||
for i in range(4):
|
||||
on = i <= index
|
||||
put_c(img, disc(26, (190, 190, 198) if cold and on else PINK if on else (228, 228, 234)), rx - 75 + i * 50, ry + 110,
|
||||
(1 + 0.5 * clamp(1 - since / 0.25)) if i == index else 1.0, show)
|
||||
if cold:
|
||||
pill(img, rx, ry + 210, "Серия вот-вот сгорит", fill=(236, 236, 240), color=(110, 110, 120), size=34,
|
||||
scale=out_back(seg(t, cold_t, cold_t + 0.3)), alpha=show)
|
||||
elif t >= warm_t:
|
||||
pill(img, rx, ry + 210, "v Серия продлена", fill=(226, 247, 232), color=(40, 140, 80), size=34,
|
||||
scale=out_back(seg(t, warm_t, warm_t + 0.3)), alpha=show)
|
||||
else:
|
||||
pill(img, rx, ry + 210, name, fill=INK, size=34, scale=0.85 + 0.15 * out_back(clamp(since / 0.3)), alpha=show)
|
||||
|
||||
|
||||
def scene_chat(img, t):
|
||||
"""An invented chat with no names and no words: the animal sits in it and the cursor carries it to the other side. Three big lines."""
|
||||
a, b = S[12], S[14]
|
||||
if t < a - 0.1 or t > b + 0.2:
|
||||
return
|
||||
step = (b - a) / 3
|
||||
come = out_cubic(seg(t, a - 0.1, a + 0.5))
|
||||
gone = in_out(seg(t, b - 0.25, b + 0.15))
|
||||
w, h = 560, 860
|
||||
px = CX if VERT else CX - 440
|
||||
py = (CY - 290 if VERT else CY) + (1 - come) * (1500 if VERT else 900) + gone * (-1700 if VERT else 1000)
|
||||
put_c(img, card(w, h, 60, (255, 255, 255), blur=44, dy=22, alpha=56), px, py)
|
||||
left, top = px - w // 2, py - h // 2
|
||||
put(img, disc(72, (222, 232, 255)), left + 40, top + 36)
|
||||
put(img, rr(170, 20, 10, (226, 226, 232)), left + 130, top + 50)
|
||||
pill(img, left + w - 100, top + 72, "30 дней", fill=(255, 236, 214), color=(220, 110, 30), size=24)
|
||||
put(img, rr(w - 80, 2, 1, (238, 238, 242)), left + 40, top + 130)
|
||||
rows = [(0, 300), (0, 220), (1, 260), (0, 340), (1, 180)]
|
||||
for i, (mine, bw) in enumerate(rows):
|
||||
k = out_back(seg(t, a + 0.25 + i * 0.09, a + 0.6 + i * 0.09), 1.2)
|
||||
if k <= 0:
|
||||
continue
|
||||
fill = VIOLET if mine else (240, 240, 243)
|
||||
bx = left + w - 40 - bw if mine else left + 40
|
||||
by = top + 160 + i * 86
|
||||
bubble = rr(bw, 62, 28, fill)
|
||||
put_c(img, bubble, bx + bw / 2, by + 31, k, clamp(k))
|
||||
if k > 0.9:
|
||||
put(img, rr(bw - 70, 12, 6, (255, 255, 255) if mine else (206, 206, 214)), bx + 35, by + 25, 0.9 if mine else 1.0)
|
||||
# the animal: sits on the left, is taken on the second line and carried to the right
|
||||
take, drop = a + step, a + step + 0.9
|
||||
k = in_out(seg(t, take, drop))
|
||||
ax = lerp(left + 120, left + w - 120, k)
|
||||
ay = top + h - 135 - math.sin(k * math.pi) * 90
|
||||
put_pet(img, t, "cat", "adult", ax, ay, 210 * out_back(seg(t, a + 0.5, a + 0.9)) * (1 + 0.08 * math.sin(k * math.pi)), angle=-10 * math.sin(k * math.pi))
|
||||
ck = in_out(seg(t, take - 0.7, take))
|
||||
away = in_out(seg(t, drop + 0.1, drop + 0.6))
|
||||
cx = lerp(lerp(left + w + 200, left + 130, ck), left + w + 260, away) if k in (0, 1) else ax + 10
|
||||
cy = lerp(lerp(top + h + 60, top + h - 130, ck), top + h + 80, away) if k in (0, 1) else ay + 20
|
||||
if k == 1 and away == 0:
|
||||
cx, cy = ax + 10, ay + 20
|
||||
put_c(img, cursor_sprite(), cx + 10, cy + 16, 1.0, seg(t, take - 0.7, take - 0.5) * (1 - seg(t, drop + 0.4, drop + 0.6)) * (1 - gone))
|
||||
# the three lines
|
||||
lines = ["Живёт в вашем чате", "Его можно таскать", "Растёт вместе с серией"]
|
||||
for i, line in enumerate(lines):
|
||||
t0 = a + i * step
|
||||
k = out_cubic(seg(t, t0, t0 + 0.35))
|
||||
fade = (1 - gone) * (1.0 if t < t0 + step or i == 2 else 0.28)
|
||||
if VERT:
|
||||
text(img, (CX, CY + 300 + i * 130 + (1 - k) * 40), line, 72, "bold", INK, "mm", alpha=k * fade)
|
||||
else:
|
||||
text(img, (CX - 60, CY - 150 + i * 150 + (1 - k) * 40), line, 84, "bold", INK, "lm", alpha=k * fade)
|
||||
|
||||
|
||||
def scene_title(img, t):
|
||||
"""The title: LihonT 3 in black, LUNA in candy letters; then the logo."""
|
||||
a = S[14] + 0.1
|
||||
if t < a:
|
||||
return
|
||||
logo_t = S[15]
|
||||
k1 = 1 - seg(t, logo_t - 0.1, logo_t + 0.3)
|
||||
if VERT:
|
||||
text(img, (CX, CY - 330), "LihonT 3", 170, "semi", INK, "mm", alpha=out_cubic(seg(t, a, a + 0.4)) * k1)
|
||||
V.candy_text(img, CX, CY - 130, "LUNA", 200, t, a + 0.25, 0.09, alpha=k1)
|
||||
text(img, (CX, CY + 60), "pre-alpha", 46, "semi", GREY, "mm", alpha=out_cubic(seg(t, a + 0.9, a + 1.3)) * k1)
|
||||
text(img, (CX, CY + 125), "у Серийчика появились звери", 46, "reg", GREY, "mm", alpha=out_cubic(seg(t, a + 1.0, a + 1.4)) * k1)
|
||||
row_y, gap, side, logo, logo_size, cap_y = CY + 380, 290, 270, (CX, CY - 130), 560, CY + 300
|
||||
else:
|
||||
text(img, (680, 450), "LihonT 3", 150, "semi", INK, "mm", alpha=out_cubic(seg(t, a, a + 0.4)) * k1)
|
||||
V.candy_text(img, 1270, 450, "LUNA", 150, t, a + 0.25, 0.09, alpha=k1)
|
||||
text(img, (960, 620), "pre-alpha · у Серийчика появились звери", 40, "reg", GREY, "mm", alpha=out_cubic(seg(t, a + 0.9, a + 1.3)) * k1)
|
||||
row_y, gap, side, logo, logo_size, cap_y = 830, 230, 210, (960, 470), 420, 770
|
||||
for i, kind in enumerate(("cat", "dog", "lion")):
|
||||
k = out_back(seg(t, a + 0.7 + i * 0.12, a + 1.1 + i * 0.12), 2.0)
|
||||
put_pet(img, t, kind, "cub", CX + (i - 1) * gap, row_y + (1 - k) * 40, side * k, k1)
|
||||
if t >= logo_t - 0.05:
|
||||
flower = Image.open(V.ROOT / "src" / "brand" / "logo_note_flower_gold_1024.png").convert("RGBA")
|
||||
k = out_back(seg(t, logo_t, logo_t + 0.6), 1.5)
|
||||
put_c(img, flower.resize((logo_size, logo_size), Image.Resampling.LANCZOS), logo[0], logo[1], k, clamp(k * 1.5))
|
||||
text(img, (CX, cap_y), "lihont.space · t.me/lihont", 38, "semi", GREY, "mm", alpha=seg(t, logo_t + 0.5, logo_t + 0.9))
|
||||
burst(img, logo[0], logo[1], t, logo_t + 0.1, seed=11, n=50, power=700, life=1.4)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the whole picture
|
||||
|
||||
def frame_at(t: float) -> Image.Image:
|
||||
img = Image.new("RGBA", (W, H), (255, 255, 255, 255))
|
||||
for scene in (scene_link, scene_gift, scene_kinds, scene_grow, scene_chat, scene_title):
|
||||
scene(img, t)
|
||||
fade_in = clamp(t / 0.25)
|
||||
if fade_in < 1:
|
||||
img.alpha_composite(Image.new("RGBA", (W, H), (255, 255, 255, int(255 * (1 - fade_in)))))
|
||||
return img
|
||||
|
||||
|
||||
def render_frame(index: int) -> bytes:
|
||||
return frame_at(index / FPS).convert("RGB").tobytes()
|
||||
|
||||
|
||||
def _init(song: str, vertical: bool = False) -> None:
|
||||
global S
|
||||
V.configure(song)
|
||||
set_format(vertical)
|
||||
S = V.S
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--song", default="store")
|
||||
parser.add_argument("--still", type=float, nargs="*")
|
||||
parser.add_argument("--sheet", action="store_true")
|
||||
parser.add_argument("--vertical", action="store_true", help="9:16 (1080x1920)")
|
||||
parser.add_argument("--jobs", type=int, default=6)
|
||||
args = parser.parse_args()
|
||||
_init(args.song, args.vertical)
|
||||
tag = "_9x16" if args.vertical else ""
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
prepare()
|
||||
if args.still:
|
||||
for t in args.still:
|
||||
path = OUT_DIR / ("still%s_%05.2f.png" % (tag, t))
|
||||
frame_at(t).convert("RGB").save(path)
|
||||
print(path)
|
||||
return
|
||||
if args.sheet:
|
||||
count, cols = 36, 6
|
||||
tw, th = (216, 384) if args.vertical else (480, 270)
|
||||
cols = 9 if args.vertical else 6
|
||||
out = Image.new("RGB", (cols * (tw + 4), (count // cols) * (th + 4)), (200, 200, 205))
|
||||
for i in range(count):
|
||||
thumb = frame_at(V.DURATION * (i + 0.5) / count).convert("RGB").resize((tw, th), Image.Resampling.LANCZOS)
|
||||
out.paste(thumb, ((i % cols) * (tw + 4) + 2, (i // cols) * (th + 4) + 2))
|
||||
out.save(OUT_DIR / ("sheet%s.png" % tag))
|
||||
print(OUT_DIR / ("sheet%s.png" % tag))
|
||||
return
|
||||
out = OUT_DIR / ("lihont3_pets%s.mp4" % tag)
|
||||
command = [shutil.which("ffmpeg") or "ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "%dx%d" % (W, H),
|
||||
"-r", str(FPS), "-i", "-", "-i", str(V.SONG), "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p",
|
||||
"-af", "afade=t=out:st=%.2f:d=0.6" % (V.DURATION - 0.6), "-c:a", "aac", "-b:a", "192k", "-t", "%.2f" % V.DURATION, str(out)]
|
||||
proc = subprocess.Popen(command, stdin=subprocess.PIPE)
|
||||
with Pool(args.jobs, initializer=_init, initargs=(args.song, args.vertical)) as pool:
|
||||
for n, data in enumerate(pool.imap(render_frame, range(V.FRAMES), chunksize=4)):
|
||||
proc.stdin.write(data)
|
||||
if n % 120 == 0:
|
||||
print("frame %d/%d" % (n, V.FRAMES), flush=True)
|
||||
proc.stdin.close()
|
||||
proc.wait()
|
||||
print("done:", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
252
scripts/make_store_cards.py
Normal file
@@ -0,0 +1,252 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Cards for the Telegram post about LihonT 2 · Serena and LihonT Store: eight pictures of 1080x1920, each drawn on purpose as a card of its own
|
||||
(not a frame cut from the video), in the same light style as scripts/make_store_video.py (white ground, rounded picture tiles with soft
|
||||
shadows, one violet accent, glossy "candy" letters). Only our own material: avatars with frames from scripts/frame_render.py, pictures
|
||||
drawn by the video script, invented names.
|
||||
|
||||
py -X utf8 -B scripts/make_store_cards.py # work/store-cards/card_1_hero.png ...
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import make_store_video as V # noqa: E402
|
||||
|
||||
V.set_format(True)
|
||||
W, H, CX = V.W, V.H, V.CX
|
||||
OUT = V.ROOT / "work" / "store-cards"
|
||||
VIOLET, INK, GREY, GOLD = V.VIOLET, V.INK, V.GREY, V.GOLD
|
||||
LATE = 100.0 # a time long after the letters have popped in: the candy text stands still
|
||||
|
||||
|
||||
def canvas() -> Image.Image:
|
||||
return Image.new("RGBA", (W, H), (255, 255, 255, 255))
|
||||
|
||||
|
||||
def petals(img, seed, n, box, avoid=(), colors=None):
|
||||
"""A few flowers and dots lying about, so that the card is not bare (fixed positions, nothing moves); never over the `avoid` boxes."""
|
||||
rng = random.Random(seed)
|
||||
colors = colors or V.FLOWERS
|
||||
x0, y0, x1, y1 = box
|
||||
for i in range(n):
|
||||
x, y, size = rng.uniform(x0, x1), rng.uniform(y0, y1), rng.randint(14, 26)
|
||||
if any(a0 - 40 <= x <= a2 + 40 and b0 - 40 <= y <= b2 + 40 for a0, b0, a2, b2 in avoid):
|
||||
continue
|
||||
col = colors[i % len(colors)]
|
||||
if i % 3 == 0:
|
||||
for p in range(5):
|
||||
a = p / 5 * math.tau + i
|
||||
V.put_c(img, V.disc(size, col), x + math.cos(a) * size * 0.7, y + math.sin(a) * size * 0.7)
|
||||
V.put_c(img, V.disc(size, (255, 235, 150)), x, y, 0.8)
|
||||
else:
|
||||
V.put_c(img, V.disc(size // 2 + 4, col), x, y)
|
||||
|
||||
|
||||
def footer(img):
|
||||
flower = Image.open(V.ROOT / "src" / "brand" / "logo_note_flower_gold_1024.png").convert("RGBA").resize((86, 86), Image.Resampling.LANCZOS)
|
||||
V.put_c(img, flower, CX - 190, H - 96)
|
||||
V.text(img, (CX - 130, H - 94), "LihonT 2 · Serena", 38, "semi", GREY, "lm")
|
||||
|
||||
|
||||
def head(img, title, sub=None, y=230, size=88):
|
||||
lines = title.split("\n")
|
||||
for i, line in enumerate(lines):
|
||||
V.text(img, (CX, y + i * (size + 10)), line, size, "semi", INK, "mm")
|
||||
if sub:
|
||||
V.text(img, (CX, y + len(lines) * (size + 10) + 20), sub, 42, "reg", GREY, "mm")
|
||||
|
||||
|
||||
def tile_card(img, index, size, cx, cy, angle=0.0, cat=False):
|
||||
V.put_c(img, V.card(size, size, int(size * 0.1), blur=30, dy=14, alpha=44), cx, cy, 1.0, 1.0, angle)
|
||||
V.put_c(img, V.tile(index, size, cat), cx, cy, 1.0, 1.0, angle)
|
||||
|
||||
|
||||
def segmented(img, cy, labels, active):
|
||||
w = 280
|
||||
total = w * len(labels)
|
||||
V.put_c(img, V.rr(total + 12, 84, 42, (240, 240, 244)), CX, cy)
|
||||
for i, label in enumerate(labels):
|
||||
x = CX - total / 2 + w * (i + 0.5)
|
||||
if i == active:
|
||||
V.put_c(img, V.rr(w - 6, 72, 36, VIOLET), x, cy)
|
||||
V.text(img, (x, cy - 1), label, 32, "semi", (255, 255, 255) if i == active else GREY, "mm")
|
||||
|
||||
|
||||
def card_hero():
|
||||
img = canvas()
|
||||
petals(img, 1, 26, (60, 80, W - 60, H - 160))
|
||||
flower = Image.open(V.ROOT / "src" / "brand" / "logo_note_flower_gold_1024.png").convert("RGBA").resize((560, 560), Image.Resampling.LANCZOS)
|
||||
V.put_c(img, V.soft_shadow(300, 300, 150, blur=60, dy=40, alpha=40), CX, 640)
|
||||
V.put_c(img, flower, CX, 620)
|
||||
V.text(img, (CX, 1040), "LihonT 2", 170, "semi", INK, "mm")
|
||||
V.candy_text(img, CX, 1230, "SERENA", 190, LATE, 0.0, 0.0)
|
||||
V.text(img, (CX, 1450), "мод для TikTok с открытым кодом", 46, "reg", GREY, "mm")
|
||||
V.pill(img, CX, 1580, "рамки · пузыри · каталог", VIOLET, (255, 255, 255), 36)
|
||||
footer(img)
|
||||
return img
|
||||
|
||||
|
||||
def card_store():
|
||||
img = canvas()
|
||||
petals(img, 2, 22, (40, 60, W - 40, 640), avoid=[(250, 160, 830, 600)])
|
||||
V.text(img, (CX, 230), "LihonT", 130, "semi", INK, "mm")
|
||||
V.candy_text(img, CX, 400, "STORE", 170, LATE, 0.0, 0.0)
|
||||
V.text(img, (CX, 560), "каталог рамок и пузырей от людей", 44, "reg", GREY, "mm")
|
||||
segmented(img, 690, ["Рамки", "Пузыри чата"], 0)
|
||||
for n, (i, x, y, a) in enumerate([(1, 300, 1010, -2), (3, 780, 1010, 2), (5, 300, 1470, 1.5), (9, 780, 1470, -1.5)]):
|
||||
tile_card(img, i, 420, x, y, a)
|
||||
V.pill(img, 300, 1190, "+ Добавить", (24, 24, 28), (255, 255, 255), 30)
|
||||
V.pill(img, 780, 1650, "v Добавлено", VIOLET, (255, 255, 255), 30)
|
||||
footer(img)
|
||||
return img
|
||||
|
||||
|
||||
def arrow(img, cx, cy, w=130):
|
||||
layer = Image.new("RGBA", (w + 40, 120), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(layer)
|
||||
d.line([(20, 60), (w + 5, 60)], fill=VIOLET + (255,), width=14)
|
||||
d.line([(w - 30, 25), (w + 10, 60), (w - 30, 95)], fill=VIOLET + (255,), width=14, joint="curve")
|
||||
V.put_c(img, layer, cx, cy)
|
||||
|
||||
|
||||
def card_ring():
|
||||
img = canvas()
|
||||
head(img, "Любая картинка\nстанет рамкой", "фото само вырежется в кольцо вокруг аватарки")
|
||||
petals(img, 3, 18, (40, 700, W - 40, 1500), avoid=[(60, 760, 1020, 1160), (60, 1290, 1020, 1430)])
|
||||
pic = V.mask_round(V.sunset(330), 40)
|
||||
V.put_c(img, V.soft_shadow(330, 330, 40, blur=50, dy=30, alpha=60), 290, 900)
|
||||
V.put_c(img, pic, 290, 900, 1.0, 1.0, -4)
|
||||
arrow(img, 540, 900)
|
||||
V.put_c(img, V.soft_shadow(250, 250, 125, blur=40, dy=24, alpha=50), 805, 900)
|
||||
V.put_c(img, V.avatar(250), 805, 900)
|
||||
V.put_c(img, V.ring_of(325), 805, 900)
|
||||
V.pill(img, 290, 1130, "ваше фото", (240, 240, 244), GREY, 30)
|
||||
V.pill(img, 805, 1130, "рамка на аватарке", VIOLET, (255, 255, 255), 30)
|
||||
V.text(img, (CX, 1330), "Выберите картинку: мод вырежет кольцо,", 42, "reg", GREY, "mm")
|
||||
V.text(img, (CX, 1392), "а аватарка останется в середине.", 42, "reg", GREY, "mm")
|
||||
for n, i in enumerate([0, 2, 4]):
|
||||
tile_card(img, i, 230, 220 + n * 320, 1620, (n - 1) * 3)
|
||||
footer(img)
|
||||
return img
|
||||
|
||||
|
||||
def card_shapes():
|
||||
img = canvas()
|
||||
head(img, "Рамка повторяет\nформу аватарки", "круг, цветочек, сердечко, шестиугольник")
|
||||
names = ["Круг", "Цветочек", "Сердечко", "Шестиугольник", "Квадрат", "Треугольник"]
|
||||
for n, (i, label) in enumerate(zip([0, 1, 3, 5, 7, 9], names)):
|
||||
x, y = 300 + (n % 2) * 480, 800 + (n // 2) * 330
|
||||
tile_card(img, i, 280, x, y, ((n % 3) - 1) * 2)
|
||||
V.text(img, (x, y + 180), label, 30, "semi", GREY, "mm")
|
||||
footer(img)
|
||||
return img
|
||||
|
||||
|
||||
def card_bubbles():
|
||||
img = canvas()
|
||||
head(img, "Пузыри чата\nс вашими картинками", "их видят и у вас, и у друга с модом")
|
||||
cx, cy = CX, 1010
|
||||
V.put_c(img, V.card(940, 1000, 52), cx, cy)
|
||||
V.text(img, (cx, cy - 430), "Чат", 36, "semi", GREY, "mm")
|
||||
V.put_c(img, V.rr(600, 104, 40, (238, 238, 242)), cx - 150, cy - 300)
|
||||
V.text(img, (cx - 150, cy - 301), "Привет! Как тебе мой пузырь?", 30, "reg", INK, "mm")
|
||||
for k, (idx, label, x, y, w) in enumerate([(0, "Он виден и у меня, и у тебя", cx + 110, cy - 130, 640), (1, "У меня тоже есть мод", cx - 140, cy + 60, 560),
|
||||
(3, "Круто, поставлю себе!", cx + 110, cy + 230, 600)]):
|
||||
V.put_c(img, V.mask_round(V.bubble_picture(idx, w, 112), 48), x, y)
|
||||
V.text(img, (x, y + 2), label, 30, "bold", (0, 0, 0), "mm", alpha=0.22)
|
||||
V.text(img, (x, y - 1), label, 30, "bold", (255, 255, 255), "mm")
|
||||
V.pill(img, cx, cy + 400, "Пузырь «Закат» из магазина", (24, 24, 28), (255, 255, 255), 28)
|
||||
petals(img, 5, 10, (40, 520, W - 40, 560))
|
||||
footer(img)
|
||||
return img
|
||||
|
||||
|
||||
def card_publish():
|
||||
img = canvas()
|
||||
head(img, "Публикуй\nсвои работы", "рамки и пузыри, сначала проверка, потом каталог")
|
||||
cx, cy = CX, 1000
|
||||
V.put_c(img, V.card(940, 800, 48), cx, cy)
|
||||
V.text(img, (cx - 400, cy - 340), "Новая рамка", 40, "bold", INK, "lm")
|
||||
V.put_c(img, V.rr(820, 460, 34, (240, 234, 255), VIOLET, 3), cx, cy - 60)
|
||||
V.put_c(img, V.disc(190, VIOLET), cx, cy - 110)
|
||||
V.draw_check(img, cx, cy - 110, 90, 1.0, (255, 255, 255), 16)
|
||||
V.text(img, (cx, cy + 40), "Готово", 44, "bold", INK, "mm")
|
||||
V.put_c(img, V.rr(260, 80, 40, (240, 240, 244)), cx - 300, cy + 290)
|
||||
V.text(img, (cx - 300, cy + 289), "Выбрать файл", 30, "semi", INK, "mm")
|
||||
V.put_c(img, V.rr(300, 80, 40, VIOLET), cx + 290, cy + 290)
|
||||
V.text(img, (cx + 290, cy + 289), "Опубликовать", 30, "semi", (255, 255, 255), "mm")
|
||||
V.pill(img, cx, cy + 500, "v отправлено на проверку", VIOLET, (255, 255, 255), 32)
|
||||
V.put_c(img, V.soft_shadow(200, 200, 30, blur=40, dy=24, alpha=50), 210, 1690)
|
||||
V.put_c(img, V.mask_round(V.sunset(200), 30), 210, 1690, 1.0, 1.0, -6)
|
||||
petals(img, 6, 14, (380, 1640, W - 40, 1790))
|
||||
footer(img)
|
||||
return img
|
||||
|
||||
|
||||
def card_profile():
|
||||
img = canvas()
|
||||
V.text(img, (CX, 200), "Профили авторов", 80, "semi", INK, "mm")
|
||||
V.text(img, (CX, 285), "нажмите на ник под карточкой и увидите все работы", 38, "reg", GREY, "mm")
|
||||
V.put_c(img, V.soft_shadow(270, 270, 135, blur=40, dy=24, alpha=50), CX, 560)
|
||||
V.put_c(img, V.avatar(270), CX, 560)
|
||||
V.put_c(img, V.ring_of(351), CX, 560)
|
||||
V.text(img, (CX, 800), "@your_nickname", 60, "bold", INK, "mm")
|
||||
V.pill(img, CX - 300, 890, "12 рамок", (240, 240, 244), INK, 32)
|
||||
V.pill(img, CX - 30, 890, "5 пузырей", (240, 240, 244), INK, 32)
|
||||
V.pill(img, CX + 275, 890, "1 204 добавили", VIOLET, (255, 255, 255), 32)
|
||||
segmented(img, 1030, ["Опубликовано", "Проверка", "Библиотека"], 0)
|
||||
for i, x, y in [(0, 300, 1330), (4, 780, 1330), (6, 300, 1700), (8, 780, 1700)]:
|
||||
tile_card(img, i, 340, x, y, 0)
|
||||
petals(img, 7, 12, (40, 1100, W - 40, 1200))
|
||||
return img
|
||||
|
||||
|
||||
def card_install():
|
||||
img = canvas()
|
||||
head(img, "Как поставить", "мод и магазин ставятся отдельно")
|
||||
steps = [("Нет мода: удалите TikTok", "у мода другая подпись, поверх не встанет"),
|
||||
("Поставьте мод LihonT 2 · Serena", "кто уже с модом: просто поверх старой версии"),
|
||||
("Поставьте LihonT Store", "и войдите через TikTok, пароль не нужен")]
|
||||
for n, (a, b) in enumerate(steps):
|
||||
y = 700 + n * 300
|
||||
V.put_c(img, V.card(900, 230, 50, blur=26, dy=12, alpha=40), CX, y)
|
||||
V.put_c(img, V.disc(110, VIOLET), 200, y)
|
||||
V.text(img, (200, y - 3), str(n + 1), 66, "bold", (255, 255, 255), "mm")
|
||||
V.text(img, (300, y - 32), a, 40, "bold", INK, "lm")
|
||||
V.text(img, (300, y + 36), b, 30, "reg", GREY, "lm")
|
||||
V.text(img, (CX, 1640), "git.lihont.space/lihont", 46, "semi", INK, "mm")
|
||||
V.text(img, (CX, 1710), "t.me/lihont", 42, "reg", GREY, "mm")
|
||||
petals(img, 8, 14, (40, 1560, W - 40, 1780), avoid=[(150, 1600, 930, 1750)])
|
||||
footer(img)
|
||||
return img
|
||||
|
||||
|
||||
CARDS = [("1_hero", card_hero), ("2_store", card_store), ("3_ring", card_ring), ("4_shapes", card_shapes), ("5_bubbles", card_bubbles),
|
||||
("6_publish", card_publish), ("7_profile", card_profile), ("8_install", card_install)]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
for name, make in CARDS:
|
||||
path = OUT / ("card_%s.png" % name)
|
||||
make().convert("RGB").save(path)
|
||||
print(path)
|
||||
# a contact sheet to look at all of them at once
|
||||
sheet = Image.new("RGB", (4 * 360 + 10, 2 * 640 + 4), (190, 190, 195))
|
||||
for i, (name, _) in enumerate(CARDS):
|
||||
im = Image.open(OUT / ("card_%s.png" % name)).resize((360, 640), Image.Resampling.LANCZOS)
|
||||
sheet.paste(im, ((i % 4) * 362, (i // 4) * 642))
|
||||
sheet.save(OUT / "sheet.png")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
374
scripts/make_store_music.py
Normal file
@@ -0,0 +1,374 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
An original soundtrack for the LihonT Store video, made of nothing but sine waves, noise and filters (numpy and scipy), so that it is ours.
|
||||
Playful and bright, in A major, 120 beats a minute with eighth notes: mallet plucks and a bell hook over a soft kick, clap and hats, a
|
||||
round bass and a warm pad. On top of it small sound effects fall exactly on the events of the video (the cursor clicks, the picture
|
||||
drops into the window, a ding on the check mark, the window whooshes down, the tiles turn into a cat, the letters of the title pop).
|
||||
|
||||
It writes work/music/store.wav and store.mp3 and store.beats.json (the same format scripts/analyze_beats.py makes), so that the video script
|
||||
takes its beats from it: a bar every 2 s, the strong beats at 1, 3, 5 ... 31 s.
|
||||
|
||||
py -X utf8 -B scripts/make_store_music.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import shutil
|
||||
import subprocess
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from scipy.signal import butter, fftconvolve, sosfilt
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "work" / "music"
|
||||
SR = 44100
|
||||
BPM = 120
|
||||
BEAT = 60.0 / BPM
|
||||
BAR = 4 * BEAT
|
||||
FIRST_BAR = 1.0 # the first strong beat
|
||||
BARS = 16
|
||||
DURATION = 33.0
|
||||
RNG = np.random.default_rng(7)
|
||||
|
||||
|
||||
def midi(n):
|
||||
return 440.0 * 2 ** ((n - 69) / 12)
|
||||
|
||||
|
||||
def tt(d):
|
||||
return np.arange(int(d * SR)) / SR
|
||||
|
||||
|
||||
def lp(x, f, order=2):
|
||||
return sosfilt(butter(order, f, "low", fs=SR, output="sos"), x)
|
||||
|
||||
|
||||
def hp(x, f, order=2):
|
||||
return sosfilt(butter(order, f, "high", fs=SR, output="sos"), x)
|
||||
|
||||
|
||||
def bp(x, lo, hi, order=2):
|
||||
return sosfilt(butter(order, [lo, hi], "band", fs=SR, output="sos"), x)
|
||||
|
||||
|
||||
def attack(x, ms=3.0):
|
||||
n = max(1, int(SR * ms / 1000))
|
||||
x = x.copy()
|
||||
x[:n] *= np.linspace(0, 1, n)
|
||||
return x
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- instruments
|
||||
|
||||
def mallet(f, d=0.9):
|
||||
t = tt(d)
|
||||
s = np.sin(2 * math.pi * f * t + 1.6 * np.exp(-10 * t) * np.sin(2 * math.pi * f * 2 * t)) * np.exp(-4.5 * t)
|
||||
s += 0.3 * np.sin(2 * math.pi * f * 4 * t) * np.exp(-16 * t)
|
||||
return attack(s * 0.8)
|
||||
|
||||
|
||||
def bell(f, d=2.4):
|
||||
t = tt(d)
|
||||
s = np.zeros_like(t)
|
||||
for ratio, amp, decay in ((1, 1.0, 1.5), (2.0, 0.5, 2.2), (2.76, 0.4, 3.0), (5.4, 0.22, 4.5), (8.9, 0.1, 7.0)):
|
||||
s += amp * np.sin(2 * math.pi * f * ratio * t) * np.exp(-decay * t)
|
||||
return attack(s * 0.5, 4)
|
||||
|
||||
|
||||
def pad(freqs, d):
|
||||
t = tt(d)
|
||||
s = np.zeros_like(t)
|
||||
for f in freqs:
|
||||
for detune in (0.997, 1.003):
|
||||
for k in range(1, 6):
|
||||
s += np.sin(2 * math.pi * f * detune * k * t) / k
|
||||
s = lp(s, 1500)
|
||||
rise = np.minimum(1, t / 0.35)
|
||||
fall = np.minimum(1, (d - t) / 0.4)
|
||||
return s * rise * fall * 0.035
|
||||
|
||||
|
||||
def bass(f, d=0.42):
|
||||
t = tt(d)
|
||||
s = np.sin(2 * math.pi * f * t) + 0.35 * np.sin(2 * math.pi * f * 2 * t)
|
||||
s = np.tanh(1.8 * s) * np.exp(-3.2 * t)
|
||||
return attack(lp(s, 600) * 0.7, 6)
|
||||
|
||||
|
||||
def kick():
|
||||
t = tt(0.45)
|
||||
f = 46 + 90 * np.exp(-t * 38)
|
||||
ph = 2 * math.pi * np.cumsum(f) / SR
|
||||
s = np.sin(ph) * np.exp(-t * 9)
|
||||
s += 0.3 * hp(RNG.standard_normal(len(t)), 3000) * np.exp(-t * 140)
|
||||
return attack(s * 0.95, 1)
|
||||
|
||||
|
||||
def clap():
|
||||
t = tt(0.3)
|
||||
s = np.zeros_like(t)
|
||||
for o in (0, 0.011, 0.022):
|
||||
i = int(o * SR)
|
||||
s[i:] += RNG.standard_normal(len(t) - i) * np.exp(-(t[: len(t) - i]) * 60)
|
||||
s += RNG.standard_normal(len(t)) * np.exp(-t * 16) * 0.4
|
||||
return bp(s, 900, 4500) * 0.55
|
||||
|
||||
|
||||
def hat(open_=False):
|
||||
t = tt(0.22 if open_ else 0.06)
|
||||
return hp(RNG.standard_normal(len(t)), 7000) * np.exp(-t * (14 if open_ else 70)) * 0.35
|
||||
|
||||
|
||||
def tick(f=2200.0):
|
||||
t = tt(0.05)
|
||||
s = hp(RNG.standard_normal(len(t)), 2500) * np.exp(-t * 160) + 0.5 * np.sin(2 * math.pi * f * t) * np.exp(-t * 90)
|
||||
return s * 0.6
|
||||
|
||||
|
||||
def pop(f0=950.0, f1=260.0, d=0.12):
|
||||
t = tt(d)
|
||||
ph = 2 * math.pi * np.cumsum(f1 + (f0 - f1) * np.exp(-t * 45)) / SR
|
||||
return attack(np.sin(ph) * np.exp(-t * 26) * 0.8, 1)
|
||||
|
||||
|
||||
def blup(f0=420.0, f1=900.0, d=0.18):
|
||||
t = tt(d)
|
||||
ph = 2 * math.pi * np.cumsum(f0 + (f1 - f0) * (t / d) ** 0.7) / SR
|
||||
return attack(np.sin(ph) * np.exp(-t * 17) * 0.7, 2)
|
||||
|
||||
|
||||
def whoosh(d=0.8, up=True):
|
||||
t = tt(d)
|
||||
noise = RNG.standard_normal(len(t))
|
||||
out = np.zeros_like(t)
|
||||
bands = [(300, 900), (700, 2200), (1800, 5200), (4000, 9000)]
|
||||
centre = np.linspace(0, 1, len(bands))
|
||||
pos = (t / d) if up else (1 - t / d)
|
||||
for b, (lo, hi) in enumerate(bands):
|
||||
w = np.exp(-((pos - centre[b]) ** 2) / 0.05)
|
||||
out += bp(noise, lo, hi) * w
|
||||
env = np.sin(np.pi * np.clip(t / d, 0, 1)) ** 1.5
|
||||
return out * env * 0.5
|
||||
|
||||
|
||||
def riser(d=0.9):
|
||||
t = tt(d)
|
||||
noise = hp(RNG.standard_normal(len(t)), 1800) * (t / d) ** 2
|
||||
tone = np.sin(2 * math.pi * np.cumsum(220 + 880 * (t / d) ** 2) / SR) * (t / d) ** 1.5 * 0.25
|
||||
return (noise * 0.35 + tone) * np.minimum(1, (d - t) / 0.03 + 0.0)
|
||||
|
||||
|
||||
def boing(d=0.35):
|
||||
t = tt(d)
|
||||
f = 280 + 520 * np.sin(np.pi * np.clip(t / d, 0, 1)) ** 0.8
|
||||
ph = 2 * math.pi * np.cumsum(f * (1 + 0.02 * np.sin(2 * math.pi * 24 * t))) / SR
|
||||
return attack(np.sin(ph) * np.exp(-t * 6) * 0.7, 2)
|
||||
|
||||
|
||||
def meow(d=0.5):
|
||||
"""A short, soft mew: a gliding saw through a formant-ish band, rising and then falling."""
|
||||
t = tt(d)
|
||||
f = 520 + 380 * np.sin(np.pi * np.clip(t / d * 0.9, 0, 1)) - 140 * (t / d)
|
||||
ph = np.cumsum(f) / SR
|
||||
saw = 2 * (ph % 1) - 1
|
||||
s = bp(saw, 700, 2600, 2) * np.sin(np.pi * np.clip(t / d, 0, 1)) ** 0.8
|
||||
return attack(s * 0.9, 12)
|
||||
|
||||
|
||||
def sparkle(d=1.3, n=9, lo=84, seed=0):
|
||||
r = np.random.default_rng(seed)
|
||||
out = np.zeros(int(d * SR))
|
||||
for i in range(n):
|
||||
note = bell(midi(lo + int(r.choice([0, 2, 4, 7, 9, 12]))), 0.7) * 0.28
|
||||
o = int(r.uniform(0, d * 0.7) * SR)
|
||||
m = min(len(note), len(out) - o)
|
||||
out[o:o + m] += note[:m]
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the mix
|
||||
|
||||
class Mix:
|
||||
def __init__(self, seconds):
|
||||
self.n = int(seconds * SR)
|
||||
self.left = np.zeros(self.n)
|
||||
self.right = np.zeros(self.n)
|
||||
self.send = np.zeros(self.n)
|
||||
self.duck_times = []
|
||||
|
||||
def add(self, sig, t0, gain=1.0, pan=0.0, send=0.0, bus=None):
|
||||
i = int(t0 * SR)
|
||||
if i >= self.n or i + len(sig) <= 0:
|
||||
return
|
||||
lo = max(0, -i)
|
||||
hi = min(len(sig), self.n - i)
|
||||
piece = sig[lo:hi] * gain
|
||||
a = (pan + 1) * math.pi / 4
|
||||
self.left[i + lo:i + hi] += piece * math.cos(a)
|
||||
self.right[i + lo:i + hi] += piece * math.sin(a)
|
||||
if send:
|
||||
self.send[i + lo:i + hi] += piece * send
|
||||
|
||||
|
||||
def build() -> np.ndarray:
|
||||
m = Mix(DURATION + 1.0)
|
||||
bars = [FIRST_BAR + BAR * b for b in range(BARS)]
|
||||
chords = [[57, 61, 64], [52, 56, 59], [54, 57, 61], [50, 54, 57]] # A, E, F#m, D (low triads)
|
||||
roots = [45, 40, 42, 38]
|
||||
hook = [[76, None, 73, 76, 78, None, 76, None], [73, None, 71, 73, 76, None, 73, None],
|
||||
[73, 76, 78, None, 76, 73, 71, None], [69, None, 71, 73, 74, None, 73, 71]]
|
||||
# which layers play in which bar (see the scenes of the video)
|
||||
layers = {
|
||||
0: "pad arp", 1: "pad arp kick hat", 2: "pad arp kick hat bass", 3: "pad arp kick hat bass clap hook",
|
||||
4: "pad arp kick hat bass clap hook", 5: "pad arp kick hat bass clap hook", 6: "pad arp kick hat bass clap hook",
|
||||
7: "pad arp kick hat bass clap hook", 8: "pad arp kick hat bass clap hook", 9: "pad arp kick hat bass clap hook",
|
||||
10: "pad arp kick hat bass clap hook", 11: "pad arp kick hat bass clap hook", 12: "pad arp bass hook",
|
||||
13: "pad arp bass hat roll", 14: "pad arp kick hat bass hook", 15: "pad arp",
|
||||
}
|
||||
kicks = []
|
||||
# a rising swell before the first bar
|
||||
m.add(riser(FIRST_BAR) * 0.5, 0.0, 0.5, send=0.2)
|
||||
for b, t0 in enumerate(bars):
|
||||
L = layers[b].split()
|
||||
c = b % 4
|
||||
tones = chords[c]
|
||||
if "pad" in L:
|
||||
notes = [midi(n + 12) for n in tones] + [midi(tones[0])]
|
||||
m.add(pad(notes, BAR + 0.5), t0 - 0.05, 1.0, send=0.25)
|
||||
if "arp" in L:
|
||||
for k in range(8):
|
||||
idx = [0, 1, 2, 1, 0, 1, 2, 1][k]
|
||||
n = tones[idx] + 24 + (12 if idx == 2 else 0)
|
||||
soft = 0.34 if b < 3 or b in (12, 15) else 0.42
|
||||
m.add(mallet(midi(n), 0.55), t0 + k * BEAT / 2, soft, pan=-0.35 + 0.1 * (k % 2), send=0.22)
|
||||
if "hook" in L:
|
||||
for k, n in enumerate(hook[c]):
|
||||
if n is not None:
|
||||
m.add(bell(midi(n + 12), 1.3), t0 + k * BEAT / 2, 0.30 if b != 12 else 0.2, pan=0.3, send=0.4)
|
||||
if "bass" in L:
|
||||
for k in (0, 3, 4, 6):
|
||||
m.add(bass(midi(roots[c])), t0 + k * BEAT / 2, 0.6 if b != 12 else 0.4)
|
||||
for beat in range(4):
|
||||
tb = t0 + beat * BEAT
|
||||
if "kick" in L and beat in (0, 2):
|
||||
m.add(kick(), tb, 0.95)
|
||||
kicks.append(tb)
|
||||
if "kick" in L and beat == 3 and b % 2 == 1:
|
||||
m.add(kick(), tb + BEAT / 2, 0.7)
|
||||
kicks.append(tb + BEAT / 2)
|
||||
if "clap" in L and beat in (1, 3):
|
||||
m.add(clap(), tb, 0.75, pan=0.1, send=0.3)
|
||||
if "hat" in L:
|
||||
for k in range(8):
|
||||
m.add(hat(k == 7), t0 + k * BEAT / 2, 0.9 if k % 2 else 0.55, pan=0.25)
|
||||
if "roll" in L: # a build before the title
|
||||
for k in range(16):
|
||||
m.add(hat(), t0 + k * BEAT / 4, 0.25 + 0.5 * k / 16, pan=0.2)
|
||||
for k in range(8):
|
||||
m.add(clap(), t0 + BAR + k * BEAT / 4 - 1.0 + 0.0, 0.0)
|
||||
|
||||
# ---- sound effects on the events of the video (their times are the same as in scripts/make_store_video.py)
|
||||
S = [FIRST_BAR + BAR * k for k in range(16)]
|
||||
sfx = lambda sig, t0, g=0.8, pan=0.0, send=0.15: m.add(sig, t0, g, pan, send)
|
||||
sfx(tick(), S[1], 0.9) # the click on the button
|
||||
sfx(pop(700, 300, 0.1), S[1] + 0.2, 0.5, send=0.2)
|
||||
sfx(whoosh(0.5, True), S[1] + 0.2, 0.35, 0.3) # the window grows
|
||||
sfx(tick(1800), S[1] + 1.25, 0.9) # the picture is taken
|
||||
sfx(whoosh(0.7, True), S[1] + 1.4, 0.3, -0.2) # the drag
|
||||
sfx(pop(), S[2], 0.9, send=0.3) # the drop
|
||||
sfx(kick(), S[2] + 0.02, 0.6)
|
||||
for i, tp in enumerate(np.arange(S[2] + 0.4, S[3] - 0.15, 0.13)): # the upload ticks, rising
|
||||
sfx(mallet(midi(72 + (i % 8) * 2), 0.18), float(tp), 0.18, 0.4, 0.2)
|
||||
sfx(bell(midi(88), 1.8), S[3], 0.5, 0.0, 0.5) # the ding of the check mark
|
||||
sfx(bell(midi(95), 1.4), S[3] + 0.08, 0.35, 0.2, 0.5)
|
||||
sfx(sparkle(1.4, 10, 86, 1), S[3] + 0.1, 0.7, 0.0, 0.4)
|
||||
sfx(whoosh(0.8, False), S[3] + 0.5, 0.45, 0.0) # the window slides down
|
||||
sfx(pop(1100, 330, 0.14), S[3] + 0.9, 0.9, send=0.3) # the avatar pops
|
||||
sfx(sparkle(1.3, 12, 84, 2), S[3] + 0.95, 0.8, 0.0, 0.4)
|
||||
sfx(bell(midi(81), 1.6), S[4], 0.45, 0.0, 0.5)
|
||||
sfx(whoosh(1.0, True), S[4] + 0.5, 0.4, 0.2) # the tiles come in
|
||||
for k in range(3):
|
||||
sfx(tick(2500 + 300 * k), S[4] + 0.7 + 0.22 * k, 0.4, -0.4 + 0.4 * k)
|
||||
sfx(whoosh(0.5, True), S[7] - 0.15, 0.55, 0.0) # the tiles gather
|
||||
sfx(kick(), S[7], 0.9)
|
||||
sfx(boing(), S[7] + 0.3, 0.7, 0.0, 0.2) # ... and turn into a cat
|
||||
sfx(meow(), S[7] + 0.45, 0.7, 0.1, 0.3)
|
||||
sfx(sparkle(1.0, 8, 88, 3), S[7] + 0.3, 0.6, 0.0, 0.4)
|
||||
sfx(riser(0.9), S[8] - 0.1, 0.7) # the camera flies in
|
||||
sfx(tick(2000), S[8] + 1.0, 0.9) # "+ add"
|
||||
sfx(bell(midi(88), 1.4), S[8] + 1.02, 0.5, 0.0, 0.5)
|
||||
sfx(bell(midi(95), 1.2), S[8] + 1.1, 0.3, 0.2, 0.5)
|
||||
for k, s in enumerate((S[9], S[10], S[11])): # the bubble pictures change on every beat
|
||||
sfx(blup(), s + 0.05, 0.8, -0.3 + 0.3 * k, 0.25)
|
||||
sfx(pop(900, 300, 0.1), s + 0.0, 0.5, 0.2)
|
||||
sfx(sparkle(1.6, 14, 84, 4), S[11] + 0.02, 0.8, 0.0, 0.4)
|
||||
for k in range(3): # the three lines
|
||||
t0 = S[12] + k * (S[14] - S[12]) / 3
|
||||
for i in range(4):
|
||||
sfx(mallet(midi(76 + [0, 4, 2, 7][i]), 0.4), t0 + i * 0.11, 0.32, -0.2 + 0.15 * i, 0.3)
|
||||
sfx(riser(0.9), S[14] - 0.9, 0.7)
|
||||
sfx(bell(midi(69), 2.2), S[14] + 0.1, 0.5, -0.2, 0.5) # LihonT
|
||||
for i, n in enumerate([76, 78, 80, 81, 83]): # S T O R E
|
||||
sfx(mallet(midi(n), 0.6), S[14] + 0.35 + i * 0.09, 0.55, -0.3 + 0.15 * i, 0.4)
|
||||
sfx(bell(midi(n + 12), 0.9), S[14] + 0.35 + i * 0.09, 0.2, 0.0, 0.5)
|
||||
sfx(sparkle(1.8, 16, 86, 5), S[15], 0.9, 0.0, 0.4) # the logo
|
||||
for n in (57, 61, 64, 69):
|
||||
sfx(bell(midi(n + 12), 2.6), S[15] + 0.02, 0.28, 0.0, 0.6)
|
||||
sfx(kick(), S[15], 0.7)
|
||||
|
||||
# ---- the pad and the plucks breathe with the kick (a light sidechain)
|
||||
n = m.n
|
||||
duck = np.ones(n)
|
||||
for tk in kicks:
|
||||
i = int(tk * SR)
|
||||
seg = min(int(0.28 * SR), n - i)
|
||||
if seg > 0:
|
||||
duck[i:i + seg] = np.minimum(duck[i:i + seg], 1 - 0.28 * np.exp(-np.arange(seg) / SR / 0.09))
|
||||
# reverb on the send bus (a different tail for each ear)
|
||||
ir_len = int(1.5 * SR)
|
||||
tail = np.exp(-np.arange(ir_len) / SR * 3.2)
|
||||
irl = bp(RNG.standard_normal(ir_len), 250, 7500) * tail
|
||||
irr = bp(RNG.standard_normal(ir_len), 250, 7500) * tail
|
||||
wet_l = fftconvolve(m.send, irl)[:n] * 0.035
|
||||
wet_r = fftconvolve(m.send, irr)[:n] * 0.035
|
||||
left = m.left * duck + wet_l
|
||||
right = m.right * duck + wet_r
|
||||
out = np.stack([left, right], axis=1)
|
||||
out = np.tanh(out * 0.8)
|
||||
out[: int(0.01 * SR)] *= np.linspace(0, 1, int(0.01 * SR))[:, None]
|
||||
out = out[: int(DURATION * SR)]
|
||||
fade = int(1.4 * SR)
|
||||
out[-fade:] *= np.linspace(1, 0, fade)[:, None] ** 1.5
|
||||
out /= max(1e-9, np.abs(out).max()) / 0.8
|
||||
return out.astype(np.float32)
|
||||
|
||||
|
||||
def write(path: Path, data: np.ndarray) -> None:
|
||||
pcm = (data * 32767).astype("<i2")
|
||||
with wave.open(str(path), "wb") as f:
|
||||
f.setnchannels(2)
|
||||
f.setsampwidth(2)
|
||||
f.setframerate(SR)
|
||||
f.writeframes(pcm.tobytes())
|
||||
|
||||
|
||||
def main() -> None:
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
audio = build()
|
||||
wav = OUT / "store.wav"
|
||||
write(wav, audio)
|
||||
mp3 = OUT / "store.mp3"
|
||||
subprocess.run([shutil.which("ffmpeg") or "ffmpeg", "-y", "-loglevel", "error", "-i", str(wav), "-c:a", "libmp3lame", "-b:a", "224k", str(mp3)], check=True)
|
||||
beats = [round(i * BEAT, 3) for i in range(int(DURATION / BEAT))]
|
||||
strong = [round(FIRST_BAR + BAR * k, 3) for k in range(BARS)]
|
||||
(OUT / "store.beats.json").write_text(json.dumps({"tempo": BPM, "duration": DURATION, "beats": beats, "strong_beats": strong}), encoding="utf-8")
|
||||
print("wrote", mp3, "| peak %.2f | rms %.3f" % (float(np.abs(audio).max()), float(np.sqrt((audio ** 2).mean()))))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
836
scripts/make_store_video.py
Normal file
@@ -0,0 +1,836 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
LihonT Store: a promo video in the style of OpenAI's product videos (white ground, one pill bar that types, rounded picture tiles
|
||||
with soft shadows that glide, fan out and zoom, confetti, glossy "candy" letters, the logo at the end). The scenes are laid on the strong
|
||||
beats of a song (work/music/<song>.mp3 and <song>.beats.json, made by scripts/analyze_beats.py).
|
||||
|
||||
Only our own material is shown: avatars with frames drawn by scripts/frame_render.py (work/serena-promo/beat-cache), pictures drawn here,
|
||||
invented names. The style is only a reference: nothing of another video is copied.
|
||||
|
||||
The key scene: a cursor drags a picture into a window, it uploads, a check is drawn, the window slides down and an avatar appears with
|
||||
that very picture cut into a ring as its frame.
|
||||
|
||||
py -X utf8 -B scripts/make_store_video.py # work/store-video/store_openai.mp4
|
||||
py -X utf8 -B scripts/make_store_video.py --still 7.5 # one frame as a picture
|
||||
py -X utf8 -B scripts/make_store_video.py --sheet # a contact sheet of the whole video
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import shutil
|
||||
import subprocess
|
||||
from functools import lru_cache
|
||||
from multiprocessing import Pool
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT_DIR = ROOT / "work" / "store-video"
|
||||
CACHE = ROOT / "work" / "serena-promo" / "beat-cache"
|
||||
W, H, FPS = 1920, 1080, 30
|
||||
VERT = False
|
||||
CX, CY = W // 2, H // 2
|
||||
|
||||
|
||||
def set_format(vertical: bool) -> None:
|
||||
"""Landscape 1920x1080 (the default) or portrait 1080x1920: the scenes read the size and the middle from here."""
|
||||
global W, H, VERT, CX, CY
|
||||
VERT = bool(vertical)
|
||||
W, H = (1080, 1920) if VERT else (1920, 1080)
|
||||
CX, CY = W // 2, H // 2
|
||||
|
||||
INK = (24, 24, 28)
|
||||
GREY = (118, 118, 126)
|
||||
SOFT = (240, 240, 243)
|
||||
VIOLET = (122, 79, 208)
|
||||
VIOLET_DARK = (92, 56, 168)
|
||||
GOLD = (238, 190, 107)
|
||||
PASTELS = [(255, 226, 214), (222, 232, 255), (226, 247, 232), (255, 240, 200), (240, 224, 255), (255, 224, 240)]
|
||||
FLOWERS = [(255, 120, 160), (255, 170, 80), (120, 190, 255), (160, 120, 255), (90, 210, 150), (255, 210, 90)]
|
||||
|
||||
FONTS = {"reg": "segoeui.ttf", "semi": "seguisb.ttf", "bold": "segoeuib.ttf", "black": "seguibl.ttf"}
|
||||
|
||||
# filled by configure()
|
||||
SONG = None
|
||||
S: list = []
|
||||
DURATION = 0.0
|
||||
FRAMES = 0
|
||||
|
||||
|
||||
def configure(name: str) -> None:
|
||||
global SONG, S, DURATION, FRAMES
|
||||
SONG = ROOT / "work" / "music" / (name + ".mp3")
|
||||
data = json.loads(SONG.with_suffix(".beats.json").read_text(encoding="utf-8"))
|
||||
S = data["strong_beats"]
|
||||
DURATION = round(data["duration"], 2)
|
||||
FRAMES = int(round(DURATION * FPS))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- maths and easing
|
||||
|
||||
def clamp(x, lo=0.0, hi=1.0):
|
||||
return max(lo, min(hi, x))
|
||||
|
||||
|
||||
def lerp(a, b, k):
|
||||
return a + (b - a) * k
|
||||
|
||||
|
||||
def seg(t, a, b):
|
||||
return clamp((t - a) / (b - a)) if b > a else (1.0 if t >= a else 0.0)
|
||||
|
||||
|
||||
def out_cubic(x):
|
||||
return 1 - (1 - clamp(x)) ** 3
|
||||
|
||||
|
||||
def in_cubic(x):
|
||||
return clamp(x) ** 3
|
||||
|
||||
|
||||
def in_out(x):
|
||||
x = clamp(x)
|
||||
return 4 * x ** 3 if x < 0.5 else 1 - (-2 * x + 2) ** 3 / 2
|
||||
|
||||
|
||||
def out_back(x, s=1.7):
|
||||
x = clamp(x)
|
||||
return 1 + (s + 1) * (x - 1) ** 3 + s * (x - 1) ** 2
|
||||
|
||||
|
||||
def out_expo(x):
|
||||
x = clamp(x)
|
||||
return 1.0 if x >= 1 else 1 - 2 ** (-10 * x)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- drawing helpers
|
||||
|
||||
@lru_cache(maxsize=64)
|
||||
def font(size: int, weight: str = "reg") -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype("C:/Windows/Fonts/" + FONTS[weight], int(size))
|
||||
|
||||
|
||||
def put(img, sprite, x, y, alpha=1.0):
|
||||
"""Composites a sprite with its top-left corner at (x, y), clipped to the picture, with an overall opacity."""
|
||||
x, y = int(round(x)), int(round(y))
|
||||
if alpha < 0.999:
|
||||
sprite = sprite.copy()
|
||||
a = sprite.getchannel("A").point(lambda v: int(v * alpha))
|
||||
sprite.putalpha(a)
|
||||
left, top = max(0, -x), max(0, -y)
|
||||
right, bottom = min(sprite.width, img.width - x), min(sprite.height, img.height - y)
|
||||
if right <= left or bottom <= top:
|
||||
return
|
||||
img.alpha_composite(sprite.crop((left, top, right, bottom)), (x + left, y + top))
|
||||
|
||||
|
||||
def put_c(img, sprite, cx, cy, scale=1.0, alpha=1.0, angle=0.0):
|
||||
"""The same with the sprite's centre at (cx, cy), optionally scaled and turned."""
|
||||
if scale <= 0.01 or alpha <= 0.003:
|
||||
return
|
||||
if abs(scale - 1.0) > 0.003:
|
||||
sprite = sprite.resize((max(1, int(sprite.width * scale)), max(1, int(sprite.height * scale))), Image.Resampling.BICUBIC)
|
||||
if abs(angle) > 0.05:
|
||||
sprite = sprite.rotate(angle, resample=Image.Resampling.BICUBIC, expand=True)
|
||||
put(img, sprite, cx - sprite.width / 2, cy - sprite.height / 2, alpha)
|
||||
|
||||
|
||||
def text(img, xy, s, size, weight="reg", fill=INK, anchor="mm", alpha=1.0):
|
||||
if alpha <= 0.003 or not s:
|
||||
return
|
||||
f = font(size, weight)
|
||||
box = ImageDraw.Draw(Image.new("L", (1, 1))).textbbox((0, 0), s, font=f, anchor="lt")
|
||||
pad = 6
|
||||
layer = Image.new("RGBA", (box[2] + 2 * pad, box[3] + 2 * pad + 8), (0, 0, 0, 0))
|
||||
ImageDraw.Draw(layer).text((pad, pad), s, font=f, fill=tuple(fill) + (255,), anchor="lt")
|
||||
w, h = layer.size
|
||||
x, y = xy
|
||||
x -= {"l": 0, "m": w / 2, "r": w}[anchor[0]] - (0 if anchor[0] == "l" else 0)
|
||||
y -= {"t": 0, "m": h / 2, "b": h}[anchor[1]] if anchor[1] in "tmb" else h / 2
|
||||
put(img, layer, x - (pad if anchor[0] == "l" else 0), y, alpha)
|
||||
|
||||
|
||||
@lru_cache(maxsize=512)
|
||||
def rr(w, h, r, fill, outline=None, ow=0):
|
||||
"""An anti-aliased rounded rectangle (drawn three times as large and scaled down)."""
|
||||
k = 3
|
||||
layer = Image.new("RGBA", (w * k, h * k), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(layer)
|
||||
d.rounded_rectangle([0, 0, w * k - 1, h * k - 1], radius=r * k, fill=tuple(fill) + (255,) if fill else None,
|
||||
outline=tuple(outline) + (255,) if outline else None, width=ow * k)
|
||||
return layer.resize((w, h), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def disc(d, fill):
|
||||
k = 3
|
||||
layer = Image.new("RGBA", (d * k, d * k), (0, 0, 0, 0))
|
||||
ImageDraw.Draw(layer).ellipse([0, 0, d * k - 1, d * k - 1], fill=tuple(fill) + (255,))
|
||||
return layer.resize((d, d), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
@lru_cache(maxsize=128)
|
||||
def card(w, h, r, fill=(255, 255, 255), blur=34, dy=16, alpha=48):
|
||||
"""A rounded card with a soft shadow; the sprite is larger than the card by the shadow's reach."""
|
||||
pad = blur * 2
|
||||
layer = Image.new("RGBA", (w + 2 * pad, h + 2 * pad), (0, 0, 0, 0))
|
||||
shadow = Image.new("RGBA", layer.size, (0, 0, 0, 0))
|
||||
ImageDraw.Draw(shadow).rounded_rectangle([pad, pad + dy, pad + w, pad + h + dy], radius=r, fill=(20, 20, 40, alpha))
|
||||
layer.alpha_composite(shadow.filter(ImageFilter.GaussianBlur(blur / 2)))
|
||||
layer.alpha_composite(rr(w, h, r, fill), (pad, pad))
|
||||
return layer
|
||||
|
||||
|
||||
@lru_cache(maxsize=64)
|
||||
def soft_shadow(w, h, r, blur=40, dy=22, alpha=70):
|
||||
pad = int(blur) * 2
|
||||
shadow = Image.new("RGBA", (w + 2 * pad, h + 2 * pad), (0, 0, 0, 0))
|
||||
ImageDraw.Draw(shadow).rounded_rectangle([pad, pad + dy, pad + w, pad + h + dy], radius=r, fill=(20, 20, 40, alpha))
|
||||
return shadow.filter(ImageFilter.GaussianBlur(blur / 2))
|
||||
|
||||
|
||||
def mask_round(img: Image.Image, r: int) -> Image.Image:
|
||||
k = 3
|
||||
m = Image.new("L", (img.width * k, img.height * k), 0)
|
||||
ImageDraw.Draw(m).rounded_rectangle([0, 0, img.width * k - 1, img.height * k - 1], radius=r * k, fill=255)
|
||||
out = img.convert("RGBA")
|
||||
out.putalpha(ImageChops.multiply(out.getchannel("A"), m.resize(img.size, Image.Resampling.LANCZOS)))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- pictures drawn here
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def sunset(size: int) -> Image.Image:
|
||||
"""The picture that is dragged in: a sunset with hills and a flower, made of nothing but gradients."""
|
||||
img = Image.new("RGB", (size, size))
|
||||
px = img.load()
|
||||
top, mid, low = (96, 82, 214), (255, 112, 140), (255, 190, 100)
|
||||
for y in range(size):
|
||||
v = y / size
|
||||
c = tuple(int(lerp(top[i], mid[i], v / 0.6)) for i in range(3)) if v < 0.6 else tuple(int(lerp(mid[i], low[i], (v - 0.6) / 0.4)) for i in range(3))
|
||||
for x in range(size):
|
||||
px[x, y] = c
|
||||
d = ImageDraw.Draw(img, "RGBA")
|
||||
sun = size * 0.18
|
||||
d.ellipse([size * 0.5 - sun, size * 0.52 - sun, size * 0.5 + sun, size * 0.52 + sun], fill=(255, 244, 200, 255))
|
||||
for i, (col, base, amp) in enumerate([((120, 70, 170), 0.70, 0.07), ((78, 44, 132), 0.80, 0.06), ((44, 26, 90), 0.90, 0.05)]):
|
||||
pts = [(0, size)]
|
||||
for x in range(0, size + 1, 8):
|
||||
pts.append((x, size * base + math.sin(x / size * (3 + i) + i) * size * amp))
|
||||
pts.append((size, size))
|
||||
d.polygon(pts, fill=col + (255,))
|
||||
for n in range(14): # petals over the first hill: a flower in the corner
|
||||
a = n / 14 * math.tau
|
||||
cx, cy = size * 0.22 + math.cos(a) * size * 0.07, size * 0.74 + math.sin(a) * size * 0.07
|
||||
d.ellipse([cx - size * 0.035, cy - size * 0.035, cx + size * 0.035, cy + size * 0.035], fill=(255, 232, 240, 255))
|
||||
d.ellipse([size * 0.22 - size * 0.03, size * 0.74 - size * 0.03, size * 0.22 + size * 0.03, size * 0.74 + size * 0.03], fill=(255, 190, 70, 255))
|
||||
return img.convert("RGBA")
|
||||
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def ring_of(size: int) -> Image.Image:
|
||||
"""The sunset cut into a ring, as the app does: the avatar fills the middle 1/1.3 of the picture."""
|
||||
art = sunset(size).copy()
|
||||
k = 3
|
||||
m = Image.new("L", (size * k, size * k), 0)
|
||||
dm = ImageDraw.Draw(m)
|
||||
outer, inner = size * k / 2 - k, size * k / 1.3 / 2 * 0.96
|
||||
dm.ellipse([size * k / 2 - outer, size * k / 2 - outer, size * k / 2 + outer, size * k / 2 + outer], fill=255)
|
||||
dm.ellipse([size * k / 2 - inner, size * k / 2 - inner, size * k / 2 + inner, size * k / 2 + inner], fill=0)
|
||||
art.putalpha(m.resize((size, size), Image.Resampling.LANCZOS))
|
||||
return art
|
||||
|
||||
|
||||
@lru_cache(maxsize=32)
|
||||
def avatar(d: int) -> Image.Image:
|
||||
"""A plain avatar: a soft disc with a person in it."""
|
||||
k = 3
|
||||
layer = Image.new("RGBA", (d * k, d * k), (0, 0, 0, 0))
|
||||
g = ImageDraw.Draw(layer)
|
||||
g.ellipse([0, 0, d * k - 1, d * k - 1], fill=(228, 224, 238, 255))
|
||||
g.ellipse([d * k * 0.34, d * k * 0.20, d * k * 0.66, d * k * 0.52], fill=(255, 255, 255, 255))
|
||||
g.ellipse([d * k * 0.18, d * k * 0.56, d * k * 0.82, d * k * 1.18], fill=(255, 255, 255, 255))
|
||||
clip = Image.new("L", layer.size, 0)
|
||||
ImageDraw.Draw(clip).ellipse([0, 0, d * k - 1, d * k - 1], fill=255)
|
||||
layer.putalpha(ImageChops.multiply(layer.getchannel("A"), clip))
|
||||
return layer.resize((d, d), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
ART_NAMES = ["basic.cat", "cat-on-flower", "basic.crown", "cat-on-heart", "basic.flame", "cat-on-hexagon", "basic.flower", "cat-on-squircle",
|
||||
"basic.helmet", "cat-on-triangle"]
|
||||
|
||||
|
||||
@lru_cache(maxsize=32)
|
||||
def art(name: str) -> Image.Image:
|
||||
return Image.open(CACHE / (name + ".png")).convert("RGBA")
|
||||
|
||||
|
||||
@lru_cache(maxsize=128)
|
||||
def tile(index: int, size: int, cat: bool = False) -> Image.Image:
|
||||
"""A rounded picture tile: a pastel ground with an avatar in a frame (our own art), like the pictures of a product video.
|
||||
The art is cut to its real outline and fitted with a margin, so that petals, ears and crowns are never cropped by the tile.
|
||||
With `cat` the tile of the same colour shows the cat frame (what the tiles turn into when they gather)."""
|
||||
name = "basic.cat" if cat else ART_NAMES[index % len(ART_NAMES)]
|
||||
source = art(name)
|
||||
shown = source.crop(source.getchannel("A").getbbox())
|
||||
k = size * 0.78 / max(shown.size)
|
||||
shown = shown.resize((max(1, int(shown.width * k)), max(1, int(shown.height * k))), Image.Resampling.LANCZOS)
|
||||
ground = Image.new("RGBA", (size, size), PASTELS[index % len(PASTELS)] + (255,))
|
||||
ground.alpha_composite(shown, ((size - shown.width) // 2, (size - shown.height) // 2))
|
||||
return mask_round(ground, int(size * 0.1))
|
||||
|
||||
|
||||
@lru_cache(maxsize=32)
|
||||
def bubble_picture(index: int, w: int, h: int) -> Image.Image:
|
||||
"""Chat-bubble backgrounds drawn from gradients, stripes and stars."""
|
||||
rng = random.Random(index * 77 + 5)
|
||||
pairs = [((255, 140, 190), (160, 110, 255)), ((90, 210, 160), (60, 150, 230)), ((255, 190, 90), (255, 110, 130)), ((110, 170, 255), (190, 130, 255))]
|
||||
c1, c2 = pairs[index % len(pairs)]
|
||||
img = Image.new("RGBA", (w, h))
|
||||
px = img.load()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
v = (x / w * 0.6 + y / h * 0.4)
|
||||
px[x, y] = tuple(int(lerp(c1[i], c2[i], v)) for i in range(3)) + (255,)
|
||||
d = ImageDraw.Draw(img, "RGBA")
|
||||
kind = index % 4
|
||||
for _ in range(14):
|
||||
x, y, r = rng.randint(0, w), rng.randint(0, h), rng.randint(4, 14)
|
||||
if kind == 0:
|
||||
d.ellipse([x - r, y - r, x + r, y + r], fill=(255, 255, 255, 46))
|
||||
elif kind == 1:
|
||||
d.line([x - 30, y + 30, x + 30, y - 30], fill=(255, 255, 255, 34), width=6)
|
||||
elif kind == 2 and rng.random() < 0.45:
|
||||
d.polygon([(x, y - r * 1.6), (x + r * 0.5, y - r * 0.4), (x + r * 1.6, y), (x + r * 0.5, y + r * 0.4), (x, y + r * 1.6), (x - r * 0.5, y + r * 0.4), (x - r * 1.6, y), (x - r * 0.5, y - r * 0.4)], fill=(255, 255, 255, 90))
|
||||
elif kind == 3:
|
||||
d.arc([x - 40, y - 20, x + 40, y + 20], 0, 180, fill=(255, 255, 255, 50), width=5)
|
||||
return img
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- small pieces of interface
|
||||
|
||||
@lru_cache(maxsize=8)
|
||||
def cursor_sprite() -> Image.Image:
|
||||
k = 4
|
||||
pts = [(0, 0), (0, 29), (8, 22), (14, 35), (20, 32), (14, 20), (25, 20)]
|
||||
big = Image.new("RGBA", (40 * k, 48 * k), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(big)
|
||||
d.polygon([(x * k + 6 * k, y * k + 4 * k) for x, y in pts], fill=(255, 255, 255, 255), outline=(255, 255, 255, 255), width=5 * k)
|
||||
d.polygon([(x * k + 6 * k, y * k + 4 * k) for x, y in pts], fill=(18, 18, 20, 255))
|
||||
out = big.resize((40, 48), Image.Resampling.LANCZOS)
|
||||
sh = Image.new("RGBA", (64, 72), (0, 0, 0, 0))
|
||||
sh.alpha_composite(out.filter(ImageFilter.GaussianBlur(3)).point(lambda v: v * 0.5 if v < 255 else v), (10, 14))
|
||||
sh.alpha_composite(out, (8, 8))
|
||||
return sh
|
||||
|
||||
|
||||
def check_path(cx, cy, size, k):
|
||||
"""Points of a check mark drawn from its start to k (0..1) of its length."""
|
||||
p = [(cx - size * 0.5, cy + size * 0.02), (cx - size * 0.14, cy + size * 0.38), (cx + size * 0.52, cy - size * 0.36)]
|
||||
lengths = [math.dist(p[0], p[1]), math.dist(p[1], p[2])]
|
||||
run = k * sum(lengths)
|
||||
out = [p[0]]
|
||||
for i in range(2):
|
||||
if run >= lengths[i]:
|
||||
out.append(p[i + 1])
|
||||
run -= lengths[i]
|
||||
else:
|
||||
f = run / lengths[i]
|
||||
out.append((lerp(p[i][0], p[i + 1][0], f), lerp(p[i][1], p[i + 1][1], f)))
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def draw_check(img, cx, cy, size, k, color=(255, 255, 255), width=18):
|
||||
big = Image.new("RGBA", (int(size * 1.6) * 3, int(size * 1.6) * 3), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(big)
|
||||
ox, oy = big.width / 2, big.height / 2
|
||||
pts = [((x - cx) * 3 + ox, (y - cy) * 3 + oy) for x, y in check_path(cx, cy, size, k)]
|
||||
d.line(pts, fill=tuple(color) + (255,), width=width * 3, joint="curve")
|
||||
for x, y in (pts[0], pts[-1]):
|
||||
d.ellipse([x - width * 1.5, y - width * 1.5, x + width * 1.5, y + width * 1.5], fill=tuple(color) + (255,))
|
||||
small = big.resize((big.width // 3, big.height // 3), Image.Resampling.LANCZOS)
|
||||
put(img, small, cx - small.width / 2, cy - small.height / 2)
|
||||
|
||||
|
||||
def burst(img, cx, cy, t, t0, seed=1, n=40, power=520, life=1.1, colors=None):
|
||||
"""Confetti: little circles and flowers thrown from a point, falling back."""
|
||||
rng = random.Random(seed)
|
||||
colors = colors or FLOWERS
|
||||
age = t - t0
|
||||
if age < 0 or age > life:
|
||||
return
|
||||
for i in range(n):
|
||||
a = rng.uniform(0, math.tau)
|
||||
v = rng.uniform(0.35, 1.0) * power
|
||||
size = rng.randint(8, 20)
|
||||
col = colors[i % len(colors)]
|
||||
x = cx + math.cos(a) * v * out_cubic(age / life) * 0.9
|
||||
y = cy + math.sin(a) * v * out_cubic(age / life) * 0.9 + 380 * age * age
|
||||
k = 1 - clamp(age / life) ** 2
|
||||
if i % 3 == 0:
|
||||
for p in range(5):
|
||||
pa = p / 5 * math.tau + age * 3
|
||||
put_c(img, disc(size, col), x + math.cos(pa) * size * 0.7, y + math.sin(pa) * size * 0.7, 1.0, k)
|
||||
put_c(img, disc(size, (255, 235, 150)), x, y, 0.8, k)
|
||||
else:
|
||||
put_c(img, disc(size, col), x, y, 1.0, k)
|
||||
|
||||
|
||||
def ripple(img, cx, cy, t, t0, color=(120, 80, 210), maxr=70):
|
||||
age = t - t0
|
||||
if 0 <= age <= 0.5:
|
||||
k = age / 0.5
|
||||
d = int(maxr * 2 * out_cubic(k))
|
||||
if d > 4:
|
||||
layer = Image.new("RGBA", (d + 8, d + 8), (0, 0, 0, 0))
|
||||
ImageDraw.Draw(layer).ellipse([4, 4, d + 4, d + 4], outline=tuple(color) + (int(180 * (1 - k)),), width=6)
|
||||
put(img, layer, cx - layer.width / 2, cy - layer.height / 2)
|
||||
|
||||
|
||||
def pill(img, cx, cy, s, fill=(32, 32, 36), color=(255, 255, 255), size=26, alpha=1.0, scale=1.0, weight="semi"):
|
||||
"""A small rounded label; a leading "v " is drawn as a check mark (the font has no such glyph)."""
|
||||
mark = s.startswith("v ")
|
||||
s = s[2:] if mark else s
|
||||
f = font(size, weight)
|
||||
tw = int(ImageDraw.Draw(Image.new("L", (1, 1))).textlength(s, font=f))
|
||||
extra = int(size * 1.1) if mark else 0
|
||||
w = tw + extra + int(size * 1.7)
|
||||
h = int(size * 1.9)
|
||||
layer = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
||||
layer.alpha_composite(rr(w, h, h // 2, fill))
|
||||
ImageDraw.Draw(layer).text((w / 2 + extra / 2, h / 2 - 1), s, font=f, fill=tuple(color) + (255,), anchor="mm")
|
||||
if mark:
|
||||
draw_check(layer, int(size * 1.15), h // 2, size * 0.8, 1.0, color, max(3, size // 7))
|
||||
put_c(img, layer, cx, cy, scale, alpha)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the glossy "candy" letters of the title
|
||||
|
||||
CANDY = [((255, 99, 150), (222, 40, 110)), ((120, 210, 90), (60, 160, 60)), ((255, 170, 40), (240, 110, 20)), ((90, 170, 255), (50, 110, 230)),
|
||||
((190, 120, 255), (130, 70, 220))]
|
||||
|
||||
|
||||
@lru_cache(maxsize=64)
|
||||
def candy_letter(ch: str, size: int, index: int) -> Image.Image:
|
||||
f = font(size, "black")
|
||||
box = f.getbbox(ch)
|
||||
pad = 26
|
||||
w, h = box[2] - box[0] + 2 * pad, box[3] - box[1] + 2 * pad
|
||||
mask = Image.new("L", (w, h), 0)
|
||||
ImageDraw.Draw(mask).text((pad - box[0], pad - box[1]), ch, font=f, fill=255)
|
||||
top, bottom = CANDY[index % len(CANDY)]
|
||||
body = Image.new("RGBA", (w, h))
|
||||
px = body.load()
|
||||
for y in range(h):
|
||||
v = y / h
|
||||
c = tuple(int(lerp(top[i], bottom[i], v)) for i in range(3))
|
||||
for x in range(w):
|
||||
px[x, y] = c + (255,)
|
||||
# a lighter rim on the inside, a glossy highlight on the upper part
|
||||
inner = mask.filter(ImageFilter.MinFilter(9)).filter(ImageFilter.GaussianBlur(3))
|
||||
rim = ImageChops.subtract(mask, inner)
|
||||
rim_img = Image.new("RGBA", (w, h), (255, 255, 255, 0))
|
||||
rim_img.putalpha(rim.point(lambda v: int(v * 0.55)))
|
||||
body.alpha_composite(rim_img)
|
||||
shine = Image.new("L", (w, h), 0)
|
||||
ImageDraw.Draw(shine).ellipse([w * 0.1, -h * 0.05, w * 0.9, h * 0.46], fill=150)
|
||||
shine = ImageChops.multiply(shine.filter(ImageFilter.GaussianBlur(5)), inner)
|
||||
gloss = Image.new("RGBA", (w, h), (255, 255, 255, 0))
|
||||
gloss.putalpha(shine)
|
||||
body.alpha_composite(gloss)
|
||||
body.putalpha(mask)
|
||||
out = Image.new("RGBA", (w + 10, h + 24), (0, 0, 0, 0))
|
||||
shadow = Image.new("RGBA", out.size, (0, 0, 0, 0))
|
||||
shadow.paste((40, 20, 60, 90), (5, 16), mask)
|
||||
out.alpha_composite(shadow.filter(ImageFilter.GaussianBlur(6)))
|
||||
out.alpha_composite(body, (5, 4))
|
||||
return out
|
||||
|
||||
|
||||
def candy_text(img, cx, cy, s, size, t, t0, step=0.08, alpha=1.0):
|
||||
"""Letters pop in one after another, each with a little overshoot, then bob very slightly."""
|
||||
f = font(size, "black")
|
||||
advance = [f.getlength(ch) for ch in s]
|
||||
total = sum(advance) + 4 * (len(s) - 1)
|
||||
x = cx - total / 2
|
||||
for i, ch in enumerate(s):
|
||||
age = t - (t0 + i * step)
|
||||
k = out_back(age / 0.35)
|
||||
if ch != " " and age > 0:
|
||||
letter = candy_letter(ch, size, i)
|
||||
bob = math.sin((t - t0) * 4 + i * 0.8) * 4 * seg(age, 0.4, 0.8)
|
||||
put_c(img, letter, x + advance[i] / 2, cy + bob + (1 - k) * 60, 0.6 + 0.4 * k, alpha * clamp(age / 0.12))
|
||||
x += advance[i] + 4
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- scenes
|
||||
# Times come from the strong beats: S[0] 1.14 s, S[1] 3.18 s ...
|
||||
|
||||
def scene_start(img, t):
|
||||
"""The opening: a pill button "publish your frame"; the cursor comes, clicks on the strong beat, the button opens into the window."""
|
||||
click = S[1]
|
||||
if t >= click + 0.45:
|
||||
return
|
||||
ks = 0.9 if VERT else 1.0
|
||||
intro = out_back(seg(t, 0.1, 0.7))
|
||||
gone = seg(t, click + 0.1, click + 0.45)
|
||||
press = 1 - 0.06 * clamp(1 - abs(t - click) / 0.1)
|
||||
w, h = 760, 120
|
||||
layer = Image.new("RGBA", (w + 120, h + 120), (0, 0, 0, 0))
|
||||
layer.alpha_composite(card(w, h, h // 2, (255, 255, 255), blur=30, dy=12, alpha=44))
|
||||
d = ImageDraw.Draw(layer)
|
||||
cx0, cy0 = 60 + 70, 60 + h // 2
|
||||
d.ellipse([cx0 - 38, cy0 - 38, cx0 + 38, cy0 + 38], fill=VIOLET + (255,))
|
||||
d.line([(cx0, cy0 - 15), (cx0, cy0 + 15)], fill=(255, 255, 255, 255), width=6)
|
||||
d.line([(cx0 - 15, cy0), (cx0 + 15, cy0)], fill=(255, 255, 255, 255), width=6)
|
||||
d.text((60 + 150, 60 + h // 2 - 1), "Опубликовать свою рамку", font=font(40, "semi"), fill=INK + (255,), anchor="lm")
|
||||
put_c(img, layer, CX, CY, lerp(0.9, 1.0, intro) * press * (1 + 0.25 * gone) * ks, clamp(intro * 1.3) * (1 - gone))
|
||||
ripple(img, CX + 50 * ks, CY + 20, t, click, VIOLET, 120 * ks)
|
||||
# the cursor comes from the corner to the button and stays on it
|
||||
k = in_out(seg(t, 1.0, click - 0.1))
|
||||
cx, cy = lerp(W - 120 + (0 if VERT else 0), CX + 50 * ks, k) - math.sin(k * math.pi) * 90, lerp(H + (-160 if VERT else 80), CY + 26, k)
|
||||
put_c(img, cursor_sprite(), cx + 10, cy + 16, 1.0 - 0.08 * clamp(1 - abs(t - click) / 0.1), out_cubic(seg(t, 0.9, 1.3)))
|
||||
|
||||
|
||||
def scene_upload(img, t): # noqa: C901
|
||||
"""The key scene: the cursor drags a picture into the window, it uploads, a check is drawn, the window slides down, an avatar appears."""
|
||||
t_in, t_grab, t_drop, t_done, t_down, t_avatar = S[1] + 0.25, S[1] + 1.25, S[2], S[3], S[3] + 0.55, S[3] + 0.9
|
||||
leave = S[5] - 0.6
|
||||
if t < t_in or t > leave + 0.8:
|
||||
return
|
||||
kv = 0.92 if VERT else 1.0 # the window is a little smaller on the narrow screen
|
||||
wy0 = 900 if VERT else 590
|
||||
# the window: grows out of the button, at the end it slides down
|
||||
appear = out_back(seg(t, t_in, t_in + 0.6), 1.15)
|
||||
down = in_cubic(seg(t, t_down, t_down + 0.75))
|
||||
wx, wy = CX, wy0 + down * 900
|
||||
walpha = (1 - seg(t, t_down + 0.35, t_down + 0.8))
|
||||
if walpha > 0.01:
|
||||
win = Image.new("RGBA", (1140, 840), (0, 0, 0, 0))
|
||||
lx, ly = 570, 420
|
||||
win.alpha_composite(card(1000, 700, 40), (lx - 500 - 68, ly - 350 - 68))
|
||||
text(win, (lx - 440, ly - 290), "Новая рамка", 38, "bold", INK, "lm")
|
||||
text(win, (lx + 440, ly - 290), "x", 40, "reg", GREY, "rm")
|
||||
hot = out_cubic(seg(t, t_grab + 0.55, t_drop - 0.05))
|
||||
zone_bg = tuple(int(lerp(c, z, hot)) for c, z in zip((250, 250, 252), (240, 234, 255)))
|
||||
zone_line = tuple(int(lerp(c, z, hot)) for c, z in zip((196, 196, 206), VIOLET))
|
||||
put_c(win, rr(860, 440, 30, zone_bg, zone_line, 3), lx, ly - 40, 1.0 + 0.012 * hot)
|
||||
sunk = seg(t, t_drop, t_drop + 0.35)
|
||||
if sunk < 0.05: # the empty drop zone
|
||||
fade = 1 - sunk * 4
|
||||
text(win, (lx, ly - 90), "Перетащите картинку сюда", 36, "semi", INK, "mm", alpha=fade)
|
||||
text(win, (lx, ly - 36), "PNG или JPG, фото само станет кольцом", 26, "reg", GREY, "mm", alpha=fade)
|
||||
prog = seg(t, t_drop + 0.35, t_done)
|
||||
if t_drop + 0.2 <= t < t_done:
|
||||
put_c(win, sunset(88), lx - 250, ly - 80, 1.0, out_cubic(seg(t, t_drop + 0.2, t_drop + 0.5)))
|
||||
text(win, (lx - 180, ly - 100), "sunset-flower.png", 34, "semi", INK, "lm")
|
||||
text(win, (lx - 180, ly - 58), "84 КБ", 26, "reg", GREY, "lm")
|
||||
text(win, (lx + 290, ly - 100), "%d%%" % int(prog * 100), 34, "bold", VIOLET, "rm")
|
||||
put_c(win, rr(580, 12, 6, (232, 232, 240)), lx, ly + 10)
|
||||
put(win, rr(max(12, int(580 * prog)), 12, 6, VIOLET), lx - 290, ly + 4)
|
||||
if t >= t_done:
|
||||
k = out_back(seg(t, t_done, t_done + 0.45), 2.0)
|
||||
put_c(win, disc(190, VIOLET), lx, ly - 100, k)
|
||||
draw_check(win, lx, ly - 100, 90 * k, out_cubic(seg(t, t_done + 0.1, t_done + 0.55)), (255, 255, 255), 16)
|
||||
text(win, (lx, ly + 40), "Готово", 40, "bold", INK, "mm", alpha=seg(t, t_done + 0.3, t_done + 0.6))
|
||||
ripple(win, lx, ly - 100, t, t_done, VIOLET, 150)
|
||||
put_c(win, rr(250, 76, 38, (240, 240, 244)), lx - 340, ly + 250)
|
||||
text(win, (lx - 340, ly + 249), "Выбрать файл", 28, "semi", INK, "mm")
|
||||
ready = seg(t, t_done, t_done + 0.4)
|
||||
put_c(win, rr(280, 76, 38, tuple(int(lerp(c, v, ready)) for c, v in zip((226, 222, 240), VIOLET))), lx + 330, ly + 250)
|
||||
text(win, (lx + 330, ly + 249), "Опубликовать", 28, "semi", (255, 255, 255), "mm")
|
||||
put_c(img, win, wx, wy, lerp(0.45, 1.0, appear) * kv, clamp(appear * 1.6) * walpha)
|
||||
if t >= t_done:
|
||||
burst(img, CX, wy0 - 100 * kv + down * 900, t, t_done + 0.05, seed=3, n=46, power=560)
|
||||
|
||||
# the picture and the cursor: the cursor arrives, takes the picture, drags it into the zone
|
||||
lift = clamp((t - t_grab) / 0.18) * (1 - seg(t, t_drop, t_drop + 0.15))
|
||||
src = (CX - 250, wy0 + 560) if VERT else (330, 880)
|
||||
zone_c = (CX, wy0 - 40 * kv)
|
||||
start_cursor = (CX + 50 * (0.9 if VERT else 1.0), CY + 26)
|
||||
if t < t_grab:
|
||||
k = in_out(seg(t, t_in + 0.05, t_grab))
|
||||
cur = (lerp(start_cursor[0], src[0] + 30, k) + math.sin(k * math.pi) * -120, lerp(start_cursor[1], src[1] + 40, k))
|
||||
drag = None
|
||||
else:
|
||||
k = in_out(seg(t, t_grab + 0.2, t_drop))
|
||||
cur = (lerp(src[0] + 30, zone_c[0] + 30, k), lerp(src[1] + 40, zone_c[1] + 30, k) - math.sin(k * math.pi) * 110)
|
||||
drag = k
|
||||
tile_pos = (src[0], src[1]) if t < t_grab else (cur[0] - 30, cur[1] - 40)
|
||||
if t < t_drop + 0.4:
|
||||
appear_pic = out_back(seg(t, t_in + 0.1, t_in + 0.6))
|
||||
size = int(lerp(250, 300, lift))
|
||||
pic = mask_round(sunset(size), 36)
|
||||
shadow = soft_shadow(size, size, 36, blur=int(lerp(18, 50, lift) // 4 * 4), dy=int(lerp(10, 34, lift) // 4 * 4), alpha=int(lerp(40, 84, lift) // 6 * 6))
|
||||
sink = seg(t, t_drop, t_drop + 0.35)
|
||||
sc = appear_pic * (1 - 0.75 * out_cubic(sink)) * (1 + 0.04 * lift)
|
||||
angle = 0.0 if drag is None else -8 * math.sin(clamp(drag) * math.pi) * (1 if drag < 1 else 0)
|
||||
a = 1 - seg(t, t_drop + 0.25, t_drop + 0.45)
|
||||
if t >= t_grab:
|
||||
put_c(img, shadow, tile_pos[0], tile_pos[1], sc, a * 0.9, angle)
|
||||
put_c(img, pic, tile_pos[0], tile_pos[1], sc, a, angle)
|
||||
if t < t_drop + 0.6:
|
||||
ripple(img, src[0] + 30, src[1] + 40, t, t_grab, (120, 80, 210), 60)
|
||||
c_alpha = 1.0 * (1 - seg(t, t_drop + 0.25, t_drop + 0.55))
|
||||
press = 1.0 - 0.08 * clamp(1 - abs(t - t_grab) / 0.1)
|
||||
put_c(img, cursor_sprite(), cur[0] + 10, cur[1] + 16, press, c_alpha)
|
||||
|
||||
# the avatar with the new frame
|
||||
if t >= t_avatar:
|
||||
k = out_back(seg(t, t_avatar, t_avatar + 0.7), 1.9)
|
||||
beat = 1 + 0.05 * clamp(1 - abs(t - S[4]) / 0.22)
|
||||
move = in_out(seg(t, S[4] + 0.4, S[5] - 0.2))
|
||||
if VERT: # a bigger avatar in the middle that then rises to the top while the tiles come in below
|
||||
ax, ay = CX, lerp(wy0 - 20, 330, move)
|
||||
sc = k * beat * lerp(1.18, 0.66, move)
|
||||
else:
|
||||
ax, ay = lerp(960, 420, move), lerp(560, 600, move)
|
||||
sc = k * beat * lerp(1.0, 0.82, move)
|
||||
out_alpha = 1.0
|
||||
put_c(img, soft_shadow(300, 300, 150, blur=40, dy=24, alpha=50), ax, ay, sc, 0.9)
|
||||
put_c(img, avatar(300), ax, ay, sc, out_alpha)
|
||||
put_c(img, ring_of(390), ax, ay, sc * 1.0, out_alpha, angle=(1 - k) * -40)
|
||||
burst(img, ax, ay, t, t_avatar + 0.05, seed=9, n=36, power=430, life=1.0, colors=[GOLD, (255, 140, 170), (140, 120, 255), (255, 255, 255)])
|
||||
text(img, (ax, ay + 262 * sc), "Рамка принята", 34, "semi", INK, "mm", alpha=seg(t, t_avatar + 0.4, t_avatar + 0.8))
|
||||
pill(img, ax, ay + 322 * sc, "v из вашей картинки", VIOLET, (255, 255, 255), 24, alpha=seg(t, t_avatar + 0.7, t_avatar + 1.1))
|
||||
|
||||
|
||||
def scene_catalog(img, t):
|
||||
"""A row of picture tiles glides across, the middle one is bigger; on a beat they fan out, the camera zooms into one and a pill says "added"."""
|
||||
a0, a1 = S[4] + 0.5, S[9]
|
||||
if t < a0 or t > a1 + 0.5:
|
||||
return
|
||||
size = 460 if VERT else 340
|
||||
spacing = 520 if VERT else 410
|
||||
center_x = CX if VERT else 1130
|
||||
zoom_k = 0.9 if VERT else 1.1
|
||||
reach = 560.0 if VERT else 700.0
|
||||
fan_gap = 190 if VERT else 150
|
||||
row_y = CY + (40 if VERT else 0)
|
||||
appear = out_cubic(seg(t, a0, a0 + 1.4))
|
||||
fan = in_out(seg(t, S[7], S[7] + 0.7)) * (1 - in_out(seg(t, S[8], S[8] + 0.45)))
|
||||
zoom = in_out(seg(t, S[8], S[8] + 0.7)) * (1 - in_out(seg(t, S[9] - 0.5, S[9] + 0.3)))
|
||||
morph = in_out(seg(t, S[7] + 0.2, S[7] + 0.65)) * (1 - in_out(seg(t, S[9] - 0.35, S[9])))
|
||||
shift = (t - a0) * (190 if VERT else 150)
|
||||
offset = center_x - 830 * spacing / 410
|
||||
out_alpha = 1 - seg(t, S[9] - 0.2, S[9] + 0.4)
|
||||
items = []
|
||||
for i in range(-3, 12):
|
||||
x_row = (i * spacing - shift) % (12 * spacing) - 2 * spacing + offset
|
||||
x_row = lerp(W + 380 + i * 60, x_row, appear)
|
||||
d = abs(x_row - center_x) / reach
|
||||
scale = clamp(1.12 - 0.42 * d, 0.5, 1.12)
|
||||
# the fan: all tiles gather to the middle and tilt
|
||||
x_fan = center_x + (i % 5 - 2) * fan_gap
|
||||
angle_fan = (i % 5 - 2) * 7
|
||||
x = lerp(x_row, x_fan, fan)
|
||||
angle = angle_fan * fan
|
||||
scale = lerp(scale, 1.0 - abs(i % 5 - 2) * 0.05, fan)
|
||||
items.append((scale * 100 - abs(i % 5 - 2) * fan * 10, i, x, angle, scale))
|
||||
for _, i, x, angle, scale in sorted(items):
|
||||
cy = row_y + math.sin(i * 1.3 + t * 1.2) * 10 * (1 - fan)
|
||||
sprite = card(size, size, 36)
|
||||
# each tile pops a little as it turns into the cat, one after another
|
||||
local = clamp((t - (S[7] + 0.2 + (i % 5) * 0.04)) / 0.4)
|
||||
pop = 1 + 0.14 * math.sin(math.pi * local) if 0 < local < 1 else 1.0
|
||||
sc = scale * (1 + zoom_k * zoom) * pop
|
||||
put_c(img, sprite, x, cy, sc, out_alpha, angle)
|
||||
put_c(img, tile(i, size), x, cy, sc, out_alpha, angle)
|
||||
if morph > 0.01:
|
||||
put_c(img, tile(i, size, True), x, cy, sc, out_alpha * morph, angle)
|
||||
burst(img, center_x, row_y, t, S[7] + 0.3, seed=21, n=34, power=470, life=0.9, colors=[(255, 150, 190), (255, 255, 255), (255, 210, 120), (190, 150, 255)])
|
||||
if zoom > 0.6:
|
||||
k = out_cubic(seg(zoom, 0.6, 1.0))
|
||||
cxz, cyz = center_x, row_y
|
||||
base = size * (1 + zoom_k * zoom)
|
||||
flip = seg(t, S[8] + 0.9, S[8] + 1.1)
|
||||
label = "v Добавлено" if flip >= 1 else "+ Добавить"
|
||||
col = VIOLET if flip >= 1 else (24, 24, 28)
|
||||
press = 1 + 0.12 * clamp(1 - abs(t - (S[8] + 1.0)) / 0.15)
|
||||
pill(img, cxz - base / 2 + 160, cyz + base / 2 - 56, label, col, (255, 255, 255), 30, alpha=k * out_alpha, scale=press)
|
||||
pill(img, cxz + base / 2 - 90, cyz - base / 2 + 56, "%d" % (1204 + (1 if flip >= 1 else 0)), (255, 255, 255), INK, 26, alpha=k * out_alpha)
|
||||
if flip >= 1:
|
||||
ripple(img, cxz - base / 2 + 160, cyz + base / 2 - 56, t, S[8] + 1.0, VIOLET, 90)
|
||||
|
||||
|
||||
def scene_bubbles(img, t):
|
||||
"""A chat panel: the picture behind the outgoing message changes on every beat while a stock grey bubble answers."""
|
||||
b0, b1 = S[9], S[12]
|
||||
if t < b0 or t > b1 + 0.6:
|
||||
return
|
||||
vy = 1.4 if VERT else 1.0 # the panel is taller on the tall screen
|
||||
appear = out_back(seg(t, b0 + 0.1, b0 + 0.8), 1.3)
|
||||
leave = in_cubic(seg(t, b1 - 0.1, b1 + 0.5))
|
||||
cx, cy = CX, lerp(H + 220, CY + 20, appear) + leave * 900
|
||||
Y = lambda v: cy + v * vy
|
||||
put_c(img, card(1000, int(780 * vy), 48), cx, cy, 1.0, clamp(appear * 1.4) * (1 - leave))
|
||||
text(img, (cx, Y(-330)), "Чат", 34, "semi", GREY, "mm", alpha=1 - leave)
|
||||
# the stock bubble of TikTok
|
||||
put_c(img, rr(560, 100, 38, (238, 238, 242)), cx - 160, Y(-200), 1.0, (1 - leave) * seg(t, b0 + 0.5, b0 + 0.9))
|
||||
text(img, (cx - 160, Y(-200) - 1), "Привет! Как тебе мой пузырь?", 29, "reg", INK, "mm", alpha=(1 - leave) * seg(t, b0 + 0.5, b0 + 0.9))
|
||||
# the custom bubble
|
||||
idx = sum(1 for s in S if t >= s + 0.0 and s >= b0 and s <= b1 + 0.01)
|
||||
since = t - (S[8 + max(0, idx)] if 8 + idx < len(S) else b0)
|
||||
pop = out_back(clamp(since / 0.4), 2.0)
|
||||
bw, bh = 640, 132
|
||||
pic = mask_round(bubble_picture(idx, bw, bh), 46)
|
||||
put_c(img, pic, cx + 150, Y(-40), lerp(0.92, 1.0, pop), (1 - leave) * seg(t, b0 + 0.9, b0 + 1.3))
|
||||
text(img, (cx + 150, Y(-40) + 2), "Он виден и у меня, и у тебя", 30, "bold", (0, 0, 0), "mm", alpha=0.25 * (1 - leave) * seg(t, b0 + 0.9, b0 + 1.3))
|
||||
text(img, (cx + 150, Y(-40) - 1), "Он виден и у меня, и у тебя", 30, "bold", (255, 255, 255), "mm", alpha=(1 - leave) * seg(t, b0 + 0.9, b0 + 1.3))
|
||||
names = ["Конфетти", "Мята", "Закат", "Облака"]
|
||||
pill(img, cx + 150, Y(80), "Пузырь «%s»" % names[idx % 4], (24, 24, 28), (255, 255, 255), 24, alpha=(1 - leave) * seg(t, b0 + 1.0, b0 + 1.4), scale=lerp(0.9, 1.0, pop))
|
||||
# the other person's custom bubble answers
|
||||
k = seg(t, S[10] + 0.1, S[10] + 0.6)
|
||||
put_c(img, mask_round(bubble_picture(idx + 2, 520, 100), 40), cx - 190, Y(190), lerp(0.9, 1.0, out_back(k)), k * (1 - leave))
|
||||
text(img, (cx - 190, Y(190) + 2), "У меня тоже есть мод", 28, "bold", (0, 0, 0), "mm", alpha=0.25 * k * (1 - leave))
|
||||
text(img, (cx - 190, Y(190) - 1), "У меня тоже есть мод", 28, "bold", (255, 255, 255), "mm", alpha=k * (1 - leave))
|
||||
burst(img, cx, Y(-40), t, S[11] + 0.02, seed=5, n=60, power=640, life=1.3)
|
||||
|
||||
|
||||
def scene_publish(img, t):
|
||||
"""Three short lines, one after another on the beats: big words that rise into place, with picture tiles drifting around."""
|
||||
p0, p1 = S[12], S[14]
|
||||
if t < p0 or t > p1 + 0.3:
|
||||
return
|
||||
lines = [["Публикуй", "рамки", "и пузыри"], ["Сначала", "проверка,", "потом каталог"], ["Жми", "«+»", "и она в TikTok"]] if VERT else \
|
||||
[["Публикуй", "рамки", "и", "пузыри"], ["Сначала", "проверка,", "потом", "каталог"], ["Жми", "«+»", "и она", "в TikTok"]]
|
||||
spots = [(210, 430, 230), (870, 1500, 260), (820, 380, 180), (240, 1560, 200)] if VERT else [(300, 330, 190), (1620, 770, 220), (1560, 250, 150), (360, 800, 160)]
|
||||
size = 92 if VERT else 84
|
||||
window = (p1 - p0) / 3
|
||||
for n, words in enumerate(lines):
|
||||
a, b = p0 + n * window, p0 + (n + 1) * window
|
||||
if not a <= t < b + 0.1:
|
||||
continue
|
||||
out = seg(t, b - 0.25, b)
|
||||
f = font(size, "semi")
|
||||
draw = ImageDraw.Draw(Image.new("L", (1, 1)))
|
||||
gap = 26
|
||||
# on the tall screen the words stand in rows (a row per word group), on the wide one in a single row
|
||||
rows = [words] if not VERT else [words[:1] if len(words) == 3 and n == 2 else words[:2] if n == 1 else words[:2], None]
|
||||
rows = [[w for w in words[:1]], [w for w in words[1:]]] if VERT else [words]
|
||||
for r, row in enumerate(rows):
|
||||
widths = [draw.textlength(w, font=f) for w in row]
|
||||
x = CX - (sum(widths) + gap * (len(row) - 1)) / 2
|
||||
base_y = CY + ((r - 0.5) * 130 if VERT else 0)
|
||||
for i, w in enumerate(row):
|
||||
order = i + (0 if r == 0 else len(rows[0]))
|
||||
k = out_back(seg(t, a + order * 0.11, a + order * 0.11 + 0.4), 1.6)
|
||||
lift = (1 - k) * 46 - out * 40
|
||||
accent = VIOLET if (n == 2 and w == "«+»") else INK
|
||||
text(img, (x, base_y + lift), w, size, "semi", accent, "lm", alpha=clamp(k * 1.4) * (1 - out))
|
||||
x += widths[i] + gap
|
||||
for j, (tx, ty, sz) in enumerate(spots):
|
||||
k = out_back(seg(t, a + 0.15 + j * 0.1, a + 0.7 + j * 0.1), 1.5)
|
||||
bob = math.sin(t * 1.6 + j * 1.7) * 14
|
||||
idx = n * 4 + j
|
||||
put_c(img, card(sz, sz, int(sz * 0.12), blur=24, dy=10, alpha=40), tx, ty + bob, k, (1 - out))
|
||||
put_c(img, tile(idx, sz), tx, ty + bob, k, (1 - out), angle=(j - 1.5) * 4 * (1 - k * 0.3))
|
||||
|
||||
|
||||
def scene_title(img, t):
|
||||
"""The title: LihonT in black, STORE in candy letters; then the logo."""
|
||||
a = S[14] + 0.1
|
||||
if t < a:
|
||||
return
|
||||
logo_t = S[15]
|
||||
k1 = 1 - seg(t, logo_t - 0.1, logo_t + 0.3)
|
||||
if VERT: # one above the other
|
||||
text(img, (CX, CY - 230), "LihonT", 170, "semi", INK, "mm", alpha=out_cubic(seg(t, a, a + 0.4)) * k1)
|
||||
candy_text(img, CX, CY - 40, "STORE", 190, t, a + 0.25, 0.09, alpha=k1)
|
||||
text(img, (CX, CY + 160), "рамки и пузыри чата", 44, "reg", GREY, "mm", alpha=out_cubic(seg(t, a + 0.9, a + 1.3)) * k1)
|
||||
text(img, (CX, CY + 220), "для вашего TikTok", 44, "reg", GREY, "mm", alpha=out_cubic(seg(t, a + 1.0, a + 1.4)) * k1)
|
||||
logo_c, logo_size, caption_y = (CX, CY - 130), 560, CY + 300
|
||||
else:
|
||||
text(img, (700, 470), "LihonT", 150, "semi", INK, "mm", alpha=out_cubic(seg(t, a, a + 0.4)) * k1)
|
||||
candy_text(img, 1230, 470, "STORE", 150, t, a + 0.25, 0.09, alpha=k1)
|
||||
text(img, (960, 640), "рамки и пузыри чата для вашего TikTok", 40, "reg", GREY, "mm", alpha=out_cubic(seg(t, a + 0.9, a + 1.3)) * k1)
|
||||
logo_c, logo_size, caption_y = (960, 480), 420, 780
|
||||
if t >= logo_t - 0.05:
|
||||
flower = Image.open(ROOT / "src" / "brand" / "logo_note_flower_gold_1024.png").convert("RGBA")
|
||||
k = out_back(seg(t, logo_t, logo_t + 0.6), 1.5)
|
||||
put_c(img, flower.resize((logo_size, logo_size), Image.Resampling.LANCZOS), logo_c[0], logo_c[1], k, clamp(k * 1.5))
|
||||
text(img, (CX, caption_y), "lihont.space · t.me/lihont", 38, "semi", GREY, "mm", alpha=seg(t, logo_t + 0.5, logo_t + 0.9))
|
||||
burst(img, logo_c[0], logo_c[1], t, logo_t + 0.1, seed=11, n=50, power=700, life=1.4)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the whole picture
|
||||
|
||||
def frame_at(t: float) -> Image.Image:
|
||||
img = Image.new("RGBA", (W, H), (255, 255, 255, 255))
|
||||
for scene in (scene_start, scene_upload, scene_catalog, scene_bubbles, scene_publish, scene_title):
|
||||
scene(img, t)
|
||||
fade_in = clamp(t / 0.25)
|
||||
if fade_in < 1:
|
||||
img.alpha_composite(Image.new("RGBA", (W, H), (255, 255, 255, int(255 * (1 - fade_in)))))
|
||||
return img
|
||||
|
||||
|
||||
def render_frame(index: int) -> bytes:
|
||||
return frame_at(index / FPS).convert("RGB").tobytes()
|
||||
|
||||
|
||||
def _init(song: str, vertical: bool) -> None:
|
||||
configure(song)
|
||||
set_format(vertical)
|
||||
|
||||
|
||||
def sheet(path: Path, count: int = 24) -> None:
|
||||
thumbs = []
|
||||
for i in range(count):
|
||||
t = DURATION * (i + 0.5) / count
|
||||
thumbs.append(frame_at(t).convert("RGB").resize((480, 270), Image.Resampling.LANCZOS))
|
||||
cols = 4
|
||||
rows = (count + cols - 1) // cols
|
||||
out = Image.new("RGB", (cols * 484, rows * 274), (200, 200, 205))
|
||||
for i, th in enumerate(thumbs):
|
||||
out.paste(th, ((i % cols) * 484 + 2, (i // cols) * 274 + 2))
|
||||
out.save(path)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--song", default="store")
|
||||
parser.add_argument("--still", type=float, nargs="*")
|
||||
parser.add_argument("--sheet", action="store_true")
|
||||
parser.add_argument("--vertical", action="store_true", help="9:16 (1080x1920) instead of 16:9")
|
||||
parser.add_argument("--jobs", type=int, default=6)
|
||||
args = parser.parse_args()
|
||||
configure(args.song)
|
||||
set_format(args.vertical)
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
if args.still:
|
||||
for t in args.still:
|
||||
path = OUT_DIR / ("still_%s%.2f.png" % ("v" if args.vertical else "", t))
|
||||
frame_at(t).convert("RGB").save(path)
|
||||
print(path)
|
||||
return
|
||||
if args.sheet:
|
||||
path = OUT_DIR / "sheet.png"
|
||||
sheet(path)
|
||||
print(path)
|
||||
return
|
||||
out = OUT_DIR / ("store_openai_%s%s.mp4" % (args.song, "_9x16" if args.vertical else ""))
|
||||
command = [shutil.which("ffmpeg") or "ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "%dx%d" % (W, H),
|
||||
"-r", str(FPS), "-i", "-", "-i", str(SONG), "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p",
|
||||
"-af", "afade=t=out:st=%.2f:d=0.6" % (DURATION - 0.6), "-c:a", "aac", "-b:a", "192k", "-t", "%.2f" % DURATION, str(out)]
|
||||
proc = subprocess.Popen(command, stdin=subprocess.PIPE)
|
||||
with Pool(args.jobs, initializer=_init, initargs=(args.song, args.vertical)) as pool:
|
||||
for n, data in enumerate(pool.imap(render_frame, range(FRAMES), chunksize=4)):
|
||||
proc.stdin.write(data)
|
||||
if n % 60 == 0:
|
||||
print("frame %d/%d" % (n, FRAMES), flush=True)
|
||||
proc.stdin.close()
|
||||
proc.wait()
|
||||
print("done:", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -24,12 +24,20 @@ PAYLOAD = [
|
||||
("src/web/lihonb.html", "lihonb/index.html"),
|
||||
("src/web/members_index.html", "members/index.html"),
|
||||
("src/web/pay_index.html", "pay/index.html"),
|
||||
("src/web/pet_index.html", "pet/index.html"),
|
||||
("src/web/assets/pets/cat.png", "assets/pets/cat.png"),
|
||||
("src/web/assets/pets/dog.png", "assets/pets/dog.png"),
|
||||
("src/web/assets/pets/lion.png", "assets/pets/lion.png"),
|
||||
("src/web/assets/site/md3.css", "assets/site/md3.css"),
|
||||
("src/web/assets/site/md3.js", "assets/site/md3.js"),
|
||||
("src/web/assets/site/icons.svg", "assets/site/icons.svg"),
|
||||
("src/web/assets/site/plugin_howto.svg", "assets/site/plugin_howto.svg"),
|
||||
]
|
||||
|
||||
# The animals of the Серийчик: one strip of frames per animal, age and mood (see scripts/make_pet_designs.py)
|
||||
for _strip in sorted((ROOT / "src" / "web" / "assets" / "pets" / "strips").glob("*.png")):
|
||||
PAYLOAD.append((_strip.relative_to(ROOT).as_posix(), "assets/pets/strips/" + _strip.name))
|
||||
|
||||
# The avatar frames the mod downloads (see scripts/build_frames_catalog.py): the catalog and every sprite of every pack, at
|
||||
# /frames/ on the site. A new pack is only the files of its folder: build the catalog, deploy, and phones pick it up by themselves.
|
||||
_FRAMES = ROOT / "frames"
|
||||
|
||||
446
services/members/accounts.py
Normal file
@@ -0,0 +1,446 @@
|
||||
"""Telegram accounts of the store: sign-in through the bot, nicknames, follows, the inbox, hidden ids of people and timed bans.
|
||||
|
||||
Three levels (see the plan of 2026-11-07):
|
||||
guest looks at the catalog and profiles, nothing else;
|
||||
member has signed in through the Telegram bot and chosen a nickname: follows authors, reads the inbox, gets notifications;
|
||||
author a member who also proved a TikTok account (the code in the bio, bound to the installation: see Registry._prove): only
|
||||
authors may publish, and only the TikTok account decides whose avatar a frame is shown on.
|
||||
|
||||
An installation (the secret that the mod and the store hold) is what stands for a signed-in person, exactly as for the TikTok proof; only
|
||||
its SHA-256 is kept. A "hidden id" (pid, like A7K-3Q2) is the short opaque name of a person that the owner uses: it is shown to nobody but
|
||||
the owner (review messages, /who) and the owner bans by it: `/ban A7K-3Q2 7 reason` for seven days.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from community import INSTALL, valid_uid
|
||||
|
||||
BOT_NAME = "lihonTauthbot"
|
||||
TOKEN = re.compile(r"[a-f0-9]{24}\Z")
|
||||
HANDLE = re.compile(r"[a-z0-9_]{3,20}\Z")
|
||||
RESERVED = {"admin", "administrator", "lihont", "lihon", "lihonts", "moderator", "mod", "support", "owner", "root", "system", "bot",
|
||||
"telegram", "tiktok", "store", "staff", "official", "cheb0chik", "null", "none", "me", "all"}
|
||||
PID_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||
PID = re.compile(r"[A-HJKMNP-Z2-9]{3}-[A-HJKMNP-Z2-9]{3}\Z")
|
||||
TOKEN_LIFETIME = 900 # a sign-in link works for 15 minutes
|
||||
PENDING_LIMIT = 5 # open links per installation
|
||||
FOLLOW_LIMIT = 200
|
||||
HANDLE_COOLDOWN = 30 * 86400 # a nickname may be changed once in 30 days
|
||||
MAX_BAN_DAYS = 3650
|
||||
|
||||
|
||||
def digest_of(installation) -> str:
|
||||
if not isinstance(installation, str) or not INSTALL.fullmatch(installation):
|
||||
raise ValueError("Invalid installation code")
|
||||
return hashlib.sha256(installation.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
class Accounts:
|
||||
def __init__(self, registry):
|
||||
self.r = registry
|
||||
self.operations = {
|
||||
"tg_start": self.start, "tg_poll": self.poll, "tg_register": self.register, "tg_me": self.me,
|
||||
"tg_link_tiktok": self.link_tiktok, "tg_logout": self.logout, "tg_delete": self.delete, "tg_notify": self.set_notify,
|
||||
"follow": self.follow, "unfollow": self.unfollow, "following": self.following, "followers": self.followers,
|
||||
"follow_info": self.follow_info, "inbox": self.inbox, "inbox_seen": self.inbox_seen,
|
||||
}
|
||||
with self.r.connect() as db:
|
||||
db.execute("CREATE TABLE IF NOT EXISTS tg_accounts (tg_id INTEGER PRIMARY KEY, handle TEXT UNIQUE COLLATE NOCASE, "
|
||||
"pid TEXT NOT NULL UNIQUE, created_at INTEGER NOT NULL, notify INTEGER NOT NULL DEFAULT 1, "
|
||||
"inbox_seen INTEGER NOT NULL DEFAULT 0, handle_changed_at INTEGER NOT NULL DEFAULT 0, "
|
||||
"banned_until INTEGER NOT NULL DEFAULT 0, ban_reason TEXT NOT NULL DEFAULT '')")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS tg_logins (token_hash TEXT PRIMARY KEY, installation TEXT NOT NULL, "
|
||||
"created_at INTEGER NOT NULL, tg_id INTEGER)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS tg_sessions (installation TEXT PRIMARY KEY, tg_id INTEGER NOT NULL, created_at INTEGER NOT NULL)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS tg_tiktok (tg_id INTEGER PRIMARY KEY, uid TEXT NOT NULL UNIQUE, linked_at INTEGER NOT NULL)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS follows (follower INTEGER NOT NULL, author_uid TEXT NOT NULL, created_at INTEGER NOT NULL, "
|
||||
"PRIMARY KEY(follower, author_uid))")
|
||||
db.execute("CREATE INDEX IF NOT EXISTS follows_author ON follows(author_uid)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS pids (pid TEXT PRIMARY KEY, tg_id INTEGER UNIQUE, uid TEXT UNIQUE)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS ban_log (id INTEGER PRIMARY KEY AUTOINCREMENT, pid TEXT NOT NULL, until INTEGER NOT NULL, "
|
||||
"reason TEXT NOT NULL, at INTEGER NOT NULL)")
|
||||
|
||||
def call(self, operation, payload):
|
||||
return self.operations[operation](payload)
|
||||
|
||||
def _now(self) -> int:
|
||||
return int(self.r.clock())
|
||||
|
||||
# ---- hidden ids ------------------------------------------------------------------------------------------
|
||||
|
||||
def _new_pid(self, db) -> str:
|
||||
while True:
|
||||
raw = "".join(secrets.choice(PID_ALPHABET) for _ in range(6))
|
||||
pid = raw[:3] + "-" + raw[3:]
|
||||
if not db.execute("SELECT 1 FROM pids WHERE pid=?", (pid,)).fetchone():
|
||||
return pid
|
||||
|
||||
def pid_for_tg(self, tg_id: int, db=None) -> str:
|
||||
def work(db):
|
||||
row = db.execute("SELECT pid FROM pids WHERE tg_id=?", (tg_id,)).fetchone()
|
||||
if row:
|
||||
return row[0]
|
||||
pid = self._new_pid(db)
|
||||
db.execute("INSERT INTO pids(pid, tg_id) VALUES(?,?)", (pid, tg_id))
|
||||
return pid
|
||||
if db is not None:
|
||||
return work(db)
|
||||
with self.r.connect() as own:
|
||||
return work(own)
|
||||
|
||||
def pid_for_uid(self, uid: str) -> str:
|
||||
"""The hidden id of a TikTok account; made when it is first needed (the owner sees it in the review messages)."""
|
||||
with self.r.connect() as db:
|
||||
row = db.execute("SELECT pid FROM pids WHERE uid=?", (uid,)).fetchone()
|
||||
if row:
|
||||
return row[0]
|
||||
tg = db.execute("SELECT tg_id FROM tg_tiktok WHERE uid=?", (uid,)).fetchone()
|
||||
if tg:
|
||||
own = db.execute("SELECT pid FROM pids WHERE tg_id=?", (tg[0],)).fetchone()
|
||||
if own:
|
||||
db.execute("UPDATE pids SET uid=? WHERE pid=?", (uid, own[0]))
|
||||
return own[0]
|
||||
pid = self._new_pid(db)
|
||||
db.execute("INSERT INTO pids(pid, uid) VALUES(?,?)", (pid, uid))
|
||||
return pid
|
||||
|
||||
# ---- signing in through the bot ----------------------------------------------------------------------------
|
||||
|
||||
def start(self, p):
|
||||
"""The app asks for a sign-in link; the person opens it in Telegram and the bot ties them to the token."""
|
||||
digest = digest_of(p.get("installation"))
|
||||
now = self._now()
|
||||
token = secrets.token_hex(12)
|
||||
with self.r.connect() as db:
|
||||
db.execute("DELETE FROM tg_logins WHERE created_at < ?", (now - TOKEN_LIFETIME,))
|
||||
if db.execute("SELECT COUNT(*) FROM tg_logins WHERE installation=?", (digest,)).fetchone()[0] >= PENDING_LIMIT:
|
||||
raise ValueError("Too many open sign-in links, wait a few minutes")
|
||||
db.execute("INSERT INTO tg_logins(token_hash, installation, created_at) VALUES(?,?,?)",
|
||||
(hashlib.sha256(token.encode("ascii")).hexdigest(), digest, now))
|
||||
return {"ok": True, "token": token, "link": "https://t.me/%s?start=%s" % (BOT_NAME, token), "expires_in": TOKEN_LIFETIME}
|
||||
|
||||
def bot_link(self, token, tg_id: int):
|
||||
"""Called by the bot on /start <token>. Returns {"ok", "banned_until"?, "registered"}."""
|
||||
if not isinstance(token, str) or not TOKEN.fullmatch(token) or not isinstance(tg_id, int):
|
||||
return {"ok": False, "reason": "bad_token"}
|
||||
now = self._now()
|
||||
key = hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
with self.r.connect() as db:
|
||||
row = db.execute("SELECT created_at, tg_id FROM tg_logins WHERE token_hash=?", (key,)).fetchone()
|
||||
if row is None or row[0] < now - TOKEN_LIFETIME:
|
||||
return {"ok": False, "reason": "expired"}
|
||||
if row[1] is not None and row[1] != tg_id:
|
||||
return {"ok": False, "reason": "expired"} # the first person to open the link has it: a copy of the link takes nothing
|
||||
account = db.execute("SELECT banned_until, ban_reason, handle FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
|
||||
if account and account[0] and account[0] > now:
|
||||
return {"ok": False, "reason": "banned", "banned_until": account[0], "ban_reason": account[1]}
|
||||
if account is None:
|
||||
self.pid_for_tg(tg_id, db)
|
||||
db.execute("INSERT INTO tg_accounts(tg_id, pid, created_at) VALUES(?,?,?)", (tg_id, self.pid_for_tg(tg_id, db), now))
|
||||
db.execute("UPDATE tg_logins SET tg_id=? WHERE token_hash=?", (tg_id, key))
|
||||
return {"ok": True, "registered": bool(account and account[2])}
|
||||
|
||||
def poll(self, p):
|
||||
digest = digest_of(p.get("installation"))
|
||||
token = p.get("token")
|
||||
if not isinstance(token, str) or not TOKEN.fullmatch(token):
|
||||
raise ValueError("Bad token")
|
||||
now = self._now()
|
||||
key = hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
with self.r.connect() as db:
|
||||
row = db.execute("SELECT installation, created_at, tg_id FROM tg_logins WHERE token_hash=?", (key,)).fetchone()
|
||||
if row is None or row[0] != digest:
|
||||
session = db.execute("SELECT tg_id FROM tg_sessions WHERE installation=?", (digest,)).fetchone()
|
||||
if session:
|
||||
return self._summary(db, session[0], "linked")
|
||||
return {"status": "expired"}
|
||||
if row[1] < now - TOKEN_LIFETIME:
|
||||
db.execute("DELETE FROM tg_logins WHERE token_hash=?", (key,))
|
||||
return {"status": "expired"}
|
||||
if row[2] is None:
|
||||
return {"status": "waiting"}
|
||||
ban = db.execute("SELECT banned_until, ban_reason FROM tg_accounts WHERE tg_id=?", (row[2],)).fetchone()
|
||||
if ban and ban[0] and ban[0] > now:
|
||||
raise ValueError("Account banned until %d: %s" % (ban[0], ban[1] or "rules"))
|
||||
db.execute("INSERT INTO tg_sessions(installation, tg_id, created_at) VALUES(?,?,?) "
|
||||
"ON CONFLICT(installation) DO UPDATE SET tg_id=excluded.tg_id, created_at=excluded.created_at", (digest, row[2], now))
|
||||
db.execute("DELETE FROM tg_logins WHERE token_hash=?", (key,))
|
||||
return self._summary(db, row[2], "linked")
|
||||
|
||||
def _summary(self, db, tg_id, status):
|
||||
row = db.execute("SELECT handle FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
|
||||
return {"status": status, "registered": bool(row and row[0]), "handle": (row[0] if row else None)}
|
||||
|
||||
def _member(self, p, db=None):
|
||||
"""(tg_id, installation digest) of a signed-in, not banned member; the nickname is not required here."""
|
||||
digest = digest_of(p.get("installation"))
|
||||
with self.r.connect() as own:
|
||||
row = own.execute("SELECT s.tg_id, a.banned_until, a.ban_reason FROM tg_sessions s JOIN tg_accounts a ON a.tg_id = s.tg_id "
|
||||
"WHERE s.installation=?", (digest,)).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("Sign in with Telegram first")
|
||||
if row[1] and row[1] > self._now():
|
||||
raise ValueError("Account banned until %d: %s" % (row[1], row[2] or "rules"))
|
||||
return row[0], digest
|
||||
|
||||
def _registered(self, p):
|
||||
tg_id, digest = self._member(p)
|
||||
with self.r.connect() as db:
|
||||
row = db.execute("SELECT handle FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
|
||||
if not row or not row[0]:
|
||||
raise ValueError("Choose a nickname first")
|
||||
return tg_id, digest
|
||||
|
||||
def register(self, p):
|
||||
"""Chooses (or, after the cooldown, changes) the public nickname."""
|
||||
tg_id, _ = self._member(p)
|
||||
handle = str(p.get("handle") or "").strip().lower().lstrip("@")
|
||||
if not HANDLE.fullmatch(handle):
|
||||
raise ValueError("A nickname is 3 to 20 letters a-z, digits or _")
|
||||
if handle in RESERVED or handle.startswith("lihont"):
|
||||
raise ValueError("This nickname is reserved")
|
||||
if any(word in handle for word in ("admin", "moder")):
|
||||
raise ValueError("This nickname is reserved")
|
||||
now = self._now()
|
||||
with self.r.connect() as db:
|
||||
row = db.execute("SELECT handle, handle_changed_at FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
|
||||
if row[0] == handle:
|
||||
return {"ok": True, "handle": handle}
|
||||
if row[0] and row[1] > now - HANDLE_COOLDOWN:
|
||||
raise ValueError("A nickname can be changed once in 30 days")
|
||||
if db.execute("SELECT 1 FROM tg_accounts WHERE handle=? AND tg_id<>?", (handle, tg_id)).fetchone():
|
||||
raise ValueError("This nickname is taken")
|
||||
db.execute("UPDATE tg_accounts SET handle=?, handle_changed_at=? WHERE tg_id=?", (handle, now, tg_id))
|
||||
return {"ok": True, "handle": handle}
|
||||
|
||||
def logout(self, p):
|
||||
digest = digest_of(p.get("installation"))
|
||||
with self.r.connect() as db:
|
||||
db.execute("DELETE FROM tg_sessions WHERE installation=?", (digest,))
|
||||
return {"ok": True}
|
||||
|
||||
def delete(self, p):
|
||||
tg_id, _ = self._member(p)
|
||||
return self.delete_tg(tg_id)
|
||||
|
||||
def delete_tg(self, tg_id: int):
|
||||
"""Takes the Telegram account away with everything that was only about it (follows, sessions, the link to TikTok)."""
|
||||
with self.r.connect() as db:
|
||||
db.execute("DELETE FROM tg_sessions WHERE tg_id=?", (tg_id,))
|
||||
db.execute("DELETE FROM follows WHERE follower=?", (tg_id,))
|
||||
db.execute("DELETE FROM tg_tiktok WHERE tg_id=?", (tg_id,))
|
||||
db.execute("DELETE FROM tg_logins WHERE tg_id=?", (tg_id,))
|
||||
pid = db.execute("SELECT pid FROM pids WHERE tg_id=?", (tg_id,)).fetchone()
|
||||
if pid:
|
||||
db.execute("UPDATE pids SET tg_id=NULL WHERE pid=?", (pid[0],)) # a ban of that person keeps its id
|
||||
db.execute("DELETE FROM tg_accounts WHERE tg_id=? AND banned_until<=?", (tg_id, self._now()))
|
||||
return {"ok": True}
|
||||
|
||||
def set_notify(self, p):
|
||||
tg_id, _ = self._member(p)
|
||||
with self.r.connect() as db:
|
||||
db.execute("UPDATE tg_accounts SET notify=? WHERE tg_id=?", (1 if p.get("on") else 0, tg_id))
|
||||
return {"ok": True, "notify": bool(p.get("on"))}
|
||||
|
||||
# ---- the author level --------------------------------------------------------------------------------------
|
||||
|
||||
def link_tiktok(self, p):
|
||||
"""Links the member to a TikTok account that this very installation proved with the code in the bio (the author level)."""
|
||||
tg_id, digest = self._registered(p)
|
||||
uid = p.get("uid")
|
||||
if not valid_uid(uid):
|
||||
raise ValueError("Invalid account ID")
|
||||
with self.r.connect() as db:
|
||||
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
||||
if owner is None or owner[0] != digest:
|
||||
raise ValueError("Prove the TikTok account first")
|
||||
db.execute("DELETE FROM tg_tiktok WHERE uid=? OR tg_id=?", (uid, tg_id)) # a new proof takes the account over
|
||||
db.execute("INSERT INTO tg_tiktok(tg_id, uid, linked_at) VALUES(?,?,?)", (tg_id, uid, self._now()))
|
||||
self.pid_for_uid(uid) # joins the two hidden ids into one
|
||||
return {"ok": True, "uid": uid}
|
||||
|
||||
def tiktok_uid(self, tg_id: int):
|
||||
with self.r.connect() as db:
|
||||
row = db.execute("SELECT uid FROM tg_tiktok WHERE tg_id=?", (tg_id,)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
# ---- follows -----------------------------------------------------------------------------------------------
|
||||
|
||||
def _author_exists(self, db, uid) -> bool:
|
||||
return bool(db.execute("SELECT 1 FROM art WHERE uid=? AND status='approved' AND listed=1", (uid,)).fetchone())
|
||||
|
||||
def follow(self, p):
|
||||
tg_id, _ = self._registered(p)
|
||||
uid = p.get("uid")
|
||||
if not valid_uid(uid):
|
||||
raise ValueError("Invalid account ID")
|
||||
if uid == self.tiktok_uid(tg_id):
|
||||
raise ValueError("You cannot follow yourself")
|
||||
with self.r.connect() as db:
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone() or not self._author_exists(db, uid):
|
||||
raise ValueError("No such author")
|
||||
if not db.execute("SELECT 1 FROM follows WHERE follower=? AND author_uid=?", (tg_id, uid)).fetchone():
|
||||
if db.execute("SELECT COUNT(*) FROM follows WHERE follower=?", (tg_id,)).fetchone()[0] >= FOLLOW_LIMIT:
|
||||
raise ValueError("You follow too many authors")
|
||||
db.execute("INSERT INTO follows(follower, author_uid, created_at) VALUES(?,?,?)", (tg_id, uid, self._now()))
|
||||
count = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
|
||||
return {"ok": True, "following": True, "followers": count}
|
||||
|
||||
def unfollow(self, p):
|
||||
tg_id, _ = self._registered(p)
|
||||
uid = p.get("uid")
|
||||
if not valid_uid(uid):
|
||||
raise ValueError("Invalid account ID")
|
||||
with self.r.connect() as db:
|
||||
db.execute("DELETE FROM follows WHERE follower=? AND author_uid=?", (tg_id, uid))
|
||||
count = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
|
||||
return {"ok": True, "following": False, "followers": count}
|
||||
|
||||
def following(self, p):
|
||||
"""Whom this member follows (only they see it)."""
|
||||
tg_id, _ = self._registered(p)
|
||||
with self.r.connect() as db:
|
||||
rows = db.execute("SELECT f.author_uid, (SELECT unique_id FROM shape_owner o WHERE o.uid = f.author_uid), "
|
||||
"(SELECT COUNT(*) FROM art a WHERE a.uid = f.author_uid AND a.status='approved' AND a.listed=1) "
|
||||
"FROM follows f WHERE f.follower=? ORDER BY f.created_at DESC LIMIT ?", (tg_id, FOLLOW_LIMIT)).fetchall()
|
||||
return {"items": [{"uid": r[0], "name": r[1], "works": r[2]} for r in rows]}
|
||||
|
||||
def followers(self, p):
|
||||
"""Who follows this member's TikTok account: the owner of the account alone sees the list, the others see a number."""
|
||||
tg_id, _ = self._registered(p)
|
||||
uid = self.tiktok_uid(tg_id)
|
||||
if uid is None:
|
||||
return {"items": [], "count": 0}
|
||||
with self.r.connect() as db:
|
||||
rows = db.execute("SELECT a.handle FROM follows f JOIN tg_accounts a ON a.tg_id = f.follower "
|
||||
"WHERE f.author_uid=? AND a.handle IS NOT NULL ORDER BY f.created_at DESC LIMIT 500", (uid,)).fetchall()
|
||||
count = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
|
||||
return {"items": [{"handle": r[0]} for r in rows], "count": count}
|
||||
|
||||
def follow_info(self, p):
|
||||
"""Public: how many follow an author (a number, never names) and, for a signed-in caller, whether they do."""
|
||||
uid = p.get("uid")
|
||||
if not valid_uid(uid):
|
||||
raise ValueError("Invalid account ID")
|
||||
with self.r.connect() as db:
|
||||
count = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
|
||||
reply = {"followers": count}
|
||||
if p.get("installation"):
|
||||
try:
|
||||
tg_id, _ = self._registered(p)
|
||||
except ValueError:
|
||||
return reply
|
||||
with self.r.connect() as db:
|
||||
reply["following"] = bool(db.execute("SELECT 1 FROM follows WHERE follower=? AND author_uid=?", (tg_id, uid)).fetchone())
|
||||
return reply
|
||||
|
||||
# ---- the inbox -----------------------------------------------------------------------------------------------
|
||||
|
||||
def inbox(self, p):
|
||||
"""New approved and listed works of the authors this member follows, newest first; `unread` counts those after the last look."""
|
||||
tg_id, _ = self._registered(p)
|
||||
items, more = self.r.catalog._page(" AND a.uid IN (SELECT author_uid FROM follows WHERE follower=?)", [tg_id], p.get("cursor"), p.get("limit"))
|
||||
with self.r.connect() as db:
|
||||
seen = db.execute("SELECT inbox_seen FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()[0]
|
||||
unread = db.execute("SELECT COUNT(*) FROM art a WHERE a.status='approved' AND a.listed=1 AND a.listed_at > ? "
|
||||
"AND a.uid IN (SELECT author_uid FROM follows WHERE follower=?) "
|
||||
"AND a.uid NOT IN (SELECT uid FROM active_blocked)", (seen, tg_id)).fetchone()[0]
|
||||
return {"items": items, "next": more, "unread": unread}
|
||||
|
||||
def inbox_seen(self, p):
|
||||
tg_id, _ = self._registered(p)
|
||||
with self.r.connect() as db:
|
||||
db.execute("UPDATE tg_accounts SET inbox_seen=? WHERE tg_id=?", (self._now(), tg_id))
|
||||
return {"ok": True}
|
||||
|
||||
def me(self, p):
|
||||
tg_id, _ = self._member(p)
|
||||
with self.r.connect() as db:
|
||||
handle, notify, seen = db.execute("SELECT handle, notify, inbox_seen FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
|
||||
following = db.execute("SELECT COUNT(*) FROM follows WHERE follower=?", (tg_id,)).fetchone()[0]
|
||||
uid = self.tiktok_uid(tg_id)
|
||||
followers = 0
|
||||
if uid:
|
||||
with self.r.connect() as db:
|
||||
followers = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
|
||||
return {"handle": handle, "registered": bool(handle), "level": "author" if uid else "member", "tiktok": uid,
|
||||
"notify": bool(notify), "following": following, "followers": followers}
|
||||
|
||||
# ---- notifications -------------------------------------------------------------------------------------------
|
||||
|
||||
def followers_to_notify(self, uid: str, limit: int = 300) -> list:
|
||||
"""Telegram ids of the followers of an author who want notifications and are not banned."""
|
||||
with self.r.connect() as db:
|
||||
rows = db.execute("SELECT a.tg_id FROM follows f JOIN tg_accounts a ON a.tg_id = f.follower "
|
||||
"WHERE f.author_uid=? AND a.notify=1 AND a.handle IS NOT NULL AND a.banned_until<=? LIMIT ?",
|
||||
(uid, self._now(), limit)).fetchall()
|
||||
return [r[0] for r in rows]
|
||||
|
||||
def handle_of_uid(self, uid: str):
|
||||
with self.r.connect() as db:
|
||||
row = db.execute("SELECT a.handle FROM tg_tiktok t JOIN tg_accounts a ON a.tg_id = t.tg_id WHERE t.uid=?", (uid,)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def mute(self, tg_id: int):
|
||||
with self.r.connect() as db:
|
||||
db.execute("UPDATE tg_accounts SET notify=0 WHERE tg_id=?", (tg_id,))
|
||||
|
||||
# ---- bans, by the hidden id -------------------------------------------------------------------------------------
|
||||
|
||||
def _person(self, db, pid):
|
||||
if not isinstance(pid, str) or not PID.fullmatch(pid.upper()):
|
||||
raise ValueError("Bad id")
|
||||
row = db.execute("SELECT pid, tg_id, uid FROM pids WHERE pid=?", (pid.upper(),)).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("Unknown id")
|
||||
return row
|
||||
|
||||
def ban(self, pid: str, days: int, reason: str = ""):
|
||||
"""Bans a person for `days` days (0 = for ever): their Telegram account and their TikTok account together."""
|
||||
if not isinstance(days, int) or not 0 <= days <= MAX_BAN_DAYS:
|
||||
raise ValueError("Days must be 0 to %d" % MAX_BAN_DAYS)
|
||||
now = self._now()
|
||||
until = 0 if days == 0 else now + days * 86400
|
||||
reason = str(reason or "")[:120]
|
||||
with self.r.connect() as db:
|
||||
pid, tg_id, uid = self._person(db, pid)
|
||||
if tg_id is not None:
|
||||
db.execute("UPDATE tg_accounts SET banned_until=?, ban_reason=? WHERE tg_id=?", (until if until else 4102444800, reason, tg_id))
|
||||
db.execute("DELETE FROM tg_sessions WHERE tg_id=?", (tg_id,))
|
||||
if uid is not None:
|
||||
db.execute("INSERT INTO blocked(uid, until) VALUES(?,?) ON CONFLICT(uid) DO UPDATE SET until=excluded.until", (uid, until))
|
||||
db.execute("INSERT INTO ban_log(pid, until, reason, at) VALUES(?,?,?,?)", (pid, until, reason, now))
|
||||
return {"ok": True, "pid": pid, "until": until or None, "tg": tg_id is not None, "tiktok": uid is not None}
|
||||
|
||||
def unban(self, pid: str):
|
||||
with self.r.connect() as db:
|
||||
pid, tg_id, uid = self._person(db, pid)
|
||||
if tg_id is not None:
|
||||
db.execute("UPDATE tg_accounts SET banned_until=0, ban_reason='' WHERE tg_id=?", (tg_id,))
|
||||
if uid is not None:
|
||||
db.execute("DELETE FROM blocked WHERE uid=?", (uid,))
|
||||
return {"ok": True, "pid": pid}
|
||||
|
||||
def who(self, pid: str):
|
||||
"""What the owner may see about a person: the nickname, the TikTok account, the counts, the ban."""
|
||||
now = self._now()
|
||||
with self.r.connect() as db:
|
||||
pid, tg_id, uid = self._person(db, pid)
|
||||
handle = banned = None
|
||||
if tg_id is not None:
|
||||
row = db.execute("SELECT handle, banned_until FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
|
||||
handle, banned = (row[0], row[1]) if row else (None, 0)
|
||||
if uid is not None:
|
||||
unique = db.execute("SELECT unique_id FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
||||
blocked = db.execute("SELECT until FROM blocked WHERE uid=?", (uid,)).fetchone()
|
||||
works = db.execute("SELECT status, COUNT(*) FROM art WHERE uid=? GROUP BY status", (uid,)).fetchall()
|
||||
else:
|
||||
unique, blocked, works = None, None, []
|
||||
followers = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0] if uid else 0
|
||||
return {"pid": pid, "handle": handle, "tiktok_uid": uid, "tiktok": unique[0] if unique else None,
|
||||
"works": dict(works), "followers": followers,
|
||||
"banned": bool((banned and banned > now) or (blocked and (blocked[0] == 0 or blocked[0] > now)))}
|
||||
184
services/members/authbot.py
Normal file
@@ -0,0 +1,184 @@
|
||||
"""The sign-in bot of the store (@lihonTauthbot): ties a Telegram person to the sign-in link the app made, answers a few commands, sends the
|
||||
notifications about new works, and takes the owner's commands (`/ban A7K-3Q2 7 reason`, `/unban`, `/who`).
|
||||
|
||||
Only the owner (MOD_OWNER_ID) may use the owner's commands. Nobody gets another person's data: the bot never says who someone else is.
|
||||
The bot's token lives in the service's environment (AUTH_BOT_TOKEN), never in the source.
|
||||
|
||||
The transport is the Telegram class of modbot.py, injected, so the tests run without a network.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
try:
|
||||
import modbot
|
||||
except ImportError: # imported as part of a package
|
||||
from . import modbot
|
||||
|
||||
HELP = ("Это бот входа LihonT Store. Откройте приложение Store и нажмите «Войти через Telegram»: оно покажет ссылку на этого бота.\n\n"
|
||||
"Команды:\n/notify, включить уведомления о новых работах авторов, на которых вы подписаны\n"
|
||||
"/stop, выключить уведомления\n/delete, удалить аккаунт Store (подписки и вход; ваши работы остаются у автора)")
|
||||
KINDS = {"frame": "рамку", "bubble": "пузырь"}
|
||||
|
||||
|
||||
def _when(ts: int) -> str:
|
||||
return datetime.fromtimestamp(ts, timezone.utc).strftime("%d.%m.%Y")
|
||||
|
||||
|
||||
class AuthBot:
|
||||
def __init__(self, registry, telegram, owner_id, clock=time.time):
|
||||
self.registry, self.telegram, self.owner = registry, telegram, int(owner_id)
|
||||
self.accounts = registry.accounts
|
||||
self.offset = 0
|
||||
self.clock = clock
|
||||
self._delete_asked = {}
|
||||
|
||||
def say(self, chat_id, text):
|
||||
self.telegram.call("sendMessage", {"chat_id": chat_id, "text": text})
|
||||
|
||||
# -- updates ----------------------------------------------------------------------------------------------------
|
||||
|
||||
def handle(self, update):
|
||||
message = update.get("message") or {}
|
||||
user = message.get("from") or {}
|
||||
chat = (message.get("chat") or {}).get("id")
|
||||
text = (message.get("text") or "").strip()
|
||||
if not user.get("id") or chat is None or not text.startswith("/") or (message.get("chat") or {}).get("type") != "private":
|
||||
return
|
||||
command, _, rest = text.partition(" ")
|
||||
command = command.split("@")[0].lower()
|
||||
rest = rest.strip()
|
||||
if command == "/start":
|
||||
return self._start(user["id"], chat, rest)
|
||||
if command in ("/notify", "/stop"):
|
||||
return self._notify(user["id"], chat, command == "/notify")
|
||||
if command == "/delete":
|
||||
return self._delete(user["id"], chat, rest)
|
||||
if user["id"] == self.owner:
|
||||
if command == "/ban":
|
||||
return self._ban(chat, rest)
|
||||
if command == "/unban":
|
||||
return self._unban(chat, rest)
|
||||
if command == "/who":
|
||||
return self._who(chat, rest)
|
||||
if command == "/stats":
|
||||
return self._stats(chat)
|
||||
self.say(chat, HELP)
|
||||
|
||||
def _start(self, tg_id, chat, token):
|
||||
if not token:
|
||||
return self.say(chat, HELP)
|
||||
reply = self.accounts.bot_link(token, tg_id)
|
||||
if reply["ok"]:
|
||||
if reply["registered"]:
|
||||
return self.say(chat, "Готово, вы вошли. Вернитесь в приложение Store.")
|
||||
return self.say(chat, "Готово. Вернитесь в приложение Store и выберите себе ник.")
|
||||
if reply["reason"] == "banned":
|
||||
until = reply.get("banned_until") or 0
|
||||
tail = "до %s" % _when(until) if until and until < 4_000_000_000 else "бессрочно"
|
||||
return self.say(chat, "Вход закрыт %s. Причина: %s. Обжалование: t.me/cheb0chik" % (tail, reply.get("ban_reason") or "правила"))
|
||||
return self.say(chat, "Ссылка устарела или уже использована. Нажмите «Войти через Telegram» в Store ещё раз.")
|
||||
|
||||
def _notify(self, tg_id, chat, on):
|
||||
with self.registry.connect() as db:
|
||||
changed = db.execute("UPDATE tg_accounts SET notify=? WHERE tg_id=?", (1 if on else 0, tg_id)).rowcount
|
||||
if not changed:
|
||||
return self.say(chat, "Сначала войдите через Store.")
|
||||
self.say(chat, "Уведомления включены." if on else "Уведомления выключены.")
|
||||
|
||||
def _delete(self, tg_id, chat, rest):
|
||||
asked = self._delete_asked.get(tg_id, 0)
|
||||
if rest.lower() == "yes" and asked > self.clock() - 300:
|
||||
self._delete_asked.pop(tg_id, None)
|
||||
self.accounts.delete_tg(tg_id)
|
||||
return self.say(chat, "Аккаунт удалён.")
|
||||
self._delete_asked[tg_id] = self.clock()
|
||||
self.say(chat, "Это удалит вход, подписки и привязку к TikTok. Если уверены, напишите в течение 5 минут: /delete yes")
|
||||
|
||||
# -- the owner's commands -----------------------------------------------------------------------------------------
|
||||
|
||||
def _ban(self, chat, rest):
|
||||
parts = rest.split(None, 2)
|
||||
if len(parts) < 2 or not parts[1].isdigit():
|
||||
return self.say(chat, "Формат: /ban A7K-3Q2 7 причина (7 дней; 0 = навсегда)")
|
||||
try:
|
||||
result = self.accounts.ban(parts[0], int(parts[1]), parts[2] if len(parts) > 2 else "")
|
||||
except ValueError as error:
|
||||
return self.say(chat, "Не получилось: %s" % error)
|
||||
until = "навсегда" if not result["until"] else "до " + _when(result["until"])
|
||||
self.say(chat, "Забанен %s %s (Telegram: %s, TikTok: %s)." % (result["pid"], until, "да" if result["tg"] else "нет",
|
||||
"да" if result["tiktok"] else "нет"))
|
||||
|
||||
def _unban(self, chat, rest):
|
||||
try:
|
||||
result = self.accounts.unban(rest.split()[0] if rest else "")
|
||||
except ValueError as error:
|
||||
return self.say(chat, "Не получилось: %s" % error)
|
||||
self.say(chat, "Бан снят с %s." % result["pid"])
|
||||
|
||||
def _who(self, chat, rest):
|
||||
try:
|
||||
info = self.accounts.who(rest.split()[0] if rest else "")
|
||||
except ValueError as error:
|
||||
return self.say(chat, "Не получилось: %s" % error)
|
||||
works = ", ".join("%s: %d" % item for item in sorted(info["works"].items())) or "нет"
|
||||
self.say(chat, "%s\nНик: %s\nTikTok: %s\nРаботы: %s\nПодписчики: %d\nБан: %s" % (
|
||||
info["pid"], info["handle"] or "нет", info["tiktok"] or "нет", works, info["followers"], "да" if info["banned"] else "нет"))
|
||||
|
||||
def _stats(self, chat):
|
||||
with self.registry.connect() as db:
|
||||
accounts = db.execute("SELECT COUNT(*) FROM tg_accounts WHERE handle IS NOT NULL").fetchone()[0]
|
||||
authors = db.execute("SELECT COUNT(*) FROM tg_tiktok").fetchone()[0]
|
||||
follows = db.execute("SELECT COUNT(*) FROM follows").fetchone()[0]
|
||||
self.say(chat, "Участников: %d\nАвторов (с TikTok): %d\nПодписок: %d" % (accounts, authors, follows))
|
||||
|
||||
# -- notifications --------------------------------------------------------------------------------------------------
|
||||
|
||||
def notify_new(self, art):
|
||||
"""Tells the followers of an author about a work that has just been accepted into the catalog."""
|
||||
if not art.get("listed"):
|
||||
return 0
|
||||
sent = 0
|
||||
author = self.accounts.handle_of_uid(art["uid"])
|
||||
text = "Новая %s в Store: «%s»%s\nОткройте LihonT Store, вкладка «Входящие»." % (
|
||||
"рамка" if art["kind"] == "frame" else "картинка для пузыря" if art["kind"] == "bubble" else "работа", art["name"],
|
||||
" от @" + author if author else "")
|
||||
for tg_id in self.accounts.followers_to_notify(art["uid"]):
|
||||
try:
|
||||
self.say(tg_id, text)
|
||||
sent += 1
|
||||
except RuntimeError as error:
|
||||
if "blocked" in str(error).lower() or "forbidden" in str(error).lower():
|
||||
self.accounts.mute(tg_id) # they stopped the bot: do not try again
|
||||
return sent
|
||||
|
||||
# -- the loop ---------------------------------------------------------------------------------------------------------
|
||||
|
||||
def poll_once(self, timeout=10):
|
||||
import json
|
||||
updates = self.telegram.call("getUpdates", {"offset": self.offset, "timeout": timeout,
|
||||
"allowed_updates": json.dumps(["message"])}, timeout=timeout + 15) or []
|
||||
for update in updates:
|
||||
self.offset = max(self.offset, int(update.get("update_id", 0)) + 1)
|
||||
try:
|
||||
self.handle(update)
|
||||
except Exception:
|
||||
pass
|
||||
return len(updates)
|
||||
|
||||
def run(self, stop: threading.Event):
|
||||
while not stop.is_set():
|
||||
try:
|
||||
self.poll_once()
|
||||
except Exception:
|
||||
stop.wait(5)
|
||||
|
||||
|
||||
def start(registry, token, owner_id):
|
||||
"""Runs the bot in a background thread; returns (the bot, the stop event)."""
|
||||
stop = threading.Event()
|
||||
bot = AuthBot(registry, modbot.Telegram(token), owner_id)
|
||||
threading.Thread(target=bot.run, args=(stop,), name="lihont-authbot", daemon=True).start()
|
||||
return bot, stop
|
||||
@@ -7,6 +7,7 @@ Everything the author sends is judged first by the AI and then by the owner (see
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import base64
|
||||
import hmac
|
||||
import re
|
||||
|
||||
@@ -32,7 +33,7 @@ class Catalog:
|
||||
self.r = registry
|
||||
self.operations = {
|
||||
"publish": self.publish, "catalog": self.listing, "item": self.item, "profile": self.profile,
|
||||
"mine": self.mine, "unpublish": self.unpublish, "install": self.install, "bubble_choose": self.choose_bubble,
|
||||
"mine": self.mine, "report": self.report, "unpublish": self.unpublish, "install": self.install, "bubble_choose": self.choose_bubble,
|
||||
"prove": self.prove, "library_add": self.library_add, "library_remove": self.library_remove, "library": self.library,
|
||||
}
|
||||
|
||||
@@ -44,7 +45,7 @@ class Catalog:
|
||||
def _page(self, where, args, cursor, limit):
|
||||
limit = limit if isinstance(limit, int) and 1 <= limit <= PAGE else PAGE
|
||||
sql = ("SELECT " + COLUMNS + " FROM art a WHERE a.status='approved' AND a.listed=1 "
|
||||
"AND a.uid NOT IN (SELECT uid FROM blocked)" + where)
|
||||
"AND a.uid NOT IN (SELECT uid FROM active_blocked)" + where)
|
||||
if cursor:
|
||||
match = CURSOR.fullmatch(cursor) if isinstance(cursor, str) else None
|
||||
if match is None:
|
||||
@@ -93,6 +94,8 @@ class Catalog:
|
||||
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 FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
||||
if owner is None or not hmac.compare_digest(owner[0], digest):
|
||||
raise ValueError("Prove the account first")
|
||||
@@ -109,6 +112,26 @@ class Catalog:
|
||||
"reason": r[5] if r[4] == "rejected" else "", "listed": bool(r[6]), "at": r[7], "installs": r[8]}
|
||||
for r in rows]}
|
||||
|
||||
def report(self, p):
|
||||
"""The detailed rejection report (PDF, base64) of one of this account's own pictures. Made now when it was not made at the time."""
|
||||
uid, art_id = p.get("uid"), str(p.get("id") or "")
|
||||
self._owner(uid, p.get("installation"))
|
||||
with self.r.connect() as db:
|
||||
row = db.execute("SELECT status FROM art WHERE id=? AND uid=?", (art_id, uid)).fetchone()
|
||||
if row is None or row[0] != "rejected":
|
||||
raise ValueError("No report for this picture")
|
||||
pdf = self.r.art_report(art_id)
|
||||
if pdf is None:
|
||||
import report
|
||||
data = self.r.art_bytes(art_id, approved_only=False)
|
||||
art = self.r.art(art_id)
|
||||
detail = report.detail_check(data) if data else {"ok": None}
|
||||
if detail["ok"] is None:
|
||||
raise ValueError("The report is not ready, try later")
|
||||
pdf = report.build_pdf(data, detail, name=art["name"], kind=art["kind"], art_id=art_id)
|
||||
self.r.art_report_save(art_id, pdf)
|
||||
return {"ok": True, "pdf": base64.b64encode(pdf).decode("ascii")}
|
||||
|
||||
def publish(self, p):
|
||||
"""Lists a picture in the catalog. It goes to the AI and then to the owner; until approved it is not shown to anyone."""
|
||||
kind = p.get("kind")
|
||||
@@ -160,7 +183,7 @@ class Catalog:
|
||||
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 blocked WHERE uid=?", (uid,)).fetchone():
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
||||
raise ValueError("Account excluded")
|
||||
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
||||
if owner is not None and hmac.compare_digest(owner[0], digest):
|
||||
@@ -215,7 +238,7 @@ class Catalog:
|
||||
raise ValueError("Unknown bubble")
|
||||
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
|
||||
with self.r.connect() as db:
|
||||
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
||||
raise ValueError("Account excluded")
|
||||
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
||||
has = db.execute("SELECT 1 FROM account_bubbles WHERE uid=?", (uid,)).fetchone()
|
||||
@@ -247,5 +270,5 @@ class Catalog:
|
||||
with self.r.connect() as db:
|
||||
rows = db.execute("SELECT b.uid, b.art_id FROM account_bubbles b JOIN art a ON a.id = b.art_id "
|
||||
"WHERE b.uid IN (" + marks + ") AND a.status='approved' AND a.kind='bubble' "
|
||||
"AND b.uid NOT IN (SELECT uid FROM blocked)", list(uids)).fetchall()
|
||||
"AND b.uid NOT IN (SELECT uid FROM active_blocked)", list(uids)).fetchall()
|
||||
return {uid: art_id for uid, art_id in rows}
|
||||
|
||||
@@ -20,6 +20,7 @@ MAX_UPLOAD = 400_000
|
||||
MAX_PIXELS = 16_000_000
|
||||
FRAME_SIDE = 256
|
||||
BUBBLE_SIDE = 512
|
||||
PET_SIDE = 512 # the picture of a pair's "Серийчик" (the streak pet): kept whole, at most this wide or tall
|
||||
MAX_PNG = 150 * 1024
|
||||
|
||||
|
||||
|
||||
222
services/members/report.py
Normal file
@@ -0,0 +1,222 @@
|
||||
"""The detailed rejection report: what the AI saw, where, and how to appeal, as a one-page PDF.
|
||||
|
||||
An upload that the AI rejects gets a short reason at once. On request the author can get this report: the picture with the parts that
|
||||
triggered the rejection marked by red squares, the model and the time of the check, the contact and the appeal terms. The squares come
|
||||
from the same vision model (it answers with boxes in 0..1000 of the picture width and height); a box that makes no sense is dropped,
|
||||
and a verdict without any box still gives a report, just without squares.
|
||||
|
||||
The page is drawn with Pillow only (no other PDF library), in A4 at 150 dpi.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import textwrap
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
try:
|
||||
from . import moderation
|
||||
except ImportError: # run as a plain script next to moderation.py
|
||||
import moderation
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
CONTACT = "t.me/cheb0chik"
|
||||
APPEAL = ("Просим не требовать мгновенной публикации ресурса при обжаловании: "
|
||||
"жалоба будет рассмотрена в течение 1 рабочего дня.")
|
||||
NOTE = "Решение ИИ предварительное. Окончательное решение по спорной работе принимает человек."
|
||||
MAX_REGIONS = 6
|
||||
|
||||
DETAIL_ANSWER = (
|
||||
"Reply with one JSON object and nothing else: "
|
||||
'{"verdict": "pass" or "review" or "reject", "reason": "up to 12 words, English", "reason_ru": "до 12 слов по-русски", '
|
||||
'"regions": [{"label": "short English label", "label_ru": "коротко по-русски", "box": [x1, y1, x2, y2]}]}. '
|
||||
"List EVERY separate problem you see, one region each, not only the first one. "
|
||||
"Each box is in the range 0..1000, relative to the picture width and height (x1,y1 top left; x2,y2 bottom right), TIGHT around "
|
||||
"that one element (for example the exposed legs, a logo, a face), never around the whole picture or an empty area; name the "
|
||||
"exact element in the label. Use an empty list when the verdict is pass."
|
||||
)
|
||||
|
||||
FONT_REGULAR = ("DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "segoeui.ttf", "arial.ttf")
|
||||
FONT_BOLD = ("DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "segoeuib.ttf", "arialbd.ttf")
|
||||
|
||||
|
||||
def _font(names, size):
|
||||
for name in names:
|
||||
try:
|
||||
return ImageFont.truetype(name, size)
|
||||
except OSError:
|
||||
continue
|
||||
raise RuntimeError("no font with Cyrillic found")
|
||||
|
||||
|
||||
def detail_check(png: bytes, post=moderation.chain_post) -> dict:
|
||||
"""The AI verdict with regions: {"ok", "reason", "reason_ru", "regions": [{"label", "label_ru", "box": [x1,y1,x2,y2] in 0..1}], "model"}.
|
||||
|
||||
ok is None when the check could not be made."""
|
||||
import base64
|
||||
url = "data:image/png;base64," + base64.b64encode(png).decode("ascii")
|
||||
body = {
|
||||
"model": moderation.IMAGE_MODEL, "temperature": 0, "max_tokens": 600,
|
||||
"messages": [
|
||||
{"role": "system", "content": moderation.POLICY + " " + DETAIL_ANSWER},
|
||||
{"role": "user", "content": [{"type": "text", "text": "Screen this picture."},
|
||||
{"type": "image_url", "image_url": {"url": url}}]},
|
||||
],
|
||||
}
|
||||
result = {"ok": None, "review": False, "reason": "", "reason_ru": "", "regions": [], "model": moderation.IMAGE_MODEL}
|
||||
if post is moderation.chain_post and not moderation.providers("image"):
|
||||
result["reason"] = "no key"
|
||||
return result
|
||||
try:
|
||||
reply = post(body)
|
||||
text = reply["choices"][0]["message"]["content"] or ""
|
||||
if reply.get("_model"):
|
||||
result["model"] = "%s (%s)" % (reply["_model"], reply.get("_provider", ""))
|
||||
except Exception as error: # network, quota, bad gateway
|
||||
result["reason"] = type(error).__name__
|
||||
return result
|
||||
text = re.sub(r"<think>.*?</think>", "", text, flags=re.S).strip()
|
||||
match = re.search(r"\{.*\}", text, flags=re.S)
|
||||
try:
|
||||
data = json.loads(match.group(0)) if match else None
|
||||
except ValueError:
|
||||
data = None
|
||||
word = data.get("verdict") if isinstance(data, dict) else None
|
||||
if word not in ("pass", "review", "reject"):
|
||||
result["reason"] = "not json"
|
||||
return result
|
||||
result["ok"] = word != "reject"
|
||||
result["review"] = word == "review"
|
||||
result["reason"] = str(data.get("reason") or "")[:moderation.REASON_MAX]
|
||||
result["reason_ru"] = str(data.get("reason_ru") or "")[:moderation.REASON_MAX]
|
||||
width, height = Image.open(io.BytesIO(png)).size
|
||||
longest = max(width, height)
|
||||
for region in (data.get("regions") or [])[:MAX_REGIONS]:
|
||||
box = region.get("box") if isinstance(region, dict) else None
|
||||
if not (isinstance(box, list) and len(box) == 4 and all(isinstance(v, (int, float)) for v in box)):
|
||||
continue
|
||||
# the model measures both axes against the LONGER side of the picture (it sees it padded to a square), so a wide picture
|
||||
# has its boxes squeezed into the top part: scale back by the longer side, then to fractions of each side
|
||||
x1, y1, x2, y2 = (min(1.0, max(0.0, box[0] / 1000.0 * longest / width)), min(1.0, max(0.0, box[1] / 1000.0 * longest / height)),
|
||||
min(1.0, max(0.0, box[2] / 1000.0 * longest / width)), min(1.0, max(0.0, box[3] / 1000.0 * longest / height)))
|
||||
if x2 - x1 < 0.02 or y2 - y1 < 0.02: # a box with no area is no box
|
||||
continue
|
||||
result["regions"].append({"label": str(region.get("label") or "")[:60], "label_ru": str(region.get("label_ru") or "")[:60],
|
||||
"box": [x1, y1, x2, y2]})
|
||||
return result
|
||||
|
||||
|
||||
def _wrap(draw, text, font, width):
|
||||
"""Lines of text that fit the width in pixels."""
|
||||
lines = []
|
||||
for paragraph in text.split("\n"):
|
||||
words, line = paragraph.split(" "), ""
|
||||
for word in words:
|
||||
trial = (line + " " + word).strip()
|
||||
if draw.textlength(trial, font=font) <= width or not line:
|
||||
line = trial
|
||||
else:
|
||||
lines.append(line)
|
||||
line = word
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
def _marked_picture(png: bytes, regions: list, width: int) -> Image.Image:
|
||||
picture = Image.open(io.BytesIO(png)).convert("RGBA")
|
||||
ground = Image.new("RGBA", picture.size, (236, 236, 240, 255))
|
||||
ground.alpha_composite(picture)
|
||||
height = max(1, int(ground.height * width / ground.width))
|
||||
shown = ground.convert("RGB").resize((width, height), Image.Resampling.LANCZOS)
|
||||
draw = ImageDraw.Draw(shown)
|
||||
tag = _font(FONT_BOLD, 26)
|
||||
for number, region in enumerate(regions, 1):
|
||||
x1, y1, x2, y2 = (region["box"][0] * width, region["box"][1] * height, region["box"][2] * width, region["box"][3] * height)
|
||||
draw.rectangle([x1, y1, x2, y2], outline=(214, 40, 57), width=5)
|
||||
side = 38
|
||||
top = y1 - side if y1 - side >= 0 else y1
|
||||
draw.rectangle([x1, top, x1 + side, top + side], fill=(214, 40, 57))
|
||||
draw.text((x1 + side / 2, top + side / 2), str(number), font=tag, fill=(255, 255, 255), anchor="mm")
|
||||
return shown
|
||||
|
||||
|
||||
def render_page(png: bytes, detail: dict, *, name: str, kind: str, art_id: str, when: datetime | None = None) -> Image.Image:
|
||||
"""The one-page report as a picture."""
|
||||
when = when or datetime.now(timezone.utc)
|
||||
moscow = when.astimezone(timezone(timedelta(hours=3)))
|
||||
w, h, margin = 1240, 1754, 90
|
||||
page = Image.new("RGB", (w, h), (255, 255, 255))
|
||||
draw = ImageDraw.Draw(page)
|
||||
ink, grey, red, violet = (24, 24, 28), (110, 110, 120), (214, 40, 57), (92, 56, 168)
|
||||
draw.rectangle([0, 0, w, 150], fill=violet)
|
||||
draw.text((margin, 75), "LihonT · подробный отчёт об отклонении", font=_font(FONT_BOLD, 44), fill=(255, 255, 255), anchor="lm")
|
||||
y = 200
|
||||
rows = [("Ресурс", "%s «%s»" % ("рамка" if kind == "frame" else "пузырь чата" if kind == "bubble" else kind, name)),
|
||||
("Номер", art_id[:12]),
|
||||
("Время проверки", moscow.strftime("%d.%m.%Y %H:%M") + " МСК"),
|
||||
("Модель ИИ", detail.get("model", "")),
|
||||
("Решение", "отклонено" if detail.get("ok") is False else "спорное, смотрит человек" if detail.get("review")
|
||||
else "принято" if detail.get("ok") else "не проверено")]
|
||||
label_font, value_font = _font(FONT_REGULAR, 30), _font(FONT_BOLD, 30)
|
||||
for label, value in rows:
|
||||
draw.text((margin, y), label, font=label_font, fill=grey)
|
||||
draw.text((margin + 330, y), value, font=value_font, fill=ink)
|
||||
y += 52
|
||||
y += 20
|
||||
reason = detail.get("reason_ru") or detail.get("reason") or "—"
|
||||
draw.text((margin, y), "Причина", font=label_font, fill=grey)
|
||||
y += 46
|
||||
body = _font(FONT_BOLD, 34)
|
||||
for line in _wrap(draw, reason, body, w - 2 * margin):
|
||||
draw.text((margin, y), line, font=body, fill=red if detail.get("ok") is False else ink)
|
||||
y += 46
|
||||
if detail.get("reason") and detail.get("reason_ru"): # the AI's own words as well
|
||||
small = _font(FONT_REGULAR, 26)
|
||||
for line in _wrap(draw, "Оригинальный ответ ИИ: " + detail["reason"], small, w - 2 * margin):
|
||||
draw.text((margin, y), line, font=small, fill=grey)
|
||||
y += 36
|
||||
y += 24
|
||||
marked = _marked_picture(png, detail.get("regions", []), min(w - 2 * margin, 900))
|
||||
page.paste(marked, (margin, y))
|
||||
draw.rectangle([margin - 1, y - 1, margin + marked.width, y + marked.height], outline=(200, 200, 208), width=2)
|
||||
y += marked.height + 30
|
||||
regions = detail.get("regions", [])
|
||||
item = _font(FONT_REGULAR, 28)
|
||||
if regions:
|
||||
draw.text((margin, y), "Что сработало (красные квадраты):", font=label_font, fill=grey)
|
||||
y += 46
|
||||
for number, region in enumerate(regions, 1):
|
||||
text = "%d. %s" % (number, region.get("label_ru") or region.get("label") or "область")
|
||||
if region.get("label") and region.get("label_ru"):
|
||||
text += " (%s)" % region["label"]
|
||||
for line in _wrap(draw, text, item, w - 2 * margin):
|
||||
draw.text((margin, y), line, font=item, fill=ink)
|
||||
y += 40
|
||||
elif detail.get("ok") is False:
|
||||
draw.text((margin, y), "ИИ не указал отдельное место: вердикт относится ко всей картинке.", font=item, fill=grey)
|
||||
y += 44
|
||||
y = max(y + 40, h - 470)
|
||||
draw.line([(margin, y), (w - margin, y)], fill=(220, 220, 226), width=3)
|
||||
y += 30
|
||||
draw.text((margin, y), "Если вы не согласны", font=_font(FONT_BOLD, 34), fill=ink)
|
||||
y += 56
|
||||
draw.text((margin, y), "Контакт: " + CONTACT, font=_font(FONT_BOLD, 32), fill=violet)
|
||||
y += 56
|
||||
for line in _wrap(draw, APPEAL, item, w - 2 * margin):
|
||||
draw.text((margin, y), line, font=item, fill=ink)
|
||||
y += 40
|
||||
y += 16
|
||||
small = _font(FONT_REGULAR, 25)
|
||||
for line in _wrap(draw, NOTE, small, w - 2 * margin):
|
||||
draw.text((margin, y), line, font=small, fill=grey)
|
||||
y += 34
|
||||
return page
|
||||
|
||||
|
||||
def build_pdf(png: bytes, detail: dict, **info) -> bytes:
|
||||
"""The one-page report as PDF bytes."""
|
||||
out = io.BytesIO()
|
||||
render_page(png, detail, **info).save(out, "PDF", resolution=150.0, title="LihonT: отчёт об отклонении", author="LihonT")
|
||||
return out.getvalue()
|
||||
@@ -29,6 +29,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import accounts
|
||||
import catalog
|
||||
import community
|
||||
from community import INSTALL, UID, valid_uid
|
||||
@@ -45,15 +46,20 @@ GRANT = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\.(\*|[a-z0-9][a-z0-9_-]{0,23})\Z")
|
||||
# A frame a member made: "u." and the first 24 hex digits of the picture's SHA-256.
|
||||
CUSTOM = re.compile(r"u\.[0-9a-f]{24}\Z")
|
||||
ART_STATES = ("new", "review", "approved", "rejected")
|
||||
SPECIES = ("cat", "dog", "lion") # the animals the mod can draw; a new one is added here and in the mod
|
||||
UPLOAD_BODY = 300_000
|
||||
# Operations by how often one address may call them: reads, the account's own small writes, installs, uploads.
|
||||
READS = ("lookup", "pair_lookup", "catalog", "item", "profile", "library")
|
||||
WRITES = ("shape", "avatar_frame", "mine", "unpublish", "bubble_choose", "prove", "library_add", "library_remove")
|
||||
UPLOADS = ("frame_upload", "bubble_upload", "publish")
|
||||
CATALOG = ("publish", "catalog", "item", "profile", "mine", "unpublish", "install", "bubble_choose", "prove", "library_add",
|
||||
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")
|
||||
READS = ("lookup", "pair_lookup", "pet_lookup", "species_lookup", "catalog", "item", "profile", "library", "tg_poll", "tg_me", "following", "followers", "follow_info", "inbox")
|
||||
WRITES = ("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")
|
||||
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") + CATALOG
|
||||
"pair_lookup", "pair_clear", "pet_upload", "pet_lookup", "pet_revert", "pet_clear",
|
||||
"species_offer", "species_lookup", "species_answer") + CATALOG + ACCOUNTS
|
||||
# The niche-mod badge can be claimed until this moment (Moscow time).
|
||||
CLAIM_DEADLINE = 1794735240 # 2026-11-15 12:34:00 +03:00
|
||||
|
||||
@@ -95,6 +101,11 @@ class Registry:
|
||||
db.execute("ALTER TABLE presence ADD COLUMN frame_color TEXT NOT NULL DEFAULT 'green'")
|
||||
db.execute("CREATE INDEX IF NOT EXISTS presence_uid ON presence(uid, last_seen)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS blocked (uid TEXT PRIMARY KEY)")
|
||||
if "until" not in {row[1] for row in db.execute("PRAGMA table_info(blocked)")}:
|
||||
db.execute("ALTER TABLE blocked ADD COLUMN until INTEGER NOT NULL DEFAULT 0") # 0 = for ever
|
||||
# what every check reads: the rows whose ban has not run out
|
||||
db.execute("CREATE VIEW IF NOT EXISTS active_blocked AS SELECT uid FROM blocked "
|
||||
"WHERE until = 0 OR until > CAST(strftime('%s','now') AS INTEGER)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS supporters (uid TEXT PRIMARY KEY, granted_at INTEGER NOT NULL)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS niche (uid TEXT PRIMARY KEY, unique_id TEXT NOT NULL, granted_at INTEGER NOT NULL)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS shapes (uid TEXT PRIMARY KEY, shape TEXT NOT NULL, updated_at INTEGER NOT NULL)")
|
||||
@@ -105,6 +116,13 @@ class Registry:
|
||||
"sha256 TEXT NOT NULL, status TEXT NOT NULL, reason TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, "
|
||||
"decided_at INTEGER, review_message INTEGER)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS pair_art (pair TEXT PRIMARY KEY, art_id TEXT NOT NULL, set_by TEXT NOT NULL, updated_at INTEGER NOT NULL)")
|
||||
# the "Серийчик" of a pair: every change is a row, the newest approved one is shown, the older ones can be brought back
|
||||
db.execute("CREATE TABLE IF NOT EXISTS pair_pet (id INTEGER PRIMARY KEY AUTOINCREMENT, pair TEXT NOT NULL, art_id TEXT NOT NULL, "
|
||||
"set_by TEXT NOT NULL, at INTEGER NOT NULL)")
|
||||
db.execute("CREATE INDEX IF NOT EXISTS pair_pet_pair ON pair_pet(pair, id)")
|
||||
# the animal of a pair: one word, no picture. `kind` is what both see; an offer waits until the other one accepts it
|
||||
db.execute("CREATE TABLE IF NOT EXISTS pair_species (pair TEXT PRIMARY KEY, kind TEXT NOT NULL DEFAULT '', "
|
||||
"offer TEXT NOT NULL DEFAULT '', offer_by TEXT NOT NULL DEFAULT '', at INTEGER NOT NULL)")
|
||||
for column, ddl in (("description", "TEXT NOT NULL DEFAULT ''"), ("listed", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("listed_at", "INTEGER NOT NULL DEFAULT 0"), ("installs", "INTEGER NOT NULL DEFAULT 0")):
|
||||
if column not in {row[1] for row in db.execute("PRAGMA table_info(art)")}:
|
||||
@@ -117,6 +135,7 @@ class Registry:
|
||||
db.execute("CREATE INDEX IF NOT EXISTS art_uid ON art(uid, created_at)")
|
||||
db.execute("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
||||
db.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('code_secret',?)", (secrets.token_hex(32),))
|
||||
self.accounts = accounts.Accounts(self)
|
||||
|
||||
@contextmanager
|
||||
def connect(self):
|
||||
@@ -139,7 +158,7 @@ class Registry:
|
||||
if withdraw:
|
||||
db.execute("DELETE FROM presence WHERE installation=? AND uid=?", (digest, uid))
|
||||
else:
|
||||
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
||||
raise ValueError("Account excluded from the registry")
|
||||
existing = db.execute("SELECT 1 FROM presence WHERE installation=? AND uid=?", (digest, uid)).fetchone()
|
||||
if not existing and db.execute("SELECT COUNT(*) FROM presence WHERE installation=?", (digest,)).fetchone()[0] >= 20:
|
||||
@@ -147,14 +166,34 @@ class Registry:
|
||||
db.execute("INSERT INTO presence(installation,uid,last_seen,frame_color) VALUES(?,?,?,?) ON CONFLICT(installation,uid) DO UPDATE SET last_seen=excluded.last_seen,frame_color=excluded.frame_color", (digest, uid, now, frame_color))
|
||||
return {"ok": True}
|
||||
|
||||
def code(self, uid):
|
||||
"""The proof string for an account: it only ever goes into that account's own bio."""
|
||||
def code(self, uid, installation_digest=None):
|
||||
"""The proof string for an account: it only ever goes into that account's own bio.
|
||||
|
||||
With `installation_digest` (the SHA-256 of the installation secret) the code belongs to that one installation as well: a code
|
||||
that stays visible in someone's bio proves nothing to any other installation, so it cannot be replayed to take the account over.
|
||||
Without it the code is the old one that only knows the account; the niche-mod badge still uses that."""
|
||||
if not valid_uid(uid):
|
||||
raise ValueError("Invalid account ID")
|
||||
with self.connect() as db:
|
||||
secret = db.execute("SELECT value FROM meta WHERE key='code_secret'").fetchone()[0]
|
||||
digest = hmac.new(bytes.fromhex(secret), uid.encode("ascii"), "sha256").digest()
|
||||
return "LT-" + base64.b32encode(digest)[:8].decode("ascii")
|
||||
message = uid if installation_digest is None else uid + ":" + installation_digest
|
||||
digest = hmac.new(bytes.fromhex(secret), message.encode("ascii"), "sha256").digest()
|
||||
length = 8 if installation_digest is None else 9 # the code of an installation is nine letters and digits after "LT-"
|
||||
return "LT-" + base64.b32encode(digest)[:length].decode("ascii")
|
||||
|
||||
FETCH_PER_HOUR = 60 # profile reads of every kind, all accounts together: the server is a polite visitor of tiktok.com
|
||||
|
||||
def _fetch_budget(self):
|
||||
"""Keeps the number of TikTok profile reads low so the server's address is not taken for a bot."""
|
||||
now = self.clock()
|
||||
window = getattr(self, "_fetches", None)
|
||||
if window is None:
|
||||
window = self._fetches = []
|
||||
while window and window[0] < now - 3600:
|
||||
window.pop(0)
|
||||
if len(window) >= self.FETCH_PER_HOUR:
|
||||
raise ValueError("Too many proofs right now, try again in a while")
|
||||
window.append(now)
|
||||
|
||||
def claim(self, uid, unique_id):
|
||||
"""Gives the niche-mod badge to `uid` when its public bio holds the account's code."""
|
||||
@@ -163,10 +202,11 @@ class Registry:
|
||||
with self.connect() as db:
|
||||
if db.execute("SELECT 1 FROM niche WHERE uid=?", (uid,)).fetchone():
|
||||
return {"ok": True, "granted": True}
|
||||
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
||||
raise ValueError("Account excluded")
|
||||
if self.clock() > CLAIM_DEADLINE:
|
||||
raise ValueError("The badge can no longer be claimed")
|
||||
self._fetch_budget()
|
||||
try:
|
||||
profile = self.fetcher(unique_id)
|
||||
except Exception:
|
||||
@@ -196,7 +236,7 @@ class Registry:
|
||||
raise ValueError("Unknown shape")
|
||||
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
|
||||
with self.connect() as db:
|
||||
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
||||
raise ValueError("Account excluded")
|
||||
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
||||
has_shape = db.execute("SELECT 1 FROM shapes WHERE uid=?", (uid,)).fetchone()
|
||||
@@ -221,7 +261,8 @@ class Registry:
|
||||
|
||||
Returns None once the installation is bound, else the reply that tells the client what is missing."""
|
||||
if not isinstance(unique_id, str) or not UNIQUE.fullmatch(unique_id):
|
||||
return {"ok": True, "published": False, "reason": "proof_needed", "code": self.code(uid)}
|
||||
return {"ok": True, "published": False, "reason": "proof_needed", "code": self.code(uid, digest)}
|
||||
self._fetch_budget()
|
||||
try:
|
||||
profile = self.fetcher(unique_id)
|
||||
except Exception:
|
||||
@@ -231,8 +272,8 @@ class Registry:
|
||||
found_uid, bio = profile
|
||||
if found_uid != uid:
|
||||
raise ValueError("That profile belongs to another account")
|
||||
if self.code(uid) not in bio:
|
||||
return {"ok": True, "published": False, "reason": "code_missing", "code": self.code(uid)}
|
||||
if self.code(uid, digest) not in bio:
|
||||
return {"ok": True, "published": False, "reason": "code_missing", "code": self.code(uid, digest)}
|
||||
with self.connect() as db:
|
||||
db.execute("INSERT INTO shape_owner(uid,installation,unique_id,verified_at) VALUES(?,?,?,?) "
|
||||
"ON CONFLICT(uid) DO UPDATE SET installation=excluded.installation,"
|
||||
@@ -257,7 +298,7 @@ class Registry:
|
||||
raise ValueError("This frame is not available for this account")
|
||||
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
|
||||
with self.connect() as db:
|
||||
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
||||
raise ValueError("Account excluded")
|
||||
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
||||
has_frame = db.execute("SELECT 1 FROM avatar_frames WHERE uid=?", (uid,)).fetchone()
|
||||
@@ -285,18 +326,18 @@ class Registry:
|
||||
return {"members": {}}
|
||||
placeholders = ",".join("?" for _ in uids)
|
||||
with self.connect() as db:
|
||||
rows = db.execute("SELECT uid,frame_color FROM presence WHERE uid IN (" + placeholders + ") AND last_seen >= ? AND uid NOT IN (SELECT uid FROM blocked)", uids + [int(self.clock()) - LIFETIME]).fetchall()
|
||||
rows = db.execute("SELECT uid,frame_color FROM presence WHERE uid IN (" + placeholders + ") AND last_seen >= ? AND uid NOT IN (SELECT uid FROM active_blocked)", uids + [int(self.clock()) - LIFETIME]).fetchall()
|
||||
niche = {row[0] for row in db.execute(
|
||||
"SELECT uid FROM niche WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM blocked)", uids
|
||||
"SELECT uid FROM niche WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM active_blocked)", uids
|
||||
).fetchall()}
|
||||
supporters = {row[0] for row in db.execute(
|
||||
"SELECT uid FROM supporters WHERE uid IN (" + placeholders + ")", uids
|
||||
).fetchall()}
|
||||
shapes = {row[0]: row[1] for row in db.execute(
|
||||
"SELECT uid,shape FROM shapes WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM blocked)", uids
|
||||
"SELECT uid,shape FROM shapes WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM active_blocked)", uids
|
||||
).fetchall() if row[1] in SHAPES}
|
||||
frames_of = {row[0]: row[1] for row in db.execute(
|
||||
"SELECT uid,frame FROM avatar_frames WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM blocked)", uids
|
||||
"SELECT uid,frame FROM avatar_frames WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM active_blocked)", uids
|
||||
).fetchall() if FRAME.fullmatch(row[1])}
|
||||
grants = {}
|
||||
for row in db.execute("SELECT uid,frame FROM frame_grants WHERE uid IN (" + placeholders + ")", uids).fetchall():
|
||||
@@ -338,6 +379,20 @@ class Registry:
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
def art_report_save(self, art_id, pdf: bytes):
|
||||
"""The detailed rejection report of one picture (PDF), kept beside the pictures."""
|
||||
self.art_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = self.art_dir / (art_id + ".report.pdf")
|
||||
part = self.art_dir / (art_id + ".report.part")
|
||||
part.write_bytes(pdf)
|
||||
os.replace(part, target)
|
||||
|
||||
def art_report(self, art_id):
|
||||
try:
|
||||
return (self.art_dir / (art_id + ".report.pdf")).read_bytes()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
def art_in_state(self, status, limit=5):
|
||||
with self.connect() as db:
|
||||
rows = db.execute("SELECT id FROM art WHERE status=? ORDER BY created_at LIMIT ?", (status, limit)).fetchall()
|
||||
@@ -363,7 +418,7 @@ class Registry:
|
||||
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
|
||||
now = int(self.clock())
|
||||
with self.connect() as db:
|
||||
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
||||
raise ValueError("Account excluded")
|
||||
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
||||
waiting = db.execute("SELECT COUNT(*) FROM art WHERE uid=? AND status IN ('new','review')", (uid,)).fetchone()[0]
|
||||
@@ -439,7 +494,7 @@ class Registry:
|
||||
if owner is None or not hmac.compare_digest(owner[0], digest):
|
||||
return {"id": None}
|
||||
row = db.execute("SELECT art_id FROM pair_art WHERE pair=?", (key,)).fetchone()
|
||||
blocked = db.execute("SELECT 1 FROM blocked WHERE uid IN (?,?)", (uid, peer)).fetchone()
|
||||
blocked = db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone()
|
||||
if row is None or blocked or row[0] not in self.approved_ids([row[0]]):
|
||||
return {"id": None}
|
||||
return {"id": row[0]}
|
||||
@@ -455,6 +510,153 @@ class Registry:
|
||||
db.execute("DELETE FROM pair_art WHERE pair=?", (key,))
|
||||
return {"ok": True}
|
||||
|
||||
# ---- the "Серийчик" of a pair: one picture for the two, either of them may change it ----------------------------------
|
||||
|
||||
PET_COOLDOWN = 3600 # a pair changes its picture once an hour
|
||||
PET_HISTORY = 5 # how many earlier pictures can be brought back
|
||||
|
||||
def _proven(self, uid, installation) -> bool:
|
||||
if 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.connect() as db:
|
||||
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
||||
return owner is not None and hmac.compare_digest(owner[0], digest)
|
||||
|
||||
def _pet_cooldown(self, key):
|
||||
with self.connect() as db:
|
||||
last = db.execute("SELECT at FROM pair_pet WHERE pair=? ORDER BY id DESC LIMIT 1", (key,)).fetchone()
|
||||
if last and int(self.clock()) - last[0] < self.PET_COOLDOWN:
|
||||
raise ValueError("The picture of the pair can be changed once an hour")
|
||||
|
||||
def pet_upload(self, uid, installation, unique_id, peer, name, data):
|
||||
"""Either of the two sends a new picture for their "Серийчик". It waits for the AI and the owner; until it is approved the
|
||||
earlier one stays."""
|
||||
key = self.pair_key(uid, peer)
|
||||
if valid_uid(uid) and self._proven(uid, installation):
|
||||
try:
|
||||
raw = base64.b64decode(data, validate=True) if isinstance(data, str) else b""
|
||||
same = hashlib.sha256(community.normalize_png(raw, community.PET_SIDE, square=False)).hexdigest()[:24]
|
||||
except (ValueError, TypeError):
|
||||
same = None # the real check of the picture comes in _receive and says what is wrong
|
||||
with self.connect() as db:
|
||||
last = db.execute("SELECT art_id FROM pair_pet WHERE pair=? ORDER BY id DESC LIMIT 1", (key,)).fetchone()
|
||||
if same is not None and last and last[0] == same and self.art(same):
|
||||
return {"ok": True, "published": True, "id": same, "status": self.art(same)["status"]} # the picture it already is
|
||||
self._pet_cooldown(key) # checked before the picture is taken, so a refused change costs nobody a review
|
||||
got = self._receive("pet", uid, installation, unique_id, name or "Серийчик", data, community.PET_SIDE, False)
|
||||
if "art" not in got:
|
||||
return got
|
||||
art = got["art"]
|
||||
now = int(self.clock())
|
||||
with self.connect() as db:
|
||||
last = db.execute("SELECT art_id FROM pair_pet WHERE pair=? ORDER BY id DESC LIMIT 1", (key,)).fetchone()
|
||||
if not last or last[0] != art["id"]:
|
||||
db.execute("INSERT INTO pair_pet(pair, art_id, set_by, at) VALUES(?,?,?,?)", (key, art["id"], uid, now))
|
||||
return {"ok": True, "published": True, "id": art["id"], "status": art["status"]}
|
||||
|
||||
def pet_lookup(self, uid, installation, peer):
|
||||
"""What the two see: the newest approved picture, whether a newer one waits, and the earlier approved ones (to bring back)."""
|
||||
key = self.pair_key(uid, peer)
|
||||
if not self._proven(uid, installation):
|
||||
return {"id": None, "pending": False, "history": []}
|
||||
with self.connect() as db:
|
||||
rows = db.execute("SELECT art_id FROM pair_pet WHERE pair=? ORDER BY id DESC LIMIT ?", (key, self.PET_HISTORY + 8)).fetchall()
|
||||
blocked = db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone()
|
||||
ids = []
|
||||
for row in rows:
|
||||
if row[0] not in ids:
|
||||
ids.append(row[0])
|
||||
approved = self.approved_ids(ids) if ids else set()
|
||||
if blocked or not ids:
|
||||
return {"id": None, "pending": False, "history": []}
|
||||
shown = [i for i in ids if i in approved]
|
||||
current = shown[0] if shown else None
|
||||
return {"id": current, "pending": ids[0] not in approved, "history": shown[1:1 + self.PET_HISTORY]}
|
||||
|
||||
def pet_revert(self, uid, installation, peer, art_id):
|
||||
"""Brings back one of the earlier approved pictures of the pair (it counts as a change: once an hour)."""
|
||||
key = self.pair_key(uid, peer)
|
||||
if not self._proven(uid, installation):
|
||||
raise ValueError("Prove the account first")
|
||||
if not isinstance(art_id, str) or not re.fullmatch(r"[0-9a-f]{24}", art_id):
|
||||
raise ValueError("Unknown picture")
|
||||
with self.connect() as db:
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone():
|
||||
raise ValueError("Account excluded")
|
||||
known = db.execute("SELECT 1 FROM pair_pet WHERE pair=? AND art_id=?", (key, art_id)).fetchone()
|
||||
if not known or art_id not in self.approved_ids([art_id]):
|
||||
raise ValueError("Unknown picture")
|
||||
self._pet_cooldown(key)
|
||||
with self.connect() as db:
|
||||
db.execute("INSERT INTO pair_pet(pair, art_id, set_by, at) VALUES(?,?,?,?)", (key, art_id, uid, int(self.clock())))
|
||||
return {"ok": True, "id": art_id}
|
||||
|
||||
def pet_clear(self, uid, installation, peer):
|
||||
"""Either side takes the picture away (the history goes with it)."""
|
||||
key = self.pair_key(uid, peer)
|
||||
if not self._proven(uid, installation):
|
||||
raise ValueError("Prove the account first")
|
||||
with self.connect() as db:
|
||||
db.execute("DELETE FROM pair_pet WHERE pair=?", (key,))
|
||||
return {"ok": True}
|
||||
|
||||
# ---- the animal of a pair: "kitten", "puppy", "lion cub" ... offered by link, accepted by the other one ---------------------
|
||||
|
||||
SPECIES_OFFER_LIFE = 7 * 86400 # an offer that nobody answered goes stale after a week
|
||||
|
||||
def _species_row(self, key):
|
||||
with self.connect() as db:
|
||||
row = db.execute("SELECT kind, offer, offer_by, at FROM pair_species WHERE pair=?", (key,)).fetchone()
|
||||
return row or ("", "", "", 0)
|
||||
|
||||
def species_offer(self, uid, installation, peer, kind):
|
||||
"""One of the two gives the pair an animal. It becomes theirs when the other accepts; their own animal does not change before."""
|
||||
key = self.pair_key(uid, peer)
|
||||
if not self._proven(uid, installation):
|
||||
raise ValueError("Prove the account first")
|
||||
if kind not in SPECIES:
|
||||
raise ValueError("Unknown animal")
|
||||
with self.connect() as db:
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone():
|
||||
raise ValueError("Account excluded")
|
||||
current, _, _, _ = self._species_row(key)
|
||||
db.execute("INSERT INTO pair_species(pair, kind, offer, offer_by, at) VALUES(?,?,?,?,?) "
|
||||
"ON CONFLICT(pair) DO UPDATE SET offer=excluded.offer, offer_by=excluded.offer_by, at=excluded.at",
|
||||
(key, current, kind, uid, int(self.clock())))
|
||||
return {"ok": True, "kind": kind}
|
||||
|
||||
def species_lookup(self, uid, installation, peer):
|
||||
"""What the two see: the animal they have, and an offer from the other one that waits for an answer."""
|
||||
key = self.pair_key(uid, peer)
|
||||
if not self._proven(uid, installation):
|
||||
return {"kind": "", "offer": ""}
|
||||
kind, offer, offer_by, at = self._species_row(key)
|
||||
with self.connect() as db:
|
||||
if db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone():
|
||||
return {"kind": "", "offer": ""}
|
||||
waiting = offer if offer and offer_by == peer and int(self.clock()) - at < self.SPECIES_OFFER_LIFE else ""
|
||||
return {"kind": kind, "offer": waiting}
|
||||
|
||||
def species_answer(self, uid, installation, peer, accept):
|
||||
"""The other one says yes (the animal is now the pair's) or no (the offer goes away)."""
|
||||
key = self.pair_key(uid, peer)
|
||||
if not self._proven(uid, installation):
|
||||
raise ValueError("Prove the account first")
|
||||
if not isinstance(accept, bool):
|
||||
raise ValueError("Say yes or no")
|
||||
kind, offer, offer_by, at = self._species_row(key)
|
||||
if not offer or offer_by != peer or int(self.clock()) - at >= self.SPECIES_OFFER_LIFE:
|
||||
raise ValueError("There is no offer to answer")
|
||||
with self.connect() as db:
|
||||
if accept and db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone():
|
||||
raise ValueError("Account excluded")
|
||||
if accept:
|
||||
db.execute("UPDATE pair_species SET kind=?, offer='', offer_by='', at=? WHERE pair=?", (offer, int(self.clock()), key))
|
||||
else:
|
||||
db.execute("UPDATE pair_species SET offer='', offer_by='', at=? WHERE pair=?", (int(self.clock()), key))
|
||||
return {"ok": True, "kind": offer if accept else kind}
|
||||
|
||||
def frame_allowed(self, uid, frame):
|
||||
"""May this account use this frame? Open packs: always; closed packs: only with a grant."""
|
||||
if frame.split(".", 1)[0] not in RESTRICTED_PACKS:
|
||||
@@ -566,6 +768,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
raise ValueError("Expected an object")
|
||||
if operation in CATALOG:
|
||||
result = self.server.registry.catalog.call(operation, payload)
|
||||
elif operation in ACCOUNTS:
|
||||
result = self.server.registry.accounts.call(operation, payload)
|
||||
elif operation == "lookup":
|
||||
result = self.server.registry.lookup(payload.get("uids"))
|
||||
elif operation == "code":
|
||||
@@ -582,6 +786,22 @@ class Handler(BaseHTTPRequestHandler):
|
||||
elif operation == "bubble_upload":
|
||||
result = self.server.registry.bubble_upload(payload.get("uid"), payload.get("installation"), payload.get("unique_id"),
|
||||
payload.get("peer"), payload.get("name"), payload.get("png"))
|
||||
elif operation == "pet_upload":
|
||||
result = self.server.registry.pet_upload(payload.get("uid"), payload.get("installation"), payload.get("unique_id"),
|
||||
payload.get("peer"), payload.get("name"), payload.get("png"))
|
||||
elif operation == "pet_lookup":
|
||||
result = self.server.registry.pet_lookup(payload.get("uid"), payload.get("installation"), payload.get("peer"))
|
||||
elif operation == "pet_revert":
|
||||
result = self.server.registry.pet_revert(payload.get("uid"), payload.get("installation"), payload.get("peer"), payload.get("id"))
|
||||
elif operation == "pet_clear":
|
||||
result = self.server.registry.pet_clear(payload.get("uid"), payload.get("installation"), payload.get("peer"))
|
||||
elif operation == "species_offer":
|
||||
result = self.server.registry.species_offer(payload.get("uid"), payload.get("installation"), payload.get("peer"), payload.get("kind"))
|
||||
elif operation == "species_lookup":
|
||||
result = self.server.registry.species_lookup(payload.get("uid"), payload.get("installation"), payload.get("peer"))
|
||||
elif operation == "species_answer":
|
||||
result = self.server.registry.species_answer(payload.get("uid"), payload.get("installation"), payload.get("peer"),
|
||||
payload.get("accept") is True)
|
||||
elif operation == "pair_lookup":
|
||||
result = self.server.registry.pair_lookup(payload.get("uid"), payload.get("installation"), payload.get("peer"))
|
||||
elif operation == "pair_clear":
|
||||
@@ -625,7 +845,13 @@ def main():
|
||||
token, owner = os.environ.get("MOD_BOT_TOKEN"), os.environ.get("MOD_OWNER_ID")
|
||||
if token and owner:
|
||||
import modbot
|
||||
modbot.start(server.registry, token, owner)
|
||||
auth_token = os.environ.get("AUTH_BOT_TOKEN")
|
||||
hook = None
|
||||
if auth_token:
|
||||
import authbot
|
||||
auth, _ = authbot.start(server.registry, auth_token, owner)
|
||||
hook = auth.notify_new
|
||||
modbot.start(server.registry, token, owner, on_approved=hook)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
|
||||
@@ -82,6 +82,16 @@ final class Owner {
|
||||
}
|
||||
}
|
||||
|
||||
/** The account whose profile picture this view shows (not the signed-in account's own), or null. Never throws. */
|
||||
static String accountOf(View view) {
|
||||
try {
|
||||
String id = Pictures.id(addressOf(view));
|
||||
return id == null || isMine(id) ? null : PictureOwners.uidOf(id);
|
||||
} catch (Throwable unreadable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The shape this view is drawn in, or null for TikTok's round one. Never throws. */
|
||||
static ModSettings.AvatarShape shapeFor(View view) {
|
||||
Look look = lookFor(view);
|
||||
|
||||
@@ -176,7 +176,7 @@ public final class PairPictures {
|
||||
}, "lihont-pair-art").start();
|
||||
}
|
||||
|
||||
private static void save(Context context, String hex, byte[] data) throws IOException {
|
||||
static void save(Context context, String hex, byte[] data) throws IOException {
|
||||
File folder = folder(context);
|
||||
File part = new File(folder, hex + ".part");
|
||||
try (FileOutputStream out = new FileOutputStream(part)) {
|
||||
|
||||
291
src/lihont/two/avatar/PetPictures.java
Normal file
@@ -0,0 +1,291 @@
|
||||
package lihont.two.avatar;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import lihont.two.account.CurrentAccount;
|
||||
import lihont.two.badge.NicheClaim;
|
||||
|
||||
/**
|
||||
* The "Серийчик" of two accounts as one picture, the same on both phones: either of the two may change it, the newest approved picture is
|
||||
* shown (an earlier one stays until the new one is approved), and the last few can be brought back. It lives on the members service
|
||||
* (pet_lookup / pet_upload / pet_revert / pet_clear); the phone asks at most every few minutes and keeps the answer, so the screens and
|
||||
* the widget draw it at once. The pictures themselves are fetched and kept by {@link PairPictures}.
|
||||
*
|
||||
* A picture the member has just sent is shown to them at once, before it is approved, for a few days.
|
||||
*/
|
||||
public final class PetPictures {
|
||||
private static final String PREFS = "lihont_pet_pictures";
|
||||
private static final long CHECK_MS = 10L * 60L * 1000L;
|
||||
private static final long PENDING_MS = 3L * 24L * 3600L * 1000L;
|
||||
private static final Handler MAIN = new Handler(Looper.getMainLooper());
|
||||
private static final Map<String, String> IDS = new HashMap<String, String>();
|
||||
private static final Map<String, Long> CHECKED = new HashMap<String, Long>();
|
||||
|
||||
private PetPictures() {}
|
||||
|
||||
/** What the service knows about the pair: the picture shown, whether a newer one waits, the earlier approved ones. */
|
||||
public static final class Info {
|
||||
public final String id;
|
||||
public final boolean pending;
|
||||
public final List<String> history;
|
||||
|
||||
Info(String id, boolean pending, List<String> history) {
|
||||
this.id = id;
|
||||
this.pending = pending;
|
||||
this.history = history;
|
||||
}
|
||||
}
|
||||
|
||||
public interface InfoCallback {
|
||||
void done(Info info, String problem);
|
||||
}
|
||||
|
||||
/** The picture for the pair of the signed-in account and `peerUid`, or null (none, not approved, or not on the phone yet). */
|
||||
public static synchronized Bitmap forPartner(Context context, String peerUid) {
|
||||
String mine = CurrentAccount.uid();
|
||||
if (mine == null || peerUid == null || mine.equals(peerUid)) return null;
|
||||
String key = key(mine, peerUid);
|
||||
SharedPreferences prefs = prefs(context);
|
||||
long now = SystemClock.uptimeMillis();
|
||||
Long checked = CHECKED.get(key);
|
||||
if (checked == null || now - checked.longValue() > CHECK_MS) {
|
||||
CHECKED.put(key, Long.valueOf(now));
|
||||
ask(app(context), mine, peerUid, key);
|
||||
}
|
||||
String hex = IDS.get(key);
|
||||
if (hex == null) {
|
||||
hex = prefs.getString("id_" + key, "");
|
||||
IDS.put(key, hex);
|
||||
}
|
||||
if (hex.length() == 0) {
|
||||
long at = prefs.getLong("pending_at_" + key, 0L);
|
||||
String waiting = prefs.getString("pending_" + key, "");
|
||||
if (waiting.length() == 0 || System.currentTimeMillis() - at > PENDING_MS) return null;
|
||||
hex = waiting;
|
||||
}
|
||||
return PairPictures.artBitmap(context, hex);
|
||||
}
|
||||
|
||||
/** Asks the service now (off the main thread) and reports on the main one. */
|
||||
public static void lookup(final Context context, final String peerUid, final InfoCallback callback) {
|
||||
final String mine = CurrentAccount.uid();
|
||||
final Context app = app(context);
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
Info info = null;
|
||||
String problem = null;
|
||||
try {
|
||||
if (mine == null) throw new IOException("Войдите в TikTok");
|
||||
JSONObject reply = lihont.two.badge.MemberClient.post("pet_lookup", new JSONObject()
|
||||
.put("uid", mine).put("peer", peerUid).put("installation", Installation.secret(app)));
|
||||
String id = reply.isNull("id") ? "" : reply.optString("id", "");
|
||||
if (!id.matches("[0-9a-f]{24}")) id = "";
|
||||
List<String> older = new ArrayList<String>();
|
||||
JSONArray array = reply.optJSONArray("history");
|
||||
for (int i = 0; array != null && i < array.length(); i++) {
|
||||
String one = array.optString(i, "");
|
||||
if (one.matches("[0-9a-f]{24}")) older.add(one);
|
||||
}
|
||||
info = new Info(id, reply.optBoolean("pending", false), older);
|
||||
remember(app, key(mine, peerUid), id);
|
||||
} catch (Exception error) {
|
||||
problem = explain(error.getMessage());
|
||||
}
|
||||
final Info result = info;
|
||||
final String message = problem;
|
||||
MAIN.post(new Runnable() {
|
||||
@Override public void run() {
|
||||
callback.done(result, message);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, "lihont-pet-lookup").start();
|
||||
}
|
||||
|
||||
/** Sends a new picture for the pair; it is shown on this phone at once and on the other one once approved. */
|
||||
public static void upload(final Context context, final String peerUid, final byte[] png, final ShapePublisher.Callback callback) {
|
||||
final NicheClaim.Account account = NicheClaim.account();
|
||||
if (account == null) {
|
||||
callback.done(new ShapePublisher.Result(false, null, "Войдите в TikTok, чтобы отправить картинку"));
|
||||
return;
|
||||
}
|
||||
final Context app = app(context);
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
ShapePublisher.Result result;
|
||||
try {
|
||||
JSONObject reply = lihont.two.badge.MemberClient.post("pet_upload", new JSONObject()
|
||||
.put("uid", account.uid).put("peer", peerUid)
|
||||
.put("installation", Installation.secret(app)).put("unique_id", account.uniqueId)
|
||||
.put("name", "Серийчик")
|
||||
.put("png", android.util.Base64.encodeToString(png, android.util.Base64.NO_WRAP)));
|
||||
if (reply.optBoolean("published", false)) {
|
||||
String status = reply.optString("status", "new");
|
||||
String id = reply.optString("id", "");
|
||||
if (!"rejected".equals(status) && id.matches("[0-9a-f]{24}")) {
|
||||
String key = key(account.uid, peerUid);
|
||||
synchronized (PetPictures.class) {
|
||||
PairPictures.save(app, id, png);
|
||||
prefs(app).edit().putString("pending_" + key, id).putLong("pending_at_" + key, System.currentTimeMillis()).apply();
|
||||
CHECKED.remove(key);
|
||||
}
|
||||
}
|
||||
result = new ShapePublisher.Result(!"rejected".equals(status), null,
|
||||
"rejected".equals(status) ? "Эту картинку не приняли"
|
||||
: "approved".equals(status) ? "Серийчик обновлён: его видите вы оба"
|
||||
: "Отправлено на проверку. Пока её не приняли, остаётся прежняя картинка.");
|
||||
} else {
|
||||
String code = reply.optString("code", "");
|
||||
result = new ShapePublisher.Result(false, code.length() == 0 ? null : code,
|
||||
"Кода в описании профиля не нашли. Вставьте его и подождите минуту.");
|
||||
}
|
||||
} catch (Exception error) {
|
||||
result = new ShapePublisher.Result(false, null, explain(error.getMessage()));
|
||||
}
|
||||
post(result, callback);
|
||||
}
|
||||
}, "lihont-pet-upload").start();
|
||||
}
|
||||
|
||||
/** Brings back one of the earlier approved pictures of the pair. */
|
||||
public static void revert(final Context context, final String peerUid, final String id, final ShapePublisher.Callback callback) {
|
||||
final String mine = CurrentAccount.uid();
|
||||
final Context app = app(context);
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
ShapePublisher.Result result;
|
||||
try {
|
||||
if (mine == null) throw new IOException("Войдите в TikTok");
|
||||
lihont.two.badge.MemberClient.post("pet_revert", new JSONObject()
|
||||
.put("uid", mine).put("peer", peerUid).put("id", id).put("installation", Installation.secret(app)));
|
||||
remember(app, key(mine, peerUid), id);
|
||||
result = new ShapePublisher.Result(true, null, "Прежняя картинка возвращена");
|
||||
} catch (Exception error) {
|
||||
result = new ShapePublisher.Result(false, null, explain(error.getMessage()));
|
||||
}
|
||||
post(result, callback);
|
||||
}
|
||||
}, "lihont-pet-revert").start();
|
||||
}
|
||||
|
||||
/** Takes the picture of the pair away, for both. */
|
||||
public static void clear(final Context context, final String peerUid, final ShapePublisher.Callback callback) {
|
||||
final String mine = CurrentAccount.uid();
|
||||
final Context app = app(context);
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
ShapePublisher.Result result;
|
||||
try {
|
||||
if (mine == null) throw new IOException("Войдите в TikTok");
|
||||
lihont.two.badge.MemberClient.post("pet_clear", new JSONObject()
|
||||
.put("uid", mine).put("peer", peerUid).put("installation", Installation.secret(app)));
|
||||
String key = key(mine, peerUid);
|
||||
synchronized (PetPictures.class) {
|
||||
IDS.put(key, "");
|
||||
prefs(app).edit().remove("id_" + key).remove("pending_" + key).apply();
|
||||
}
|
||||
result = new ShapePublisher.Result(true, null, "Серийчик убран");
|
||||
} catch (Exception error) {
|
||||
result = new ShapePublisher.Result(false, null, explain(error.getMessage()));
|
||||
}
|
||||
post(result, callback);
|
||||
}
|
||||
}, "lihont-pet-clear").start();
|
||||
}
|
||||
|
||||
/** The account whose profile picture an avatar view shows, or null (the same lookup that dresses avatars with frames). */
|
||||
public static String avatarOwner(android.view.View view) {
|
||||
return Owner.accountOf(view);
|
||||
}
|
||||
|
||||
/** The accounts that have a picture (shown or waiting) with the signed-in account `mine`, as far as this phone knows. */
|
||||
public static synchronized List<String> partners(Context context, String mine) {
|
||||
List<String> found = new ArrayList<String>();
|
||||
if (mine == null) return found;
|
||||
for (Map.Entry<String, ?> entry : prefs(context).getAll().entrySet()) {
|
||||
String name = entry.getKey();
|
||||
if (!name.startsWith("id_") && !name.startsWith("pending_")) continue;
|
||||
if (entry.getValue() == null || entry.getValue().toString().length() == 0) continue;
|
||||
String key = name.substring(name.indexOf('_') + 1);
|
||||
int colon = key.indexOf(':');
|
||||
if (colon <= 0) continue;
|
||||
String a = key.substring(0, colon);
|
||||
String b = key.substring(colon + 1);
|
||||
String other = mine.equals(a) ? b : mine.equals(b) ? a : null;
|
||||
if (other != null && !found.contains(other)) found.add(other);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// ---- inside ---------------------------------------------------------------------------------------------------
|
||||
|
||||
private static void ask(final Context context, final String mine, final String peer, final String key) {
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
try {
|
||||
JSONObject reply = lihont.two.badge.MemberClient.post("pet_lookup", new JSONObject()
|
||||
.put("uid", mine).put("peer", peer).put("installation", Installation.secret(context)));
|
||||
String id = reply.isNull("id") ? "" : reply.optString("id", "");
|
||||
if (!id.matches("[0-9a-f]{24}")) id = "";
|
||||
remember(context, key, id);
|
||||
} catch (Exception unreachable) {
|
||||
// the last answer stays
|
||||
}
|
||||
}
|
||||
}, "lihont-pet-ask").start();
|
||||
}
|
||||
|
||||
private static void remember(Context context, String key, String id) {
|
||||
synchronized (PetPictures.class) {
|
||||
IDS.put(key, id);
|
||||
SharedPreferences.Editor edit = prefs(context).edit().putString("id_" + key, id);
|
||||
if (id.length() > 0) edit.remove("pending_" + key);
|
||||
edit.apply();
|
||||
}
|
||||
}
|
||||
|
||||
private static void post(final ShapePublisher.Result result, final ShapePublisher.Callback callback) {
|
||||
MAIN.post(new Runnable() {
|
||||
@Override public void run() {
|
||||
callback.done(result);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** The service answers in English; the person reads Russian. */
|
||||
static String explain(String message) {
|
||||
if (message == null) return "Нет связи с сервером";
|
||||
if (message.startsWith("The picture of the pair can be changed once an hour")) return "Серийчик можно менять раз в час, подождите немного";
|
||||
if (message.startsWith("Too many pictures")) return "Слишком много картинок ждут проверки, попробуйте позже";
|
||||
if (message.startsWith("Account excluded")) return "Аккаунт исключён";
|
||||
if (message.startsWith("Unknown picture")) return "Такой картинки у пары нет";
|
||||
if (message.startsWith("Prove the account")) return "Сначала подтвердите аккаунт в настройках";
|
||||
return message;
|
||||
}
|
||||
|
||||
private static Context app(Context context) {
|
||||
return context.getApplicationContext() != null ? context.getApplicationContext() : context;
|
||||
}
|
||||
|
||||
private static String key(String mine, String peer) {
|
||||
return mine.compareTo(peer) < 0 ? mine + ":" + peer : peer + ":" + mine;
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,17 @@ public final class MemberClient {
|
||||
}
|
||||
int status = connection.getResponseCode();
|
||||
InputStream stream = status == 200 ? connection.getInputStream() : connection.getErrorStream();
|
||||
JSONObject reply = stream == null ? new JSONObject() : new JSONObject(readLimited(stream));
|
||||
JSONObject reply;
|
||||
String text = stream == null ? "" : readLimited(stream);
|
||||
try {
|
||||
reply = text.length() == 0 ? new JSONObject() : new JSONObject(text);
|
||||
} catch (org.json.JSONException notJson) {
|
||||
// which call, which answer: so that a report of this message can be traced (no account data is in it)
|
||||
android.util.Log.w("LIHONT", "member " + operation + " got status " + status + " and not JSON: "
|
||||
+ text.substring(0, Math.min(160, text.length())).replace('\n', ' '));
|
||||
// a page of a network (an operator, a captive portal, a proxy) instead of the service's answer
|
||||
throw new IOException("Сервер ответил не так, как ожидалось. Скорее всего, сеть мешает: подождите и попробуйте ещё раз");
|
||||
}
|
||||
if (status != 200) {
|
||||
throw new IOException(reply.optString("error", "Membership request failed (" + status + ")"));
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ public final class Bubbles {
|
||||
// one picture for the chat, chosen by either of the two, is the same on both phones and replaces the personal ones
|
||||
partner = cachedName(activity, decor, list);
|
||||
BubbleStore.seen(activity, partner);
|
||||
PetFlame.apply(activity, decor, partnerUid, partner); // the picture of the pair instead of the streak flame in the header
|
||||
Bitmap shared = partnerUid == null ? null : lihont.two.avatar.PairPictures.forPartner(activity, partnerUid);
|
||||
String publishedId = partnerUid == null ? null : lihont.two.avatar.ShapeCatalog.bubbleOf(partnerUid);
|
||||
Bitmap published = publishedId == null ? null : lihont.two.avatar.PairPictures.artBitmap(activity, publishedId);
|
||||
@@ -130,6 +131,10 @@ public final class Bubbles {
|
||||
name = headerName(decor, list);
|
||||
nameAt = now;
|
||||
partnerUid = name == null ? null : lihont.two.badge.Badges.uidForName(name);
|
||||
// the names TikTok has shown are kept on the phone: a header name that matches one of them (and only one) is that person
|
||||
if (partnerUid == null && name != null) partnerUid = PetFlame.uidByContactName(activity, name);
|
||||
// the chat itself knows who is in it: its id ("0:1:" and the two account numbers) is among what the screen was opened with
|
||||
if (partnerUid == null) partnerUid = PetFlame.partnerFromScreen(activity);
|
||||
if (partnerUid != null) BubbleStore.rememberAccount(activity, name, partnerUid);
|
||||
}
|
||||
return name;
|
||||
|
||||
714
src/lihont/two/chat/PetFlame.java
Normal file
@@ -0,0 +1,714 @@
|
||||
package lihont.two.chat;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import lihont.two.avatar.PetPictures;
|
||||
|
||||
/**
|
||||
* The flame with the day count in the header of a chat (TikTok's streak icon) becomes the picture of the pair when the two of them have
|
||||
* one (see {@link PetPictures}). The flame is an icon view whose drawable keeps the number of the raw resource it was made from; the
|
||||
* resources of the streak icons are found by name, so no number is written here. Chats with nobody to show keep TikTok's flame.
|
||||
*
|
||||
* While the structure of the header is not known for sure, a short line per image view of the top of the screen is written to the log
|
||||
* (class, size, drawable, icon resource; never a text) every few seconds.
|
||||
*/
|
||||
final class PetFlame {
|
||||
private static final String TAG = "LIHONT";
|
||||
private static final String TUX_DRAWABLE = "com.bytedance.tux.drawable.TuxIconDrawable";
|
||||
private static final String[] NAMES = {
|
||||
"icon_bitmap_streak_light_level_1", "icon_bitmap_streak_light_level_2", "icon_bitmap_streak_light_level_3",
|
||||
"icon_bitmap_streak_light_level_4", "icon_bitmap_streak_light_level_5",
|
||||
"icon_bitmap_streak_gray_level_1", "icon_bitmap_streak_gray_level_2", "icon_bitmap_streak_gray_level_3",
|
||||
"icon_bitmap_streak_gray_level_4", "icon_bitmap_streak_gray_level_5",
|
||||
"icon_color_streak_light", "icon_color_streak_gray"};
|
||||
private static final int MAX_NODES = 700;
|
||||
private static final long LOG_MS = 15000L;
|
||||
|
||||
private static int[] ids;
|
||||
private static Field iconRes;
|
||||
private static boolean fieldTried;
|
||||
private static long loggedAt;
|
||||
|
||||
private PetFlame() {}
|
||||
|
||||
private static long guessedAt;
|
||||
private static String guessed;
|
||||
private static int guessedDays = -1;
|
||||
|
||||
static void apply(Activity activity, View decor, String partnerUid, String headerName) {
|
||||
try {
|
||||
long now = SystemClock.uptimeMillis();
|
||||
boolean log = now - loggedAt > LOG_MS;
|
||||
if (log) loggedAt = now;
|
||||
if (ids == null) ids = resolve(activity);
|
||||
if (log) {
|
||||
// what the Lynx engine draws on this screen (the streak creature is one of it): class, size, place, never a text
|
||||
View root = activity.getWindow().getDecorView();
|
||||
Log.i(TAG, "pet: screen " + activity.getClass().getName());
|
||||
lynxIn(root, root.getWidth(), root.getHeight(), 0, new java.util.ArrayList<View>(), new int[1], true);
|
||||
}
|
||||
int limit = Math.max(1, activity.getResources().getDisplayMetrics().heightPixels * 3 / 10);
|
||||
java.util.ArrayList<ImageView> flames = new java.util.ArrayList<ImageView>();
|
||||
collect(decor, limit, 0, flames, new int[2], log);
|
||||
if (flames.isEmpty()) iconByNumber(decor, limit, flames, log);
|
||||
if (flames.isEmpty()) {
|
||||
if (log) Log.i(TAG, "pet: no streak flame in the header of this screen");
|
||||
clearCreature();
|
||||
return;
|
||||
}
|
||||
String partner = partnerUid != null ? partnerUid : byAvatar(activity, decor, limit, log);
|
||||
if (partner == null) partner = guessPartner(activity, flames.get(0), log, decor, limit);
|
||||
if (partner == null) {
|
||||
if (log) Log.i(TAG, "pet: the person of this chat is not known (the flame is there)");
|
||||
clearCreature();
|
||||
return;
|
||||
}
|
||||
Bitmap picture = PetPictures.forPartner(activity, partner);
|
||||
if (log) Log.i(TAG, "pet: partner known, picture " + (picture == null ? "none" : "ready"));
|
||||
// the animal the pair was given wins; without one (or while its strip is coming) the picture of the pair is shown
|
||||
Bitmap[] animal = animalFrames(activity, partner, log);
|
||||
if (animal != null) {
|
||||
lastPartner = partner;
|
||||
lastShownAt = android.os.SystemClock.uptimeMillis();
|
||||
replaceCreature(activity, animal, log);
|
||||
play(activity, flames, animal, lihont.two.pet.Species.kind(activity, lihont.two.account.CurrentAccount.uid(), partner));
|
||||
return;
|
||||
}
|
||||
if (picture == null) {
|
||||
clearCreature();
|
||||
return;
|
||||
}
|
||||
replaceCreature(activity, new Bitmap[] {picture}, log);
|
||||
for (ImageView flame : flames) {
|
||||
flame.setImageDrawable(new BitmapDrawable(activity.getResources(), picture));
|
||||
flame.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
}
|
||||
} catch (Throwable unexpected) {
|
||||
// the chat must never break because of the flame
|
||||
}
|
||||
}
|
||||
|
||||
/** The animal the pair was given, playing in place of the flame: its age is the days of the streak, it is grey when the streak is about to end. */
|
||||
private static void showAnimal(final Activity activity, java.util.List<ImageView> flames, String partner, boolean log) {
|
||||
Bitmap[] shown = animalFrames(activity, partner, log);
|
||||
if (shown == null) return;
|
||||
replaceCreature(activity, shown, log);
|
||||
play(activity, flames, shown, lihont.two.pet.Species.kind(activity, lihont.two.account.CurrentAccount.uid(), partner));
|
||||
}
|
||||
|
||||
private static void play(Activity activity, java.util.List<ImageView> flames, Bitmap[] frames, String kind) {
|
||||
// the first frame tells which strip plays: another animal, age or mood is another strip, and the icon changes with it
|
||||
Object tag = frames[0];
|
||||
for (ImageView flame : flames) {
|
||||
if (tag == flame.getTag(0x4c504554) && flame.getDrawable() instanceof android.graphics.drawable.AnimationDrawable) continue;
|
||||
android.graphics.drawable.AnimationDrawable play = lihont.two.pet.PetArt.animation(activity, frames);
|
||||
flame.setImageDrawable(play);
|
||||
flame.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
flame.setTag(0x4c504554, tag);
|
||||
play.start();
|
||||
}
|
||||
}
|
||||
|
||||
/** The frames of the animal the pair has right now (its age by the streak, grey when it is about to end), or null. */
|
||||
private static Bitmap[] animalFrames(final Activity activity, String partner, boolean log) {
|
||||
String mine = lihont.two.account.CurrentAccount.uid();
|
||||
if (mine == null) return null;
|
||||
lihont.two.pet.Species.refresh(activity, mine, partner);
|
||||
String kind = lihont.two.pet.Species.kind(activity, mine, partner);
|
||||
if (kind.length() == 0) return null;
|
||||
lihont.two.widget.StreakApi.Info info = lihont.two.widget.StreakApi.info(lihont.two.widget.StreakApi.conversationId(mine, partner));
|
||||
int days = info == null ? 0 : info.streak;
|
||||
boolean grey = lihont.two.widget.StreakApi.frozen(info, System.currentTimeMillis());
|
||||
Bitmap[] frames = lihont.two.pet.PetArt.frames(activity, kind, days, grey, null);
|
||||
if (log) Log.i(TAG, "pet: animal " + kind + ", days " + days + (grey ? ", grey" : "") + (info == null ? ", no streak info" : ", active before " + info.activeBefore + " remind " + info.remindAt
|
||||
+ " end " + info.endAt + " now " + System.currentTimeMillis()) + ", " + (frames == null ? "strip not on the phone yet" : "playing"));
|
||||
return frames;
|
||||
}
|
||||
|
||||
private static final int OVERLAY_TAG = 0x4c504555;
|
||||
|
||||
/** The person of the chat an animal was last shown in: the big screen of the pet opens from that chat. */
|
||||
static volatile String lastPartner;
|
||||
|
||||
/** When that animal was last drawn in the chat (uptime): a page opened a moment later was opened from that chat. */
|
||||
static volatile long lastShownAt;
|
||||
|
||||
/** The frames of the animal the signed-in account has with this person right now, or null. */
|
||||
static Bitmap[] framesFor(Activity activity, String partner) {
|
||||
return animalFrames(activity, partner, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* The creature that floats at the right edge of the chat (TikTok's streak pet, drawn by the Lynx engine): its view is found by its
|
||||
* class (the name holds "Lynx") and place (right part of the screen, upper half, not a whole-screen layer), hidden, and the animal
|
||||
* plays on its place. What was found is written to the log (class and size, never a text).
|
||||
*/
|
||||
private static void replaceCreature(Activity activity, Bitmap[] frames, boolean log) {
|
||||
try {
|
||||
View decor = activity.getWindow().getDecorView();
|
||||
if (!(decor instanceof ViewGroup)) return;
|
||||
int width = decor.getWidth();
|
||||
int height = decor.getHeight();
|
||||
java.util.ArrayList<View> found = new java.util.ArrayList<View>();
|
||||
lynxIn(decor, width, height, 0, found, new int[1], log);
|
||||
if (found.isEmpty()) {
|
||||
if (log) Log.i(TAG, "pet: no creature view found on the right of this chat");
|
||||
clearCreature();
|
||||
return;
|
||||
}
|
||||
View creature = found.get(0);
|
||||
int best = -1;
|
||||
for (View candidate : found) {
|
||||
int weight = weight(candidate, 0);
|
||||
if (log) Log.i(TAG, "pet: creature candidate holds " + weight + " views");
|
||||
if (weight > best) {
|
||||
best = weight;
|
||||
creature = candidate;
|
||||
}
|
||||
}
|
||||
// the engine draws the creature, its cloud and its parts in the holder views around the one found (all of the same size): the
|
||||
// topmost of them that is still no bigger than the creature is the whole creature; the animal takes its place and its size
|
||||
View holder = creature;
|
||||
while (holder.getParent() instanceof View) {
|
||||
View parent = (View) holder.getParent();
|
||||
if (parent.getWidth() > creature.getWidth() * 12 / 10 || parent.getHeight() > creature.getHeight() * 12 / 10) break;
|
||||
holder = parent;
|
||||
}
|
||||
int[] at = new int[2];
|
||||
holder.getLocationInWindow(at);
|
||||
ViewGroup root = (ViewGroup) decor;
|
||||
int side = holder.getWidth();
|
||||
int margin = Math.round(width * 0.012f);
|
||||
int left = Math.max(margin, Math.min(at[0], width - side - margin));
|
||||
int top = at[1];
|
||||
ImageView overlay = (ImageView) root.findViewWithTag(Integer.valueOf(OVERLAY_TAG));
|
||||
if (overlay == null) {
|
||||
overlay = new ImageView(activity);
|
||||
overlay.setTag(Integer.valueOf(OVERLAY_TAG));
|
||||
overlay.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
overlay.setClickable(false);
|
||||
root.addView(overlay, new android.widget.FrameLayout.LayoutParams(side, side));
|
||||
}
|
||||
overlayRef = new java.lang.ref.WeakReference<ImageView>(overlay);
|
||||
android.widget.FrameLayout.LayoutParams params = (android.widget.FrameLayout.LayoutParams) overlay.getLayoutParams();
|
||||
int gravity = android.view.Gravity.TOP | android.view.Gravity.LEFT;
|
||||
// this runs before every frame: asking for a new layout when nothing moved would keep the screen laying itself out forever
|
||||
if (params.width != side || params.height != side || params.leftMargin != left || params.topMargin != top || params.gravity != gravity) {
|
||||
params.width = side;
|
||||
params.height = side;
|
||||
params.leftMargin = left;
|
||||
params.topMargin = top;
|
||||
params.gravity = gravity;
|
||||
overlay.setLayoutParams(params);
|
||||
}
|
||||
// the first frame tells which strip plays: another chat, age or mood brings another one
|
||||
if (overlay.getTag(0x4c504556) != frames[0] || !(overlay.getDrawable() instanceof android.graphics.drawable.AnimationDrawable)) {
|
||||
android.graphics.drawable.AnimationDrawable play = lihont.two.pet.PetArt.animation(activity, frames);
|
||||
overlay.setImageDrawable(play);
|
||||
overlay.setTag(0x4c504556, frames[0]);
|
||||
play.start();
|
||||
}
|
||||
if (log) {
|
||||
// what holds the creature (the engine may draw it in the layer of a parent): class, size, place of each ancestor
|
||||
android.view.ViewParent up = creature.getParent();
|
||||
int level = 0;
|
||||
while (up instanceof View && level++ < 7) {
|
||||
View parent = (View) up;
|
||||
int[] where = new int[2];
|
||||
parent.getLocationInWindow(where);
|
||||
Log.i(TAG, "pet: creature parent " + level + " " + parent.getClass().getName() + " " + parent.getWidth() + "x" + parent.getHeight()
|
||||
+ " at " + where[0] + "," + where[1] + " children " + (parent instanceof ViewGroup ? ((ViewGroup) parent).getChildCount() : 0));
|
||||
up = parent.getParent();
|
||||
}
|
||||
}
|
||||
hide(holder, 0);
|
||||
if (holder != creature) hide(creature, 0);
|
||||
hiddenRef = new java.lang.ref.WeakReference<View>(holder);
|
||||
hiddenInnerRef = new java.lang.ref.WeakReference<View>(creature);
|
||||
if (log) Log.i(TAG, "pet: creature replaced: " + creature.getClass().getName() + " " + creature.getWidth() + "x" + creature.getHeight());
|
||||
} catch (Throwable unexpected) {
|
||||
if (log) Log.i(TAG, "pet: creature not replaced: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
private static java.lang.ref.WeakReference<ImageView> overlayRef;
|
||||
private static java.lang.ref.WeakReference<View> hiddenRef;
|
||||
private static java.lang.ref.WeakReference<View> hiddenInnerRef;
|
||||
|
||||
/**
|
||||
* The screen has no animal to show any more (another chat, another screen of the same activity, the animal is gone): the animal is
|
||||
* taken off the screen and TikTok's own creature is shown again. Costs nothing while there is nothing to take off.
|
||||
*/
|
||||
private static void clearCreature() {
|
||||
ImageView overlay = overlayRef == null ? null : overlayRef.get();
|
||||
overlayRef = null;
|
||||
if (overlay != null && overlay.getParent() instanceof ViewGroup) ((ViewGroup) overlay.getParent()).removeView(overlay);
|
||||
View holder = hiddenRef == null ? null : hiddenRef.get();
|
||||
View inner = hiddenInnerRef == null ? null : hiddenInnerRef.get();
|
||||
hiddenRef = null;
|
||||
hiddenInnerRef = null;
|
||||
if (holder != null) show(holder, 0);
|
||||
if (inner != null && inner != holder) show(inner, 0);
|
||||
}
|
||||
|
||||
/** Undoes {@link #hide}. */
|
||||
private static void show(View view, int depth) {
|
||||
view.setAlpha(1f);
|
||||
if (depth == 0) {
|
||||
view.setVisibility(View.VISIBLE);
|
||||
view.setClipBounds(null);
|
||||
}
|
||||
if (view instanceof ViewGroup && depth < 12) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) show(group.getChildAt(i), depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/** The creature and everything it is made of: nothing of it is drawn, but it still takes touches. */
|
||||
static void hide(View view, int depth) {
|
||||
view.setAlpha(0f);
|
||||
if (depth == 0) {
|
||||
// an empty clip draws nothing, whatever the engine does with the opacity afterwards; the view stays visible for the system,
|
||||
// so it still takes the finger: the creature can be dragged and tapped as before, and the animal follows it
|
||||
if (view.getVisibility() == View.INVISIBLE) view.setVisibility(View.VISIBLE);
|
||||
view.setClipBounds(new android.graphics.Rect(0, 0, 0, 0));
|
||||
}
|
||||
if (view instanceof ViewGroup && depth < 12) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) hide(group.getChildAt(i), depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/** How many views the view holds in all (an empty slot holds none, the creature holds its picture and parts). */
|
||||
private static int weight(View view, int depth) {
|
||||
int total = 1;
|
||||
if (view instanceof ViewGroup && depth < 12) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) total += weight(group.getChildAt(i), depth + 1);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static void lynxIn(View view, int width, int height, int depth, java.util.List<View> found, int[] count, boolean log) {
|
||||
if (view == null || depth > 40 || count[0]++ > 2500 || view.getVisibility() == View.GONE) return;
|
||||
String name = view.getClass().getName();
|
||||
if (name.toLowerCase(java.util.Locale.ROOT).contains("lynx")) {
|
||||
int[] at = new int[2];
|
||||
view.getLocationInWindow(at);
|
||||
boolean small = view.getWidth() > 0 && view.getWidth() < width * 7 / 10 && view.getHeight() < height * 45 / 100;
|
||||
int visibleWidth = Math.min(at[0] + view.getWidth(), width) - Math.max(at[0], 0);
|
||||
boolean right = visibleWidth * 100 >= view.getWidth() * 30; // at least a third of it is on the screen (the side does not matter)
|
||||
if (log) Log.i(TAG, "pet: lynx view " + name + " " + view.getWidth() + "x" + view.getHeight() + " at " + at[0] + "," + at[1]
|
||||
+ (small && right ? " CANDIDATE" : ""));
|
||||
if (small && right) found.add(view);
|
||||
}
|
||||
if (view instanceof ViewGroup) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) lynxIn(group.getChildAt(i), width, height, depth + 1, found, count, log);
|
||||
}
|
||||
}
|
||||
|
||||
private static void showAnimalOld(final Activity activity, java.util.List<ImageView> flames, String partner, boolean log) {
|
||||
String mine = lihont.two.account.CurrentAccount.uid();
|
||||
if (mine == null) return;
|
||||
lihont.two.pet.Species.refresh(activity, mine, partner);
|
||||
String kind = lihont.two.pet.Species.kind(activity, mine, partner);
|
||||
if (kind.length() == 0) return;
|
||||
lihont.two.widget.StreakApi.Info info = lihont.two.widget.StreakApi.info(lihont.two.widget.StreakApi.conversationId(mine, partner));
|
||||
int days = info == null ? 0 : info.streak;
|
||||
boolean grey = lihont.two.widget.StreakApi.frozen(info, System.currentTimeMillis());
|
||||
Bitmap[] frames = lihont.two.pet.PetArt.frames(activity, kind, days, grey, null);
|
||||
if (log) Log.i(TAG, "pet: animal " + kind + ", days " + days + (grey ? ", grey" : "") + (info == null ? ", no streak info" : ", active before " + info.activeBefore + " remind " + info.remindAt
|
||||
+ " end " + info.endAt + " now " + System.currentTimeMillis()) + ", " + (frames == null ? "strip not on the phone yet" : "playing"));
|
||||
if (frames == null) return;
|
||||
String tag = kind + days + grey;
|
||||
for (ImageView flame : flames) {
|
||||
if (tag.equals(flame.getTag(0x4c504554)) && flame.getDrawable() instanceof android.graphics.drawable.AnimationDrawable) continue;
|
||||
android.graphics.drawable.AnimationDrawable play = lihont.two.pet.PetArt.animation(activity, frames);
|
||||
flame.setImageDrawable(play);
|
||||
flame.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
flame.setTag(0x4c504554, tag);
|
||||
play.start();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Who the chat is with, when nothing tells it: the header shows the number of days of the streak, and the pairs that have a picture are
|
||||
* few, so the one whose streak has exactly this many days is the person (nobody is guessed when two have the same number).
|
||||
*/
|
||||
/**
|
||||
* Who the chat is with, from the profile picture in its header: the mod already knows which account a profile picture belongs to
|
||||
* (it dresses avatars with frames that way). The one of the pairs with a picture whose avatar is in the header is the person.
|
||||
*/
|
||||
private static java.util.List<String> allPartners(Activity activity, String mine) {
|
||||
java.util.ArrayList<String> all = new java.util.ArrayList<String>(PetPictures.partners(activity, mine));
|
||||
for (String uid : lihont.two.pet.Species.partners(activity, mine)) if (!all.contains(uid)) all.add(uid);
|
||||
return all;
|
||||
}
|
||||
|
||||
private static String byAvatar(Activity activity, View decor, int limit, boolean log) {
|
||||
String mine = lihont.two.account.CurrentAccount.uid();
|
||||
if (mine == null) return null;
|
||||
java.util.List<String> partners = allPartners(activity, mine);
|
||||
if (partners.isEmpty()) return null;
|
||||
java.util.HashSet<String> owners = new java.util.HashSet<String>();
|
||||
avatarsIn(decor, limit, 0, owners, new int[1]);
|
||||
String found = null;
|
||||
int matches = 0;
|
||||
for (String uid : partners) {
|
||||
if (owners.contains(uid)) {
|
||||
matches++;
|
||||
found = uid;
|
||||
}
|
||||
}
|
||||
if (log) Log.i(TAG, "pet: avatars of known accounts in the header " + owners.size() + ", pairs with a picture " + partners.size()
|
||||
+ ", matching " + matches);
|
||||
return matches == 1 ? found : null;
|
||||
}
|
||||
|
||||
private static void avatarsIn(View view, int limit, int depth, java.util.Set<String> owners, int[] count) {
|
||||
if (view == null || depth > 28 || count[0]++ > MAX_NODES || view.getVisibility() != View.VISIBLE) return;
|
||||
if (view instanceof ImageView) {
|
||||
int[] at = new int[2];
|
||||
view.getLocationOnScreen(at);
|
||||
if (at[1] < limit && view.getWidth() > 0) {
|
||||
String uid = PetPictures.avatarOwner(view);
|
||||
if (uid != null) owners.add(uid);
|
||||
}
|
||||
}
|
||||
if (view instanceof ViewGroup) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) avatarsIn(group.getChildAt(i), limit, depth + 1, owners, count);
|
||||
}
|
||||
}
|
||||
|
||||
private static String guessPartner(Activity activity, ImageView flame, boolean log, View decor, int limit) {
|
||||
long now = SystemClock.uptimeMillis();
|
||||
if (!log && now - guessedAt < 3000L) return guessed;
|
||||
guessedAt = now;
|
||||
guessed = null;
|
||||
java.util.HashSet<Integer> numbers = new java.util.HashSet<Integer>();
|
||||
java.util.ArrayList<String> texts = new java.util.ArrayList<String>();
|
||||
numbersIn(decor, limit, 0, numbers, texts, new int[1]);
|
||||
String mine = lihont.two.account.CurrentAccount.uid();
|
||||
if (mine == null || numbers.isEmpty()) {
|
||||
if (log) Log.i(TAG, "pet: numbers in the header: " + numbers.size() + (mine == null ? ", account not known" : ""));
|
||||
return null;
|
||||
}
|
||||
java.util.List<String> partners = allPartners(activity, mine);
|
||||
int known = 0;
|
||||
java.util.ArrayList<String> matching = new java.util.ArrayList<String>();
|
||||
for (String uid : partners) {
|
||||
lihont.two.widget.StreakApi.Info info = lihont.two.widget.StreakApi.info(lihont.two.widget.StreakApi.conversationId(mine, uid));
|
||||
if (info == null) continue;
|
||||
known++;
|
||||
if (numbers.contains(Integer.valueOf(info.streak))) matching.add(uid);
|
||||
}
|
||||
int byName = -1;
|
||||
if (matching.size() > 1) {
|
||||
// the same number of days for two of them: the name written in the header tells which (a header text holding the person's name)
|
||||
java.util.Map<String, String> names = lihont.two.widget.Contacts.all(activity.getApplicationContext(), mine);
|
||||
java.util.ArrayList<String> named = new java.util.ArrayList<String>();
|
||||
for (String uid : matching) {
|
||||
String name = names.get(uid);
|
||||
String wanted = name == null ? "" : plain(name);
|
||||
if (wanted.length() < 2) continue;
|
||||
for (String text : texts) {
|
||||
if (plain(text).contains(wanted)) {
|
||||
named.add(uid);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
byName = named.size();
|
||||
matching = named;
|
||||
}
|
||||
if (matching.size() == 1) guessed = matching.get(0);
|
||||
if (log) Log.i(TAG, "pet: numbers in the header " + numbers + ", pairs with a picture " + partners.size()
|
||||
+ ", of them with a streak " + known + ", matching the header " + (byName >= 0 ? "by number several, by name " + byName : matching.size()));
|
||||
return guessed;
|
||||
}
|
||||
|
||||
/** Every number written alone in a text of the top of the screen (the day count is one of them). */
|
||||
private static void numbersIn(View view, int limit, int depth, java.util.Set<Integer> numbers, java.util.List<String> texts, int[] count) {
|
||||
if (view == null || depth > 28 || count[0]++ > MAX_NODES || view.getVisibility() != View.VISIBLE) return;
|
||||
if (view instanceof android.widget.TextView) {
|
||||
int[] at = new int[2];
|
||||
view.getLocationOnScreen(at);
|
||||
CharSequence text = ((android.widget.TextView) view).getText();
|
||||
String value = text == null ? "" : text.toString().trim();
|
||||
if (at[1] < limit && value.matches("\\d{1,5}")) numbers.add(Integer.valueOf(Integer.parseInt(value)));
|
||||
if (at[1] < limit && value.length() > 0) texts.add(value);
|
||||
return;
|
||||
}
|
||||
if (view instanceof ViewGroup) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) numbersIn(group.getChildAt(i), limit, depth + 1, numbers, texts, count);
|
||||
}
|
||||
}
|
||||
|
||||
private static final java.util.regex.Pattern CONVERSATION = java.util.regex.Pattern.compile("0:1:(\\d{5,25}):(\\d{5,25})");
|
||||
|
||||
/**
|
||||
* The other person of the chat, read from what the chat screen was opened with: TikTok puts the id of the conversation (the two account
|
||||
* numbers) among the extras. Null when the screen carries no such id or the signed-in account is not one of the two.
|
||||
*/
|
||||
static String partnerFromScreen(Activity activity) {
|
||||
try {
|
||||
String mine = lihont.two.account.CurrentAccount.uid();
|
||||
if (mine == null) return null;
|
||||
android.content.Intent intent = activity.getIntent();
|
||||
String found = idIn(intent == null ? null : intent.getExtras(), mine);
|
||||
if (found == null) found = fromFragments(activity, mine, 0);
|
||||
return found;
|
||||
} catch (Throwable unreadable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The other account of a conversation id found in the text of a bundle, when the signed-in account is one of the two. */
|
||||
private static String idIn(android.os.Bundle bundle, String mine) {
|
||||
if (bundle == null) return null;
|
||||
String found = null;
|
||||
java.util.regex.Matcher matcher = CONVERSATION.matcher(String.valueOf(bundle));
|
||||
while (matcher.find()) {
|
||||
if (mine.equals(matcher.group(1))) found = matcher.group(2);
|
||||
else if (mine.equals(matcher.group(2))) found = matcher.group(1);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The screen of a chat is a fragment inside the activity: its arguments carry the conversation id. */
|
||||
private static String fromFragments(Object holder, String mine, int depth) throws Exception {
|
||||
if (depth > 3) return null;
|
||||
Object manager;
|
||||
if (holder instanceof Activity) {
|
||||
manager = holder.getClass().getMethod("getSupportFragmentManager").invoke(holder);
|
||||
} else {
|
||||
manager = holder.getClass().getMethod("getChildFragmentManager").invoke(holder);
|
||||
}
|
||||
java.util.List<?> fragments = (java.util.List<?>) manager.getClass().getMethod("getFragments").invoke(manager);
|
||||
for (Object fragment : fragments) {
|
||||
if (fragment == null) continue;
|
||||
android.os.Bundle arguments = (android.os.Bundle) fragment.getClass().getMethod("getArguments").invoke(fragment);
|
||||
String found = idIn(arguments, mine);
|
||||
if (found == null) {
|
||||
try {
|
||||
found = fromFragments(fragment, mine, depth + 1);
|
||||
} catch (Throwable noChildren) {
|
||||
found = null;
|
||||
}
|
||||
}
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** What fragments the screen holds, by class name and the names of their arguments (never values), for the log. */
|
||||
private static String fragmentKeys(Activity activity) {
|
||||
try {
|
||||
Object manager = activity.getClass().getMethod("getSupportFragmentManager").invoke(activity);
|
||||
java.util.List<?> fragments = (java.util.List<?>) manager.getClass().getMethod("getFragments").invoke(manager);
|
||||
StringBuilder out = new StringBuilder();
|
||||
int shown = 0;
|
||||
for (Object fragment : fragments) {
|
||||
if (fragment == null || shown++ >= 8) continue;
|
||||
android.os.Bundle arguments = (android.os.Bundle) fragment.getClass().getMethod("getArguments").invoke(fragment);
|
||||
out.append(fragment.getClass().getSimpleName()).append(arguments == null ? "[-]" : arguments.keySet().toString()).append(' ');
|
||||
}
|
||||
return "fragments " + fragments.size() + ": " + out;
|
||||
} catch (Throwable unreadable) {
|
||||
return "fragments unreadable (" + unreadable.getClass().getSimpleName() + ")";
|
||||
}
|
||||
}
|
||||
|
||||
/** The names (never the values) of what the screen was opened with, for the log. */
|
||||
private static String extraKeys(Activity activity) {
|
||||
try {
|
||||
android.os.Bundle extras = activity.getIntent() == null ? null : activity.getIntent().getExtras();
|
||||
if (extras == null) return "no extras";
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (String key : extras.keySet()) {
|
||||
if (out.length() > 0) out.append(',');
|
||||
out.append(key);
|
||||
if (out.length() > 220) break;
|
||||
}
|
||||
return "extras " + out;
|
||||
} catch (Throwable unreadable) {
|
||||
return "extras unreadable";
|
||||
}
|
||||
}
|
||||
|
||||
/** Letters and digits only, in lower case: a name with a decoration (an emoji, a dot) after it is still the same name. */
|
||||
private static String plain(String name) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < name.length(); i++) {
|
||||
char c = name.charAt(i);
|
||||
if (Character.isLetterOrDigit(c)) out.append(Character.toLowerCase(c));
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** The account of the person whose name is this one among the names kept on the phone, when exactly one has it, else null. */
|
||||
static String uidByContactName(Activity activity, String name) {
|
||||
try {
|
||||
String mine = lihont.two.account.CurrentAccount.uid();
|
||||
if (mine == null || name == null) return null;
|
||||
java.util.Map<String, String> all = lihont.two.widget.Contacts.all(activity.getApplicationContext(), mine);
|
||||
String exact = null;
|
||||
boolean exactTwice = false;
|
||||
for (java.util.Map.Entry<String, String> contact : all.entrySet()) {
|
||||
if (!name.equals(contact.getValue())) continue;
|
||||
if (exact != null && !exact.equals(contact.getKey())) exactTwice = true;
|
||||
exact = contact.getKey();
|
||||
}
|
||||
if (exact != null) return exactTwice ? null : exact;
|
||||
String wanted = plain(name);
|
||||
if (wanted.length() < 2) return null;
|
||||
String loose = null;
|
||||
for (java.util.Map.Entry<String, String> contact : all.entrySet()) {
|
||||
if (contact.getValue() == null || !wanted.equals(plain(contact.getValue()))) continue;
|
||||
if (loose != null && !loose.equals(contact.getKey())) return null;
|
||||
loose = contact.getKey();
|
||||
}
|
||||
return loose;
|
||||
} catch (Throwable unreadable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Numbers for the log, never names: how many names are kept, and how many of them equal this one exactly or without decoration. */
|
||||
private static String contactStats(Activity activity, String name) {
|
||||
try {
|
||||
String mine = lihont.two.account.CurrentAccount.uid();
|
||||
if (mine == null) return "account not known";
|
||||
java.util.Map<String, String> all = lihont.two.widget.Contacts.all(activity.getApplicationContext(), mine);
|
||||
int exact = 0;
|
||||
int loose = 0;
|
||||
String wanted = name == null ? "" : plain(name);
|
||||
for (String kept : all.values()) {
|
||||
if (name != null && name.equals(kept)) exact++;
|
||||
if (wanted.length() > 1 && kept != null && wanted.equals(plain(kept))) loose++;
|
||||
}
|
||||
return "contacts " + all.size() + ", same " + exact + ", same without decoration " + loose;
|
||||
} catch (Throwable unreadable) {
|
||||
return "contacts unreadable";
|
||||
}
|
||||
}
|
||||
|
||||
private static int[] resolve(Activity activity) {
|
||||
int[] found = new int[NAMES.length];
|
||||
for (int i = 0; i < NAMES.length; i++) {
|
||||
found[i] = activity.getResources().getIdentifier(NAMES[i], "raw", activity.getPackageName());
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
private static boolean streakIcon(int res) {
|
||||
if (res == 0) return false;
|
||||
for (int id : ids) if (id == res) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The icon resource a TikTok icon drawable was made from, or 0 when it is not one. */
|
||||
private static int iconOf(Drawable drawable) {
|
||||
if (drawable == null || !TUX_DRAWABLE.equals(drawable.getClass().getName())) return 0;
|
||||
try {
|
||||
if (!fieldTried) {
|
||||
fieldTried = true;
|
||||
iconRes = drawable.getClass().getDeclaredField("iconRes");
|
||||
iconRes.setAccessible(true);
|
||||
}
|
||||
return iconRes == null ? 0 : iconRes.getInt(drawable);
|
||||
} catch (Throwable unreadable) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Some chats show the streak with another picture than TikTok's flame (the pair's pet, a sticker): then the icon is not one of the
|
||||
* flame resources, but it still stands right before the number of days. The picture just left of a number written alone in the top
|
||||
* of the screen is taken for it.
|
||||
*/
|
||||
private static void iconByNumber(View decor, int limit, java.util.List<ImageView> flames, boolean log) {
|
||||
java.util.ArrayList<View> numbers = new java.util.ArrayList<View>();
|
||||
java.util.ArrayList<ImageView> pictures = new java.util.ArrayList<ImageView>();
|
||||
gather(decor, limit, 0, numbers, pictures, new int[1]);
|
||||
for (View number : numbers) {
|
||||
int[] at = new int[2];
|
||||
number.getLocationOnScreen(at);
|
||||
ImageView best = null;
|
||||
int bestGap = Integer.MAX_VALUE;
|
||||
for (ImageView picture : pictures) {
|
||||
int[] to = new int[2];
|
||||
picture.getLocationOnScreen(to);
|
||||
int right = to[0] + picture.getWidth();
|
||||
int gap = at[0] - right;
|
||||
boolean sameRow = Math.abs((to[1] + picture.getHeight() / 2) - (at[1] + number.getHeight() / 2)) < Math.max(picture.getHeight(), number.getHeight());
|
||||
boolean sensible = picture.getWidth() >= number.getHeight() / 2 && picture.getWidth() <= number.getHeight() * 4;
|
||||
if (sameRow && sensible && gap > -12 && gap < 140 && gap < bestGap) {
|
||||
best = picture;
|
||||
bestGap = gap;
|
||||
}
|
||||
}
|
||||
if (best != null) {
|
||||
if (log) Log.i(TAG, "pet: icon before the day count: " + best.getClass().getSimpleName() + " " + best.getWidth() + "x" + best.getHeight()
|
||||
+ " drawable=" + (best.getDrawable() == null ? "none" : best.getDrawable().getClass().getSimpleName()));
|
||||
flames.add(best);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void gather(View view, int limit, int depth, java.util.List<View> numbers, java.util.List<ImageView> pictures, int[] count) {
|
||||
if (view == null || depth > 28 || count[0]++ > MAX_NODES || view.getVisibility() != View.VISIBLE) return;
|
||||
int[] at = new int[2];
|
||||
if (view instanceof android.widget.TextView) {
|
||||
view.getLocationOnScreen(at);
|
||||
CharSequence text = ((android.widget.TextView) view).getText();
|
||||
if (at[1] < limit && text != null && text.toString().trim().matches("\\d{1,5}")) numbers.add(view);
|
||||
return;
|
||||
}
|
||||
if (view instanceof ImageView) {
|
||||
view.getLocationOnScreen(at);
|
||||
if (at[1] < limit && view.getWidth() > 0) pictures.add((ImageView) view);
|
||||
}
|
||||
if (view instanceof ViewGroup) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) gather(group.getChildAt(i), limit, depth + 1, numbers, pictures, count);
|
||||
}
|
||||
}
|
||||
|
||||
private static void collect(View view, int limit, int depth, java.util.List<ImageView> flames, int[] counters, boolean log) {
|
||||
if (view == null || depth > 28 || counters[0]++ > MAX_NODES || view.getVisibility() != View.VISIBLE) return;
|
||||
if (view instanceof ImageView) {
|
||||
int[] at = new int[2];
|
||||
view.getLocationOnScreen(at);
|
||||
if (at[1] < limit && view.getWidth() > 0) {
|
||||
Drawable drawable = ((ImageView) view).getDrawable();
|
||||
int res = iconOf(drawable);
|
||||
boolean flame = streakIcon(res);
|
||||
if (log && counters[1]++ < 14) {
|
||||
Log.i(TAG, "pet: view " + view.getClass().getSimpleName() + " " + view.getWidth() + "x" + view.getHeight() + " y=" + at[1]
|
||||
+ " drawable=" + (drawable == null ? "none" : drawable.getClass().getSimpleName())
|
||||
+ " icon=0x" + Integer.toHexString(res) + (flame ? " FLAME" : ""));
|
||||
}
|
||||
if (flame) flames.add((ImageView) view);
|
||||
}
|
||||
}
|
||||
if (view instanceof ViewGroup) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) collect(group.getChildAt(i), limit, depth + 1, flames, counters, log);
|
||||
}
|
||||
}
|
||||
}
|
||||
229
src/lihont/two/chat/PetPanel.java
Normal file
@@ -0,0 +1,229 @@
|
||||
package lihont.two.chat;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Bundle;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewTreeObserver;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The big screen of the streak pet ("Серийчик": the days, the creature in the middle, the timer). It is a page of TikTok's Lynx
|
||||
* engine in its own activity; the creature is drawn in one wide area in the upper middle. For a pair that has an animal that area
|
||||
* is not drawn any more and the animal plays in its middle, grey while the streak is frozen.
|
||||
*
|
||||
* The page is told from the other pages of the engine by what it was opened with (the word "streak"); who the pair is comes from
|
||||
* the conversation id in the same place, or else from the chat that was open last.
|
||||
*/
|
||||
public final class PetPanel {
|
||||
private static final String TAG = "LIHONT";
|
||||
private static final Pattern CONVERSATION = Pattern.compile("0:1:(\\d{5,25}):(\\d{5,25})");
|
||||
private static final WeakHashMap<View, Boolean> WATCHED = new WeakHashMap<View, Boolean>();
|
||||
private static final long SEARCH_MS = 500L;
|
||||
private static final long FROM_CHAT_MS = 4000L;
|
||||
|
||||
private PetPanel() {
|
||||
}
|
||||
|
||||
public static void watch(final Activity activity) {
|
||||
if (!activity.getClass().getName().endsWith(".SparkActivity")) return;
|
||||
final View decor = activity.getWindow().getDecorView();
|
||||
if (WATCHED.containsKey(decor)) return;
|
||||
WATCHED.put(decor, Boolean.TRUE);
|
||||
String opened = openedWith(activity);
|
||||
boolean named = opened.toLowerCase(java.util.Locale.ROOT).contains("streak");
|
||||
// the page does not always say what it is: one opened a moment after the animal was on the screen was opened from that chat
|
||||
boolean fromChat = PetFlame.lastShownAt > 0 && SystemClock.uptimeMillis() - PetFlame.lastShownAt < FROM_CHAT_MS;
|
||||
boolean streak = named || fromChat;
|
||||
String mine = lihont.two.account.CurrentAccount.uid();
|
||||
String partner = mine == null ? null : partnerIn(opened, mine);
|
||||
boolean byPage = partner != null;
|
||||
if (partner == null) partner = PetFlame.lastPartner;
|
||||
Log.i(TAG, "pet: engine page, named " + named + ", from the chat " + fromChat + ", opened with " + shape(activity) + ", pair " + (partner == null ? "not known" : byPage ? "from the page" : "from the last chat"));
|
||||
if (!streak || partner == null) return;
|
||||
final String who = partner;
|
||||
final Panel panel = new Panel();
|
||||
decor.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
|
||||
@Override public boolean onPreDraw() {
|
||||
try {
|
||||
panel.place(activity, decor, who);
|
||||
} catch (Throwable ignored) {
|
||||
// decoration: the page must never break because of it
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Everything the page was opened with, as one text (never written to the log). */
|
||||
private static String openedWith(Activity activity) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
try {
|
||||
android.content.Intent intent = activity.getIntent();
|
||||
if (intent == null) return "";
|
||||
if (intent.getDataString() != null) out.append(intent.getDataString()).append(' ');
|
||||
Bundle extras = intent.getExtras();
|
||||
if (extras != null) {
|
||||
for (String key : extras.keySet()) {
|
||||
Object value = extras.get(key);
|
||||
if (value instanceof Bundle) {
|
||||
Bundle inner = (Bundle) value;
|
||||
for (String name : inner.keySet()) out.append(name).append('=').append(inner.get(name)).append(' ');
|
||||
} else {
|
||||
out.append(key).append('=').append(value).append(' ');
|
||||
}
|
||||
if (out.length() > 60000) break;
|
||||
}
|
||||
}
|
||||
} catch (Throwable unreadable) {
|
||||
// what was read so far is used
|
||||
}
|
||||
String text = out.toString();
|
||||
// an address inside an address is escaped, sometimes twice
|
||||
for (int i = 0; i < 2 && text.indexOf('%') >= 0; i++) {
|
||||
try {
|
||||
text = java.net.URLDecoder.decode(text.replace("+", "%2B"), "UTF-8");
|
||||
} catch (Throwable notEscaped) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/** For the log: the names of what the page was opened with and the addresses up to the question mark, no values. */
|
||||
private static String shape(Activity activity) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
try {
|
||||
Bundle extras = activity.getIntent() == null ? null : activity.getIntent().getExtras();
|
||||
if (extras == null) return "nothing";
|
||||
for (String key : extras.keySet()) {
|
||||
Object value = extras.get(key);
|
||||
out.append(key);
|
||||
if (value instanceof Bundle) out.append(((Bundle) value).keySet());
|
||||
else if (value instanceof String && ((String) value).contains("://")) {
|
||||
String address = (String) value;
|
||||
int cut = address.indexOf('?');
|
||||
out.append('=').append(cut < 0 ? address : address.substring(0, cut));
|
||||
java.util.regex.Matcher names = Pattern.compile("[?&]([A-Za-z_]{2,40})=").matcher(address);
|
||||
out.append('{');
|
||||
while (names.find()) out.append(names.group(1)).append(' ');
|
||||
out.append('}');
|
||||
}
|
||||
out.append("; ");
|
||||
if (out.length() > 1500) break;
|
||||
}
|
||||
} catch (Throwable unreadable) {
|
||||
out.append("unreadable");
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String partnerIn(String text, String mine) {
|
||||
Matcher matcher = CONVERSATION.matcher(text);
|
||||
while (matcher.find()) {
|
||||
if (mine.equals(matcher.group(1))) return matcher.group(2);
|
||||
if (mine.equals(matcher.group(2))) return matcher.group(1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static final class Panel {
|
||||
private WeakReference<View> area = new WeakReference<View>(null);
|
||||
private ImageView overlay;
|
||||
private long searchedAt;
|
||||
private boolean logged;
|
||||
|
||||
void place(Activity activity, View decor, String partner) {
|
||||
if (!(decor instanceof ViewGroup)) return;
|
||||
Bitmap[] frames = PetFlame.framesFor(activity, partner);
|
||||
long now = SystemClock.uptimeMillis();
|
||||
View found = area.get();
|
||||
if (found == null || !found.isAttachedToWindow() || now - searchedAt > SEARCH_MS) {
|
||||
searchedAt = now;
|
||||
View[] best = new View[1];
|
||||
find(decor, decor.getWidth(), decor.getHeight(), 0, best, new int[1]);
|
||||
found = best[0] == null ? null : whole(best[0]);
|
||||
area = new WeakReference<View>(found);
|
||||
if (!logged && found != null) {
|
||||
logged = true;
|
||||
Log.i(TAG, "pet: page creature area " + found.getWidth() + "x" + found.getHeight() + ", animal " + (frames == null ? "not ready" : "ready"));
|
||||
}
|
||||
}
|
||||
if (found == null || frames == null) {
|
||||
if (overlay != null) overlay.setVisibility(View.GONE);
|
||||
return;
|
||||
}
|
||||
PetFlame.hide(found, 0);
|
||||
int[] at = new int[2];
|
||||
found.getLocationInWindow(at);
|
||||
int side = Math.min(found.getWidth(), found.getHeight()) * 6 / 10;
|
||||
int left = at[0] + (found.getWidth() - side) / 2;
|
||||
int top = at[1] + (found.getHeight() - side) / 2;
|
||||
if (overlay == null) {
|
||||
overlay = new ImageView(activity);
|
||||
overlay.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
overlay.setClickable(false);
|
||||
((ViewGroup) decor).addView(overlay, new FrameLayout.LayoutParams(side, side));
|
||||
}
|
||||
if (overlay.getVisibility() != View.VISIBLE) overlay.setVisibility(View.VISIBLE);
|
||||
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) overlay.getLayoutParams();
|
||||
int gravity = Gravity.TOP | Gravity.LEFT;
|
||||
// before every frame: a new layout is asked for only when the page has scrolled
|
||||
if (params.width != side || params.height != side || params.leftMargin != left || params.topMargin != top || params.gravity != gravity) {
|
||||
params.width = side;
|
||||
params.height = side;
|
||||
params.leftMargin = left;
|
||||
params.topMargin = top;
|
||||
params.gravity = gravity;
|
||||
overlay.setLayoutParams(params);
|
||||
}
|
||||
if (overlay.getTag() != frames[0]) {
|
||||
android.graphics.drawable.AnimationDrawable play = lihont.two.pet.PetArt.animation(activity, frames);
|
||||
overlay.setImageDrawable(play);
|
||||
overlay.setTag(frames[0]);
|
||||
play.start();
|
||||
}
|
||||
}
|
||||
|
||||
/** The widest plain view (no picture, no text, nothing inside) of the upper middle of the page: the creature is drawn in it. */
|
||||
private static void find(View view, int width, int height, int depth, View[] best, int[] count) {
|
||||
if (view == null || depth > 40 || count[0]++ > 2500 || view.getVisibility() != View.VISIBLE) return;
|
||||
if (view instanceof ViewGroup && ((ViewGroup) view).getChildCount() > 0) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) find(group.getChildAt(i), width, height, depth + 1, best, count);
|
||||
return;
|
||||
}
|
||||
if (view instanceof ImageView || view instanceof TextView) return;
|
||||
boolean wide = view.getWidth() >= width * 6 / 10;
|
||||
boolean tall = view.getHeight() >= height * 2 / 10 && view.getHeight() <= height * 6 / 10;
|
||||
if (!wide || !tall) return;
|
||||
if (best[0] == null || area(view) > area(best[0])) best[0] = view;
|
||||
}
|
||||
|
||||
private static long area(View view) {
|
||||
return (long) view.getWidth() * view.getHeight();
|
||||
}
|
||||
|
||||
/** The topmost holder of the same size: the engine may draw parts of the creature in the holders around the view. */
|
||||
private static View whole(View view) {
|
||||
View holder = view;
|
||||
while (holder.getParent() instanceof View) {
|
||||
View parent = (View) holder.getParent();
|
||||
if (parent.getWidth() > view.getWidth() * 11 / 10 || parent.getHeight() > view.getHeight() * 11 / 10) break;
|
||||
holder = parent;
|
||||
}
|
||||
return holder;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ public final class Windows implements Application.ActivityLifecycleCallbacks {
|
||||
}
|
||||
try {
|
||||
lihont.two.chat.Bubbles.watch(activity);
|
||||
lihont.two.chat.PetPanel.watch(activity);
|
||||
} catch (Throwable ignored) {
|
||||
// bubbles are an extra
|
||||
}
|
||||
|
||||
90
src/lihont/two/pet/GiftActivity.java
Normal file
@@ -0,0 +1,90 @@
|
||||
package lihont.two.pet;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import lihont.two.badge.NicheClaim;
|
||||
import lihont.two.widget.Contacts;
|
||||
|
||||
/**
|
||||
* Opens from the link lihont.space/pet?kind=cat&from=ID (or lihont://pet?...) and asks before it does anything: "Саша дарит вам
|
||||
* котёнка. Принять?". The link says only who and which animal; the offer itself is on the members service, so a link nobody made
|
||||
* changes nothing. Yes makes the animal the pair's on both phones, no throws the offer away.
|
||||
*/
|
||||
public final class GiftActivity extends Activity {
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
Uri uri = getIntent() == null ? null : getIntent().getData();
|
||||
String kind = uri == null ? null : uri.getQueryParameter("kind");
|
||||
String from = uri == null ? null : uri.getQueryParameter("from");
|
||||
NicheClaim.Account me = NicheClaim.account();
|
||||
if (!Species.known(kind) || from == null || !from.matches("\\d{6,24}")) {
|
||||
end("Эта ссылка не подходит");
|
||||
} else if (me == null || me.uid == null) {
|
||||
end("Сначала войдите в TikTok, потом откройте ссылку ещё раз");
|
||||
} else if (from.equals(me.uid)) {
|
||||
end("Эту ссылку нужно отправить другу");
|
||||
} else {
|
||||
ask(me.uid, from);
|
||||
}
|
||||
}
|
||||
|
||||
private void ask(final String mine, final String from) {
|
||||
Species.look(this, mine, from, new Species.Done() {
|
||||
@Override public void done(boolean ok, String offer) {
|
||||
if (isFinishing()) return;
|
||||
if (!ok) {
|
||||
end(offer);
|
||||
} else if (offer.isEmpty()) {
|
||||
end("Предложения от этого человека нет или оно устарело. Пусть пришлёт новую ссылку");
|
||||
} else {
|
||||
confirm(mine, from, offer);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void confirm(final String mine, final String from, final String offer) {
|
||||
Map<String, String> names = Contacts.all(this, mine);
|
||||
String name = names == null ? null : names.get(from);
|
||||
String who = name == null || name.trim().isEmpty() ? "Друг" : name;
|
||||
new AlertDialog.Builder(this)
|
||||
.setTitle("Серийчик")
|
||||
.setMessage(who + " дарит вам " + Species.gift(offer) + ". Он будет жить в вашем общем чате и расти вместе с серией. Принять?")
|
||||
.setPositiveButton("Принять", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface dialog, int which) {
|
||||
reply(mine, from, true);
|
||||
}
|
||||
})
|
||||
.setNegativeButton("Не надо", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface dialog, int which) {
|
||||
reply(mine, from, false);
|
||||
}
|
||||
})
|
||||
.setOnCancelListener(new DialogInterface.OnCancelListener() {
|
||||
@Override public void onCancel(DialogInterface dialog) {
|
||||
finish();
|
||||
}
|
||||
})
|
||||
.show();
|
||||
}
|
||||
|
||||
private void reply(String mine, String from, final boolean accept) {
|
||||
Species.answer(this, mine, from, accept, new Species.Done() {
|
||||
@Override public void done(boolean ok, String text) {
|
||||
end(!ok ? text : accept ? "Теперь у вас " + Species.label(text) : "Хорошо, оставили как было");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void end(String message) {
|
||||
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
|
||||
finish();
|
||||
}
|
||||
}
|
||||
129
src/lihont/two/pet/PetArt.java
Normal file
@@ -0,0 +1,129 @@
|
||||
package lihont.two.pet;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.drawable.AnimationDrawable;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The drawings of the animals of a pair. An animal has four ages (by the days of the streak) and two moods (lit, or grey when the streak
|
||||
* is about to end); each is one strip of 8 frames (tail wag, ear twitch, blink) that the site serves and the phone keeps. Nothing is
|
||||
* drawn while a strip is not on the phone yet: the caller shows what it showed before and asks again, the strip comes by itself.
|
||||
*/
|
||||
public final class PetArt {
|
||||
private static final String BASE = "https://lihont.space/assets/pets/strips/";
|
||||
private static final int FRAMES = 8;
|
||||
private static final int LIMIT = 600 * 1024;
|
||||
private static final Map<String, Bitmap[]> MEMORY = new HashMap<String, Bitmap[]>();
|
||||
private static final Set<String> LOADING = new HashSet<String>();
|
||||
private static final Map<String, Long> FAILED = new HashMap<String, Long>();
|
||||
private static final long RETRY_MS = 60000L;
|
||||
|
||||
private PetArt() {
|
||||
}
|
||||
|
||||
/** cub, teen, adult or elder, by the days of the streak. */
|
||||
public static String stage(int days) {
|
||||
if (days < 7) return "cub";
|
||||
if (days < 30) return "teen";
|
||||
if (days < 100) return "adult";
|
||||
return "elder";
|
||||
}
|
||||
|
||||
private static String name(String kind, int days, boolean grey) {
|
||||
return kind + "_" + stage(days) + "_" + (grey ? "grey" : "lit");
|
||||
}
|
||||
|
||||
/** The 8 frames, or null while the strip is not on the phone (then it is fetched, and `ready` runs on a worker thread when it is). */
|
||||
public static synchronized Bitmap[] frames(Context context, String kind, int days, boolean grey, Runnable ready) {
|
||||
if (!Species.known(kind)) return null;
|
||||
final String name = name(kind, days, grey);
|
||||
Bitmap[] cached = MEMORY.get(name);
|
||||
if (cached != null) return cached;
|
||||
final Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context;
|
||||
File file = new File(new File(app.getFilesDir(), "pet_strips"), name + ".png");
|
||||
if (file.isFile()) {
|
||||
Bitmap[] loaded = cut(BitmapFactory.decodeFile(file.getPath()));
|
||||
if (loaded != null) {
|
||||
MEMORY.put(name, loaded);
|
||||
return loaded;
|
||||
}
|
||||
file.delete();
|
||||
}
|
||||
// this is asked before every frame: a fetch that failed (no network, no such strip) is tried again a minute later, not at once
|
||||
Long failed = FAILED.get(name);
|
||||
long now = android.os.SystemClock.uptimeMillis();
|
||||
if (failed != null && now - failed.longValue() < RETRY_MS) return null;
|
||||
if (LOADING.add(name)) fetch(file, name, ready);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** One drawable that plays the strip over and over. */
|
||||
public static AnimationDrawable animation(Context context, Bitmap[] frames) {
|
||||
AnimationDrawable animation = new AnimationDrawable();
|
||||
for (Bitmap frame : frames) animation.addFrame(new BitmapDrawable(context.getResources(), frame), 200);
|
||||
animation.setOneShot(false);
|
||||
return animation;
|
||||
}
|
||||
|
||||
private static Bitmap[] cut(Bitmap strip) {
|
||||
if (strip == null || strip.getWidth() < FRAMES || strip.getHeight() < 1) return null;
|
||||
int cell = strip.getWidth() / FRAMES;
|
||||
Bitmap[] out = new Bitmap[FRAMES];
|
||||
for (int i = 0; i < FRAMES; i++) out[i] = Bitmap.createBitmap(strip, i * cell, 0, cell, strip.getHeight());
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void fetch(final File file, final String name, final Runnable ready) {
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
boolean ok = false;
|
||||
try {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(BASE + name + ".png").openConnection();
|
||||
connection.setConnectTimeout(8000);
|
||||
connection.setReadTimeout(15000);
|
||||
if (connection.getResponseCode() == 200) {
|
||||
InputStream in = connection.getInputStream();
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[8192];
|
||||
int n;
|
||||
while ((n = in.read(buffer)) > 0) {
|
||||
bytes.write(buffer, 0, n);
|
||||
if (bytes.size() > LIMIT) throw new java.io.IOException("too big");
|
||||
}
|
||||
in.close();
|
||||
byte[] data = bytes.toByteArray();
|
||||
if (cut(BitmapFactory.decodeByteArray(data, 0, data.length)) != null) {
|
||||
file.getParentFile().mkdirs();
|
||||
FileOutputStream out = new FileOutputStream(file);
|
||||
out.write(data);
|
||||
out.close();
|
||||
ok = true;
|
||||
}
|
||||
}
|
||||
} catch (Exception unreachable) {
|
||||
ok = false;
|
||||
} finally {
|
||||
synchronized (PetArt.class) {
|
||||
LOADING.remove(name);
|
||||
if (ok) FAILED.remove(name);
|
||||
else FAILED.put(name, Long.valueOf(android.os.SystemClock.uptimeMillis()));
|
||||
}
|
||||
}
|
||||
if (ok && ready != null) ready.run();
|
||||
}
|
||||
}, "lihont-pet-art").start();
|
||||
}
|
||||
}
|
||||
186
src/lihont/two/pet/Species.java
Normal file
@@ -0,0 +1,186 @@
|
||||
package lihont.two.pet;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import lihont.two.avatar.Installation;
|
||||
import lihont.two.badge.MemberClient;
|
||||
|
||||
/**
|
||||
* The animal of a pair: one word ("cat", "dog", "lion"), the same on both phones. One of the two gives it by a link
|
||||
* (lihont.space/pet?kind=cat&from=ID); it becomes the pair's when the other accepts. It lives on the members service
|
||||
* (species_offer / species_lookup / species_answer); the phone keeps the last answer, so the screens draw at once.
|
||||
*/
|
||||
public final class Species {
|
||||
public static final String[] KINDS = {"cat", "dog", "lion"};
|
||||
private static final String PREFS = "lihont_pet_species";
|
||||
private static final Handler MAIN = new Handler(Looper.getMainLooper());
|
||||
|
||||
public interface Done {
|
||||
void done(boolean ok, String text);
|
||||
}
|
||||
|
||||
private Species() {
|
||||
}
|
||||
|
||||
public static boolean known(String kind) {
|
||||
for (String one : KINDS) if (one.equals(kind)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** What the animal is called when it is small. */
|
||||
public static String label(String kind) {
|
||||
if ("cat".equals(kind)) return "котёнок";
|
||||
if ("dog".equals(kind)) return "щенок";
|
||||
if ("lion".equals(kind)) return "львёнок";
|
||||
return "питомец";
|
||||
}
|
||||
|
||||
/** The same, as "дарит вам ...". */
|
||||
public static String gift(String kind) {
|
||||
if ("cat".equals(kind)) return "котёнка";
|
||||
if ("dog".equals(kind)) return "щенка";
|
||||
if ("lion".equals(kind)) return "львёнка";
|
||||
return "питомца";
|
||||
}
|
||||
|
||||
/** The link the other one opens. */
|
||||
public static String link(String mine, String kind) {
|
||||
return "https://lihont.space/pet/?kind=" + kind + "&from=" + mine;
|
||||
}
|
||||
|
||||
/** The animal the pair has, or "" while they have none (the last answer of the service). */
|
||||
public static String kind(Context context, String mine, String peer) {
|
||||
return prefs(context).getString("kind_" + key(mine, peer), "");
|
||||
}
|
||||
|
||||
private static final java.util.Map<String, Long> ASKED = new java.util.HashMap<String, Long>();
|
||||
|
||||
/** The people the signed-in account has an animal with. */
|
||||
public static java.util.List<String> partners(Context context, String mine) {
|
||||
java.util.ArrayList<String> out = new java.util.ArrayList<String>();
|
||||
for (java.util.Map.Entry<String, ?> entry : prefs(context).getAll().entrySet()) {
|
||||
if (!entry.getKey().startsWith("kind_") || !(entry.getValue() instanceof String) || ((String) entry.getValue()).isEmpty()) continue;
|
||||
String[] pair = entry.getKey().substring(5).split(":");
|
||||
if (pair.length != 2) continue;
|
||||
if (mine.equals(pair[0])) out.add(pair[1]);
|
||||
else if (mine.equals(pair[1])) out.add(pair[0]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Asks the service what the pair has, at most every ten minutes, so an animal given on the other phone turns up here by itself. */
|
||||
public static synchronized void refresh(Context context, String mine, String peer) {
|
||||
String key = key(mine, peer);
|
||||
long now = android.os.SystemClock.uptimeMillis();
|
||||
Long last = ASKED.get(key);
|
||||
if (last != null && now - last.longValue() < 10L * 60L * 1000L) return;
|
||||
ASKED.put(key, Long.valueOf(now));
|
||||
look(context, mine, peer, null);
|
||||
}
|
||||
|
||||
/** Gives the pair an animal: the offer goes to the service, then the link can be sent. */
|
||||
public static void offer(final Context context, final String mine, final String peer, final String kind, final Done done) {
|
||||
final Context app = app(context);
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
boolean ok = false;
|
||||
String text;
|
||||
try {
|
||||
if (!known(kind)) throw new IllegalArgumentException("Unknown animal");
|
||||
MemberClient.post("species_offer", new JSONObject().put("uid", mine).put("peer", peer).put("kind", kind)
|
||||
.put("installation", Installation.secret(app)));
|
||||
ok = true;
|
||||
text = link(mine, kind);
|
||||
} catch (Exception error) {
|
||||
text = explain(error.getMessage());
|
||||
}
|
||||
finish(done, ok, text);
|
||||
}
|
||||
}, "lihont-species-offer").start();
|
||||
}
|
||||
|
||||
/** Asks what the pair has and whether the other one has offered an animal: done(true, offeredKind or ""). */
|
||||
public static void look(final Context context, final String mine, final String peer, final Done done) {
|
||||
final Context app = app(context);
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
boolean ok = false;
|
||||
String text;
|
||||
try {
|
||||
JSONObject reply = MemberClient.post("species_lookup", new JSONObject().put("uid", mine).put("peer", peer)
|
||||
.put("installation", Installation.secret(app)));
|
||||
String kind = reply.optString("kind", "");
|
||||
remember(app, mine, peer, known(kind) ? kind : "");
|
||||
String offer = reply.optString("offer", "");
|
||||
text = known(offer) ? offer : "";
|
||||
ok = true;
|
||||
} catch (Exception error) {
|
||||
text = explain(error.getMessage());
|
||||
}
|
||||
finish(done, ok, text);
|
||||
}
|
||||
}, "lihont-species-look").start();
|
||||
}
|
||||
|
||||
/** The other one says yes or no to the offer. */
|
||||
public static void answer(final Context context, final String mine, final String peer, final boolean accept, final Done done) {
|
||||
final Context app = app(context);
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
boolean ok = false;
|
||||
String text;
|
||||
try {
|
||||
JSONObject reply = MemberClient.post("species_answer", new JSONObject().put("uid", mine).put("peer", peer).put("accept", accept)
|
||||
.put("installation", Installation.secret(app)));
|
||||
String kind = reply.optString("kind", "");
|
||||
remember(app, mine, peer, known(kind) ? kind : "");
|
||||
ok = true;
|
||||
text = kind;
|
||||
} catch (Exception error) {
|
||||
text = explain(error.getMessage());
|
||||
}
|
||||
finish(done, ok, text);
|
||||
}
|
||||
}, "lihont-species-answer").start();
|
||||
}
|
||||
|
||||
/** The service answers in English; the person reads Russian. */
|
||||
static String explain(String message) {
|
||||
if (message == null) return "Нет связи с сервером";
|
||||
if (message.startsWith("There is no offer")) return "Это предложение уже устарело или отменено";
|
||||
if (message.startsWith("Prove the account")) return "Сначала подтвердите аккаунт в настройках LihonT";
|
||||
if (message.startsWith("Account excluded")) return "Аккаунт исключён";
|
||||
if (message.startsWith("Unknown animal")) return "Такого зверя пока нет";
|
||||
return message;
|
||||
}
|
||||
|
||||
private static void remember(Context context, String mine, String peer, String kind) {
|
||||
prefs(context).edit().putString("kind_" + key(mine, peer), kind).apply();
|
||||
}
|
||||
|
||||
private static void finish(final Done done, final boolean ok, final String text) {
|
||||
if (done == null) return;
|
||||
MAIN.post(new Runnable() {
|
||||
@Override public void run() {
|
||||
done.done(ok, text);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static Context app(Context context) {
|
||||
return context.getApplicationContext() != null ? context.getApplicationContext() : context;
|
||||
}
|
||||
|
||||
private static String key(String mine, String peer) {
|
||||
return mine.compareTo(peer) < 0 ? mine + ":" + peer : peer + ":" + mine;
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
}
|
||||
}
|
||||
@@ -251,6 +251,12 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
pairRow.setOnClickListener(v -> askPairPerson());
|
||||
cardChat.addView(pairRow);
|
||||
cardChat.addView(Md3.cardDivider(this, palette));
|
||||
LinearLayout petRow = Md3.listItem(this, palette,
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.FLAME, palette.onPrimaryContainer, 8),
|
||||
"Серийчик", "Одна картинка вместо питомца серии, её видите вы оба. Собеседнику нужен мод", Md3.chevron(this, palette), true);
|
||||
petRow.setOnClickListener(v -> askPetPerson());
|
||||
cardChat.addView(petRow);
|
||||
cardChat.addView(Md3.cardDivider(this, palette));
|
||||
cardChat.addView(bubbleColorRow("Цвет текста: мой", true));
|
||||
cardChat.addView(Md3.cardDivider(this, palette));
|
||||
cardChat.addView(bubbleColorRow("Цвет текста: собеседника", false));
|
||||
@@ -690,6 +696,8 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
private String pairPeer;
|
||||
private java.util.List<lihont.two.store.StoreClient.Piece> libraryPieces = new java.util.ArrayList<lihont.two.store.StoreClient.Piece>();
|
||||
private String pairPeerName;
|
||||
private static final int REQUEST_PET = 4105;
|
||||
private boolean petMode; // the picture being chosen is for the Серийчик, not for the chat
|
||||
private String bubbleSlot;
|
||||
|
||||
private View bubblesSwitchRow() {
|
||||
@@ -1241,9 +1249,9 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
list.setOrientation(LinearLayout.VERTICAL);
|
||||
final Dialog[] shown = new Dialog[1];
|
||||
int count = 0;
|
||||
for (final String person : lihont.two.chat.BubbleStore.people(this)) {
|
||||
final String uid = lihont.two.chat.BubbleStore.accountOf(this, person);
|
||||
if (uid == null) continue;
|
||||
for (final String[] candidate : pairCandidates()) {
|
||||
final String uid = candidate[0];
|
||||
final String person = candidate[1];
|
||||
count++;
|
||||
TextView item = Md3.text(this, person, Md3.BODY_LARGE, false, palette.onSurface);
|
||||
item.setPadding(Md3.dp(this, 8), Md3.dp(this, 14), Md3.dp(this, 8), Md3.dp(this, 14));
|
||||
@@ -1258,7 +1266,7 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
list.addView(item);
|
||||
}
|
||||
if (count == 0) {
|
||||
list.addView(Md3.text(this, "Пока никого. Откройте чат с человеком, и он появится здесь.", Md3.BODY_MEDIUM,
|
||||
list.addView(Md3.text(this, "Пока никого. Откройте чат с человеком или полистайте список чатов, и он появится здесь.", Md3.BODY_MEDIUM,
|
||||
false, palette.onSurfaceVariant));
|
||||
}
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
@@ -1266,6 +1274,186 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
shown[0] = bubbleDialog("Картинка на двоих: с кем чат", scroll, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The people a shared picture can be made with, as {account id, name}: the chats the mod has opened with the account known, and
|
||||
* the people this account has a streak chat with (found among the names TikTok has shown, as the streak widget's picker does).
|
||||
*/
|
||||
private List<String[]> pairCandidates() {
|
||||
java.util.LinkedHashMap<String, String> byUid = new java.util.LinkedHashMap<String, String>();
|
||||
for (String person : lihont.two.chat.BubbleStore.people(this)) {
|
||||
String uid = lihont.two.chat.BubbleStore.accountOf(this, person);
|
||||
if (uid != null) byUid.put(uid, person);
|
||||
}
|
||||
String mine = lihont.two.account.CurrentAccount.uid();
|
||||
if (mine != null) {
|
||||
Context app = getApplicationContext() != null ? getApplicationContext() : this;
|
||||
for (java.util.Map.Entry<String, String> contact : lihont.two.widget.Contacts.all(app, mine).entrySet()) {
|
||||
if (contact.getKey().equals(mine) || byUid.containsKey(contact.getKey())) continue;
|
||||
if (contact.getValue() == null || contact.getValue().length() == 0) continue;
|
||||
// the list holds everybody TikTok showed a name of (the feed, comments...): only those with a streak chat are partners
|
||||
if (lihont.two.widget.StreakApi.info(lihont.two.widget.StreakApi.conversationId(mine, contact.getKey())) == null) continue;
|
||||
byUid.put(contact.getKey(), contact.getValue());
|
||||
}
|
||||
}
|
||||
List<String[]> found = new ArrayList<String[]>();
|
||||
for (java.util.Map.Entry<String, String> entry : byUid.entrySet()) found.add(new String[] {entry.getKey(), entry.getValue()});
|
||||
java.util.Collections.sort(found, new java.util.Comparator<String[]>() {
|
||||
@Override public int compare(String[] a, String[] b) {
|
||||
return a[1].compareToIgnoreCase(b[1]);
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The same people as for the chat picture: whose Серийчик to change. */
|
||||
private void askPetPerson() {
|
||||
LinearLayout list = new LinearLayout(this);
|
||||
list.setOrientation(LinearLayout.VERTICAL);
|
||||
final Dialog[] shown = new Dialog[1];
|
||||
int count = 0;
|
||||
for (final String[] candidate : pairCandidates()) {
|
||||
final String uid = candidate[0];
|
||||
final String person = candidate[1];
|
||||
count++;
|
||||
TextView item = Md3.text(this, person, Md3.BODY_LARGE, false, palette.onSurface);
|
||||
item.setPadding(Md3.dp(this, 8), Md3.dp(this, 14), Md3.dp(this, 8), Md3.dp(this, 14));
|
||||
item.setBackground(Md3.stateLayer(this, Md3.SHAPE_EXTRA_SMALL, Md3.stateLayerColor(palette.onSurface)));
|
||||
item.setClickable(true);
|
||||
item.setOnClickListener(v -> {
|
||||
shown[0].dismiss();
|
||||
pairPeer = uid;
|
||||
pairPeerName = person;
|
||||
showPet();
|
||||
});
|
||||
list.addView(item);
|
||||
}
|
||||
if (count == 0) {
|
||||
list.addView(Md3.text(this, "Пока никого. Откройте чат с человеком или полистайте список чатов, и он появится здесь.", Md3.BODY_MEDIUM,
|
||||
false, palette.onSurfaceVariant));
|
||||
}
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.addView(list, new ScrollView.LayoutParams(-1, -2));
|
||||
shown[0] = bubbleDialog("Серийчик: с кем чат", scroll, null, null);
|
||||
}
|
||||
|
||||
/** The Серийчик of the pair: the picture shown, its state, the earlier ones to bring back, and the buttons. */
|
||||
private void showPet() {
|
||||
final String peer = pairPeer;
|
||||
LinearLayout body = new LinearLayout(this);
|
||||
body.setOrientation(LinearLayout.VERTICAL);
|
||||
body.addView(Md3.text(this, "Чат с " + pairPeerName + ". Менять картинку может любой из вас двоих. Новую сначала проверят, "
|
||||
+ "пока её не приняли, остаётся прежняя. Менять можно раз в час.", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant));
|
||||
final ImageView current = new ImageView(this);
|
||||
current.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
LinearLayout.LayoutParams currentParams = new LinearLayout.LayoutParams(-1, Md3.dp(this, 160));
|
||||
currentParams.topMargin = Md3.dp(this, 12);
|
||||
body.addView(current, currentParams);
|
||||
final TextView status = Md3.text(this, "Загружаем…", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant);
|
||||
status.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8));
|
||||
body.addView(status);
|
||||
final LinearLayout older = new LinearLayout(this);
|
||||
older.setOrientation(LinearLayout.HORIZONTAL);
|
||||
final android.widget.HorizontalScrollView strip = new android.widget.HorizontalScrollView(this);
|
||||
strip.addView(older);
|
||||
strip.setVisibility(View.GONE);
|
||||
body.addView(strip);
|
||||
body.addView(Md3.text(this, "Подарить зверя. Он будет жить в вашем общем чате и расти вместе с серией. Другу придёт ссылка, "
|
||||
+ "он нажмёт «Принять» (ему нужен мод).", Md3.BODY_SMALL, false, palette.onSurfaceVariant));
|
||||
LinearLayout gifts = new LinearLayout(this);
|
||||
gifts.setOrientation(LinearLayout.HORIZONTAL);
|
||||
for (final String kind : lihont.two.pet.Species.KINDS) {
|
||||
TextView give = Md3.textButton(this, palette, Character.toUpperCase(lihont.two.pet.Species.label(kind).charAt(0))
|
||||
+ lihont.two.pet.Species.label(kind).substring(1));
|
||||
give.setOnClickListener(v -> giveAnimal(peer, kind));
|
||||
gifts.addView(give);
|
||||
}
|
||||
body.addView(gifts);
|
||||
TextView clear = Md3.textButton(this, palette, "Убрать Серийчик");
|
||||
clear.setOnClickListener(v -> lihont.two.avatar.PetPictures.clear(this, peer,
|
||||
result -> Toast.makeText(this, result.message, Toast.LENGTH_LONG).show()));
|
||||
body.addView(clear);
|
||||
final Dialog dialog = bubbleDialog("Серийчик", body, "Выбрать картинку", this::pickPet);
|
||||
lihont.two.avatar.PetPictures.lookup(this, peer, (info, problem) -> {
|
||||
if (isFinishing()) return;
|
||||
if (info == null) {
|
||||
status.setText(problem == null ? "Нет связи с сервером" : problem);
|
||||
return;
|
||||
}
|
||||
status.setText(info.id.length() == 0
|
||||
? (info.pending ? "Картинка ждёт проверки" : "Картинки пока нет. Выберите первую")
|
||||
: (info.pending ? "Новая картинка ждёт проверки, пока показывается эта" : "Так выглядит ваш Серийчик"));
|
||||
showPetPicture(current, info.id);
|
||||
if (info.history.isEmpty()) return;
|
||||
strip.setVisibility(View.VISIBLE);
|
||||
older.addView(Md3.text(this, "Прежние: ", Md3.BODY_SMALL, false, palette.onSurfaceVariant));
|
||||
for (final String earlier : info.history) {
|
||||
ImageView thumb = new ImageView(this);
|
||||
thumb.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
thumb.setClickable(true);
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Md3.dp(this, 64), Md3.dp(this, 64));
|
||||
params.rightMargin = Md3.dp(this, 8);
|
||||
thumb.setOnClickListener(v -> lihont.two.avatar.PetPictures.revert(this, peer, earlier, result -> {
|
||||
Toast.makeText(this, result.message, Toast.LENGTH_LONG).show();
|
||||
if (result.published && !isFinishing()) {
|
||||
dialog.dismiss();
|
||||
showPet();
|
||||
}
|
||||
}));
|
||||
older.addView(thumb, params);
|
||||
showPetPicture(thumb, earlier);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Gives the pair an animal: the offer goes to the service, then the link is handed to the share sheet. */
|
||||
private void giveAnimal(String peer, final String kind) {
|
||||
lihont.two.badge.NicheClaim.Account me = lihont.two.badge.NicheClaim.account();
|
||||
if (me == null || me.uid == null) {
|
||||
Toast.makeText(this, "Войдите в TikTok", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
final String mine = me.uid;
|
||||
lihont.two.pet.Species.offer(this, mine, peer, kind, (ok, text) -> {
|
||||
if (isFinishing()) return;
|
||||
if (!ok) {
|
||||
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
|
||||
return;
|
||||
}
|
||||
Intent send = new Intent(Intent.ACTION_SEND).setType("text/plain")
|
||||
.putExtra(Intent.EXTRA_TEXT, "Дарю тебе " + lihont.two.pet.Species.gift(kind) + " для нашего чата: " + text);
|
||||
try {
|
||||
startActivity(Intent.createChooser(send, "Отправить ссылку"));
|
||||
} catch (ActivityNotFoundException none) {
|
||||
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Puts the picture with this id into the view: fetched off the main thread when it is not on the phone yet. */
|
||||
private void showPetPicture(final ImageView view, final String id) {
|
||||
if (id == null || id.length() == 0) return;
|
||||
new Thread(() -> {
|
||||
final Bitmap picture = lihont.two.avatar.PairPictures.fetchNow(this, id);
|
||||
handler.post(() -> {
|
||||
if (!isFinishing() && picture != null) view.setImageBitmap(picture);
|
||||
});
|
||||
}, "lihont-pet-show").start();
|
||||
}
|
||||
|
||||
private void pickPet() {
|
||||
petMode = true;
|
||||
try {
|
||||
startActivityForResult(IconShortcuts.pickIntent(), REQUEST_PET);
|
||||
} catch (ActivityNotFoundException | SecurityException none) {
|
||||
Toast.makeText(this, "Не нашлось приложения для выбора фото", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void uploadShared(String peer, byte[] png, lihont.two.avatar.ShapePublisher.Callback callback) {
|
||||
if (petMode) lihont.two.avatar.PetPictures.upload(this, peer, png, callback);
|
||||
else lihont.two.avatar.PairPictures.upload(this, peer, png, callback);
|
||||
}
|
||||
|
||||
private void askPairAction() {
|
||||
final String peer = pairPeer;
|
||||
LinearLayout body = new LinearLayout(this);
|
||||
@@ -1280,6 +1468,7 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
}
|
||||
|
||||
private void pickPair() {
|
||||
petMode = false;
|
||||
try {
|
||||
startActivityForResult(IconShortcuts.pickIntent(), REQUEST_PAIR);
|
||||
} catch (ActivityNotFoundException | SecurityException none) {
|
||||
@@ -1327,7 +1516,7 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this));
|
||||
root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16));
|
||||
root.addView(Md3.text(this, "Картинка на двоих", Md3.HEADLINE_SMALL, false, palette.onSurface));
|
||||
root.addView(Md3.text(this, petMode ? "Серийчик" : "Картинка на двоих", Md3.HEADLINE_SMALL, false, palette.onSurface));
|
||||
ImageView preview = new ImageView(this);
|
||||
preview.setImageBitmap(picture);
|
||||
preview.setAdjustViewBounds(true);
|
||||
@@ -1335,7 +1524,8 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
previewParams.topMargin = Md3.dp(this, 16);
|
||||
preview.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
root.addView(preview, previewParams);
|
||||
TextView note = Md3.text(this, "Вы увидите её сразу. Собеседнику её покажут после проверки, ему нужен мод.",
|
||||
TextView note = Md3.text(this, petMode ? "Вы увидите её сразу. Собеседнику её покажут после проверки, ему нужен мод. "
|
||||
+ "Пока её не приняли, остаётся прежняя картинка у обоих." : "Вы увидите её сразу. Собеседнику её покажут после проверки, ему нужен мод.",
|
||||
Md3.BODY_MEDIUM, false, palette.onSurfaceVariant);
|
||||
note.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 8));
|
||||
root.addView(note);
|
||||
@@ -1346,11 +1536,11 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
TextView send = Md3.textButton(this, palette, "Отправить");
|
||||
send.setOnClickListener(v -> {
|
||||
dialog.dismiss();
|
||||
lihont.two.avatar.PairPictures.upload(this, peer, png, result -> {
|
||||
uploadShared(peer, png, result -> {
|
||||
if (result.published || result.code == null) {
|
||||
Toast.makeText(this, result.message, Toast.LENGTH_LONG).show();
|
||||
} else {
|
||||
openProofDialog("картинку", result.code, retry -> lihont.two.avatar.PairPictures.upload(this, peer, png, retry));
|
||||
openProofDialog("картинку", result.code, retry -> uploadShared(peer, png, retry));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1923,7 +2113,7 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
|
||||
@Override protected void onActivityResult(int request, int result, Intent data) {
|
||||
super.onActivityResult(request, result, data);
|
||||
if (request == REQUEST_PAIR) {
|
||||
if (request == REQUEST_PAIR || request == REQUEST_PET) {
|
||||
if (result == RESULT_OK && data != null && data.getData() != null) pairPicked(data.getData());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -26,8 +26,11 @@ public final class StreakApi {
|
||||
public final int streak;
|
||||
public final long endAt;
|
||||
public final long remindAt;
|
||||
/** The end of the day both have written in: after it, and until the streak ends, TikTok shows the streak grey. */
|
||||
public final long activeBefore;
|
||||
|
||||
Info(String conversation, int streak, long endAt, long remindAt) {
|
||||
Info(String conversation, int streak, long endAt, long remindAt, long activeBefore) {
|
||||
this.activeBefore = activeBefore;
|
||||
this.conversation = conversation;
|
||||
this.streak = streak;
|
||||
this.endAt = endAt;
|
||||
@@ -39,6 +42,8 @@ public final class StreakApi {
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean dumped;
|
||||
public static String lastFields = "";
|
||||
private static Object service;
|
||||
private static Method dataMethod;
|
||||
private static final Object NONE = new Object();
|
||||
@@ -55,6 +60,18 @@ public final class StreakApi {
|
||||
return remind > 0 && nowMillis >= remind && (end == 0 || nowMillis < end);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether TikTok shows this streak grey ("frozen"): the day the two have both written in is over and nobody has written since,
|
||||
* but the streak has not ended yet. Seen on the phone: grey at a moment before the reminder, with activeBefore a day before endAt.
|
||||
*/
|
||||
public static boolean frozen(Info info, long nowMillis) {
|
||||
if (info == null) return false;
|
||||
long end = millis(info.endAt);
|
||||
long before = millis(info.activeBefore);
|
||||
if (before <= 0 && end > 0) before = end - 86400000L;
|
||||
return before > 0 && nowMillis >= before && (end == 0 || nowMillis < end);
|
||||
}
|
||||
|
||||
/** The service reports seconds or milliseconds; anything below 10^11 is taken for seconds. */
|
||||
public static long millis(long value) {
|
||||
return value > 0 && value < 100000000000L ? value * 1000L : value;
|
||||
@@ -79,8 +96,18 @@ public final class StreakApi {
|
||||
if (data == null) return null;
|
||||
int streak = ((Number) field(data, "streak")).intValue();
|
||||
if (streak <= 0) return null;
|
||||
if (!dumped) {
|
||||
dumped = true;
|
||||
StringBuilder fields = new StringBuilder();
|
||||
for (Field one : data.getClass().getFields()) {
|
||||
Object value = one.get(data);
|
||||
if (value instanceof Number || value instanceof Boolean) fields.append(one.getName()).append('=').append(value).append(' ');
|
||||
}
|
||||
lastFields = fields.toString();
|
||||
Log.i(TAG, "streak fields: " + fields);
|
||||
}
|
||||
return new Info(conversation, streak, ((Number) field(data, "endAt")).longValue(),
|
||||
((Number) field(data, "remindAt")).longValue());
|
||||
((Number) field(data, "remindAt")).longValue(), number(data, "activeBefore"));
|
||||
} catch (Throwable unavailable) {
|
||||
Log.i(TAG, "streak: " + unavailable);
|
||||
return null;
|
||||
@@ -103,6 +130,16 @@ public final class StreakApi {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A number field that may be missing in another version of TikTok: then 0. */
|
||||
private static long number(Object data, String name) {
|
||||
try {
|
||||
Object value = field(data, name);
|
||||
return value instanceof Number ? ((Number) value).longValue() : 0L;
|
||||
} catch (Throwable missing) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
private static Object field(Object data, String name) throws Exception {
|
||||
Field field = data.getClass().getField(name);
|
||||
return field.get(data);
|
||||
|
||||
@@ -36,16 +36,7 @@ public class StreakWidget extends AppWidgetProvider {
|
||||
/** The route TikTok itself opens a direct chat with, by the account id of the other person. */
|
||||
private static final String CHAT_ROUTE = "snssdk1233://chat/message?uid=";
|
||||
|
||||
// Resource ids of TikTok 47.1.3's own layout of the small Stories widget (res/b/pr.xml).
|
||||
private static final int LAYOUT = 0x7F0D0178;
|
||||
private static final int PICTURE = 0x7F0A1DAB;
|
||||
/**
|
||||
* The three more picture views that lihont/widget_patch.py puts next to PICTURE inside a ViewFlipper. The
|
||||
* launcher flips through the four by itself, so the flame moves without any code running in the widget.
|
||||
*/
|
||||
private static final int[] FRAME_VIEWS = {0x7F0A1DAC, 0x7F0A1DAD, 0x7F0A1DAE};
|
||||
private static final int BADGE = 0x7F0A881C;
|
||||
private static final int LABEL = 0x7F0A8829;
|
||||
// The resource ids of TikTok's own layout of the small Stories widget come from WidgetIds (found in the build by lihont/widget_patch.py).
|
||||
|
||||
private static final long REFRESH_EVERY_MS = 120000L;
|
||||
private static final int MIN_SIDE_PX = 96;
|
||||
@@ -93,12 +84,13 @@ public class StreakWidget extends AppWidgetProvider {
|
||||
int drawn = burning ? Math.min(side, MAX_ANIMATED_SIDE_PX) : side;
|
||||
Bitmap[] frames = choice == null ? FlowerArt.frames(colors, -1, false, null, drawn, compact)
|
||||
: FlowerArt.frames(colors, choice.streak, fading(choice), choice.name, drawn, compact);
|
||||
RemoteViews views = new RemoteViews(context.getPackageName(), LAYOUT);
|
||||
views.setImageViewBitmap(PICTURE, frames[0]);
|
||||
for (int i = 0; i < FRAME_VIEWS.length; i++) views.setImageViewBitmap(FRAME_VIEWS[i], frames[i + 1]);
|
||||
views.setViewVisibility(BADGE, View.GONE);
|
||||
views.setViewVisibility(LABEL, View.GONE);
|
||||
views.setOnClickPendingIntent(PICTURE, choice == null ? chooser(context, id)
|
||||
WidgetIds ids = WidgetIds.get(context);
|
||||
RemoteViews views = new RemoteViews(context.getPackageName(), ids.layout);
|
||||
views.setImageViewBitmap(ids.picture, frames[0]);
|
||||
for (int i = 0; i < ids.frames.length; i++) views.setImageViewBitmap(ids.frames[i], frames[i + 1]);
|
||||
views.setViewVisibility(ids.badge, View.GONE);
|
||||
views.setViewVisibility(ids.label, View.GONE);
|
||||
views.setOnClickPendingIntent(ids.picture, choice == null ? chooser(context, id)
|
||||
: foreign(choice) ? launcher(context, id) : chat(context, id, choice.uid));
|
||||
manager.updateAppWidget(id, views);
|
||||
} catch (Throwable failure) {
|
||||
@@ -201,8 +193,9 @@ public class StreakWidget extends AppWidgetProvider {
|
||||
|
||||
private static boolean hasLayout(Context context) {
|
||||
try {
|
||||
return "layout".equals(context.getResources().getResourceTypeName(LAYOUT))
|
||||
&& "id".equals(context.getResources().getResourceTypeName(PICTURE));
|
||||
WidgetIds ids = WidgetIds.get(context);
|
||||
return "layout".equals(context.getResources().getResourceTypeName(ids.layout))
|
||||
&& "id".equals(context.getResources().getResourceTypeName(ids.picture));
|
||||
} catch (Throwable missing) {
|
||||
return false;
|
||||
}
|
||||
|
||||
95
src/lihont/two/widget/WidgetIds.java
Normal file
@@ -0,0 +1,95 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
* The resource ids of TikTok's own layout of the small Stories widget (the layout the streak widget draws into): which layout, its picture
|
||||
* view, the three more picture views of the flame, the number tile and its text.
|
||||
*
|
||||
* They differ in every TikTok build, so lihont/widget_patch.py finds them in the build and writes them to assets/lihont_widget_ids.txt;
|
||||
* this class reads that file once. A build made before the file existed (TikTok 47.1.3) has the numbers of 47.1.3 below.
|
||||
*/
|
||||
final class WidgetIds {
|
||||
static final String FILE = "lihont_widget_ids.txt";
|
||||
|
||||
final int layout;
|
||||
final int picture;
|
||||
final int badge;
|
||||
final int label;
|
||||
final int[] frames;
|
||||
|
||||
private static WidgetIds cached;
|
||||
|
||||
WidgetIds(int layout, int picture, int badge, int label, int[] frames) {
|
||||
this.layout = layout;
|
||||
this.picture = picture;
|
||||
this.badge = badge;
|
||||
this.label = label;
|
||||
this.frames = frames;
|
||||
}
|
||||
|
||||
/** The numbers of TikTok 47.1.3. */
|
||||
static WidgetIds builtIn() {
|
||||
return new WidgetIds(0x7F0D0178, 0x7F0A1DAB, 0x7F0A881C, 0x7F0A8829, new int[] {0x7F0A1DAC, 0x7F0A1DAD, 0x7F0A1DAE});
|
||||
}
|
||||
|
||||
static synchronized WidgetIds get(Context context) {
|
||||
if (cached == null) {
|
||||
WidgetIds found = null;
|
||||
try (InputStream in = context.getAssets().open(FILE);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "US-ASCII"))) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) text.append(line).append('\n');
|
||||
found = parse(text.toString());
|
||||
} catch (Throwable absent) {
|
||||
found = null;
|
||||
}
|
||||
cached = found != null ? found : builtIn();
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
/** `name=0xID` lines (frames: ids separated by commas); null when something is missing or malformed. */
|
||||
static WidgetIds parse(String text) {
|
||||
try {
|
||||
int layout = 0;
|
||||
int picture = 0;
|
||||
int badge = 0;
|
||||
int label = 0;
|
||||
int[] frames = null;
|
||||
for (String line : text.split("\n")) {
|
||||
int equals = line.indexOf('=');
|
||||
if (equals < 0) continue;
|
||||
String key = line.substring(0, equals).trim();
|
||||
String value = line.substring(equals + 1).trim();
|
||||
if ("frames".equals(key)) {
|
||||
String[] parts = value.split(",");
|
||||
frames = new int[parts.length];
|
||||
for (int i = 0; i < parts.length; i++) frames[i] = id(parts[i]);
|
||||
} else if ("layout".equals(key)) {
|
||||
layout = id(value);
|
||||
} else if ("picture".equals(key)) {
|
||||
picture = id(value);
|
||||
} else if ("badge".equals(key)) {
|
||||
badge = id(value);
|
||||
} else if ("label".equals(key)) {
|
||||
label = id(value);
|
||||
}
|
||||
}
|
||||
if (layout == 0 || picture == 0 || badge == 0 || label == 0 || frames == null || frames.length != 3) return null;
|
||||
return new WidgetIds(layout, picture, badge, label, frames);
|
||||
} catch (RuntimeException malformed) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int id(String hex) {
|
||||
String digits = hex.startsWith("0x") || hex.startsWith("0X") ? hex.substring(2) : hex;
|
||||
return (int) Long.parseLong(digits, 16);
|
||||
}
|
||||
}
|
||||
BIN
src/web/assets/pets/cat.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
BIN
src/web/assets/pets/dog.png
Normal file
|
After Width: | Height: | Size: 28 KiB |
BIN
src/web/assets/pets/lion.png
Normal file
|
After Width: | Height: | Size: 31 KiB |
BIN
src/web/assets/pets/strips/cat_adult_grey.png
Normal file
|
After Width: | Height: | Size: 59 KiB |
BIN
src/web/assets/pets/strips/cat_adult_lit.png
Normal file
|
After Width: | Height: | Size: 59 KiB |
BIN
src/web/assets/pets/strips/cat_cub_grey.png
Normal file
|
After Width: | Height: | Size: 63 KiB |
BIN
src/web/assets/pets/strips/cat_cub_lit.png
Normal file
|
After Width: | Height: | Size: 64 KiB |
BIN
src/web/assets/pets/strips/cat_elder_grey.png
Normal file
|
After Width: | Height: | Size: 64 KiB |
BIN
src/web/assets/pets/strips/cat_elder_lit.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
src/web/assets/pets/strips/cat_teen_grey.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
src/web/assets/pets/strips/cat_teen_lit.png
Normal file
|
After Width: | Height: | Size: 63 KiB |
BIN
src/web/assets/pets/strips/dog_adult_grey.png
Normal file
|
After Width: | Height: | Size: 50 KiB |
BIN
src/web/assets/pets/strips/dog_adult_lit.png
Normal file
|
After Width: | Height: | Size: 52 KiB |
BIN
src/web/assets/pets/strips/dog_cub_grey.png
Normal file
|
After Width: | Height: | Size: 52 KiB |
BIN
src/web/assets/pets/strips/dog_cub_lit.png
Normal file
|
After Width: | Height: | Size: 54 KiB |
BIN
src/web/assets/pets/strips/dog_elder_grey.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
src/web/assets/pets/strips/dog_elder_lit.png
Normal file
|
After Width: | Height: | Size: 57 KiB |
BIN
src/web/assets/pets/strips/dog_teen_grey.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
src/web/assets/pets/strips/dog_teen_lit.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
src/web/assets/pets/strips/lion_adult_grey.png
Normal file
|
After Width: | Height: | Size: 83 KiB |
BIN
src/web/assets/pets/strips/lion_adult_lit.png
Normal file
|
After Width: | Height: | Size: 82 KiB |
BIN
src/web/assets/pets/strips/lion_cub_grey.png
Normal file
|
After Width: | Height: | Size: 56 KiB |
BIN
src/web/assets/pets/strips/lion_cub_lit.png
Normal file
|
After Width: | Height: | Size: 56 KiB |
BIN
src/web/assets/pets/strips/lion_elder_grey.png
Normal file
|
After Width: | Height: | Size: 87 KiB |
BIN
src/web/assets/pets/strips/lion_elder_lit.png
Normal file
|
After Width: | Height: | Size: 86 KiB |
BIN
src/web/assets/pets/strips/lion_teen_grey.png
Normal file
|
After Width: | Height: | Size: 80 KiB |
BIN
src/web/assets/pets/strips/lion_teen_lit.png
Normal file
|
After Width: | Height: | Size: 80 KiB |
55
src/web/pet_index.html
Normal file
@@ -0,0 +1,55 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>Серийчик в подарок: LihonT</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/logo_single_note.svg">
|
||||
<style>
|
||||
:root { --bg: #fff4e0; --ink: #221c2e; --card: #fff; --muted: #5b5368; --yellow: #ffcd3c; --shadow: #221c2e; }
|
||||
@media (prefers-color-scheme: dark) { :root { --bg: #1c1626; --ink: #f6efe4; --card: #2b2338; --muted: #b9afc9; --shadow: #0b0810; } }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px 16px; background: var(--bg); color: var(--ink); font-family: "Nunito", "Segoe UI", system-ui, -apple-system, Roboto, sans-serif; font-size: 17px; line-height: 1.5; }
|
||||
main { width: min(440px, 100%); text-align: center; display: grid; gap: 16px; justify-items: center; }
|
||||
h1 { margin: 0; font-size: clamp(1.7rem, 7vw, 2.3rem); line-height: 1.1; font-weight: 900; }
|
||||
p { margin: 0; } .muted { color: var(--muted); }
|
||||
img { width: 220px; height: 220px; object-fit: contain; animation: bob 2.4s ease-in-out infinite; filter: drop-shadow(5px 5px 0 var(--shadow)); }
|
||||
@keyframes bob { 50% { transform: translateY(-8px) rotate(-2deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { img { animation: none; } }
|
||||
.btn { display: flex; align-items: center; justify-content: center; width: 100%; min-height: 56px; padding: 10px 22px; border: 3px solid var(--ink); border-radius: 999px; background: var(--card); color: var(--ink); font: inherit; font-weight: 800; text-decoration: none; box-shadow: 5px 5px 0 var(--shadow); }
|
||||
.btn--yellow { background: var(--yellow); color: #221c2e; }
|
||||
.btn:active { transform: translate(4px, 4px); box-shadow: 1px 1px 0 var(--shadow); }
|
||||
[hidden] { display: none !important; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<img id="pic" alt="" width="220" height="220" hidden>
|
||||
<h1 id="title">Серийчик в подарок</h1>
|
||||
<p id="lead" class="muted">Ссылка не подошла: попросите друга прислать её ещё раз.</p>
|
||||
<a id="open" class="btn btn--yellow" href="#" hidden>Открыть в LihonT</a>
|
||||
<a id="get" class="btn" href="https://git.lihont.space/lihont/LihonT/releases" rel="noopener" hidden>У меня нет LihonT: скачать</a>
|
||||
<p id="hint" class="muted" hidden>Нужен TikTok с модом LihonT. Нажмите «Принять» в окошке, и зверь поселится в вашем общем чате.</p>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
var names = { cat: ["котёнка", "cat"], dog: ["щенка", "dog"], lion: ["львёнка", "lion"] };
|
||||
var q = new URLSearchParams(location.search);
|
||||
var kind = q.get("kind"), from = q.get("from");
|
||||
if (!Object.prototype.hasOwnProperty.call(names, kind) || !/^[0-9]{6,24}$/.test(from || "")) return;
|
||||
var pic = document.getElementById("pic");
|
||||
pic.src = "/assets/pets/" + kind + ".png"; pic.hidden = false;
|
||||
document.getElementById("title").textContent = "Вам дарят " + names[kind][0];
|
||||
document.getElementById("lead").textContent = "Он будет жить в вашем общем чате в TikTok и расти вместе с серией.";
|
||||
var open = document.getElementById("open");
|
||||
open.href = "lihont://pet?kind=" + kind + "&from=" + from;
|
||||
open.hidden = false;
|
||||
document.getElementById("get").hidden = false;
|
||||
document.getElementById("hint").hidden = false;
|
||||
if (/Android/i.test(navigator.userAgent)) setTimeout(function () { location.href = open.href; }, 400);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
23
tests/java/lihont/two/widget/WidgetIdsTest.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
/** Reads the ids file of lihont/widget_patch.py the way the widget does. Usage: WidgetIdsTest "<file text with \n written as |>"; prints the ids. */
|
||||
public final class WidgetIdsTest {
|
||||
private WidgetIdsTest() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length == 0) {
|
||||
WidgetIds ids = WidgetIds.builtIn();
|
||||
System.out.println(line(ids));
|
||||
return;
|
||||
}
|
||||
WidgetIds ids = WidgetIds.parse(args[0].replace("|", "\n"));
|
||||
System.out.println(ids == null ? "NULL" : line(ids));
|
||||
}
|
||||
|
||||
private static String line(WidgetIds ids) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append(String.format("layout=0x%08X picture=0x%08X badge=0x%08X label=0x%08X frames=", ids.layout, ids.picture, ids.badge, ids.label));
|
||||
for (int i = 0; i < ids.frames.length; i++) out.append(i == 0 ? "" : ",").append(String.format("0x%08X", ids.frames[i]));
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
305
tests/test_accounts.py
Normal file
@@ -0,0 +1,305 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import time as real_time
|
||||
import importlib.util
|
||||
import io
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] / "services" / "members"
|
||||
SPEC = importlib.util.spec_from_file_location("members_server", ROOT / "server.py")
|
||||
server = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(server)
|
||||
|
||||
import authbot # noqa: E402 (server.py put the folder on sys.path)
|
||||
|
||||
ALICE, BOB = "6812345678901234", "6899999999999999"
|
||||
INST_A, INST_B = "a" * 64, "b" * 64
|
||||
OWNER = 777
|
||||
|
||||
|
||||
def sha(value):
|
||||
return hashlib.sha256(value.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
def picture(shade):
|
||||
out = io.BytesIO()
|
||||
Image.new("RGBA", (120, 80), (shade, 40, 90, 255)).save(out, "PNG")
|
||||
return base64.b64encode(out.getvalue()).decode("ascii")
|
||||
|
||||
|
||||
class FakeTelegram:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
self.fail = {}
|
||||
|
||||
def call(self, method, fields=None, files=None, timeout=40):
|
||||
if method == "sendMessage":
|
||||
if fields["chat_id"] in self.fail:
|
||||
raise RuntimeError(self.fail[fields["chat_id"]])
|
||||
self.sent.append((fields["chat_id"], fields["text"]))
|
||||
return []
|
||||
|
||||
|
||||
class AccountsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.now = int(real_time.time()) # the bans of TikTok accounts are judged by the database clock, so the test clock starts now
|
||||
self.who = ALICE
|
||||
self.inst = INST_A
|
||||
self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now,
|
||||
fetcher=lambda unique_id: (self.who, self.registry.code(self.who, sha(self.inst))))
|
||||
self.acc = self.registry.accounts
|
||||
self.telegram = FakeTelegram()
|
||||
self.bot = authbot.AuthBot(self.registry, self.telegram, OWNER, clock=lambda: self.now)
|
||||
|
||||
# -- helpers --
|
||||
def sign_in(self, tg_id, installation, handle):
|
||||
token = self.acc.call("tg_start", {"installation": installation})["token"]
|
||||
self.assertTrue(self.acc.bot_link(token, tg_id)["ok"])
|
||||
reply = self.acc.call("tg_poll", {"installation": installation, "token": token})
|
||||
self.assertEqual("linked", reply["status"])
|
||||
self.acc.call("tg_register", {"installation": installation, "handle": handle})
|
||||
|
||||
def prove(self, uid, installation):
|
||||
self.who, self.inst = uid, installation
|
||||
self.assertTrue(self.registry.shape(uid, installation, "flower", "someone")["published"])
|
||||
|
||||
def publish_approved(self, uid, installation, name="Венок", shade=10):
|
||||
self.who, self.inst = uid, installation
|
||||
art = self.registry.catalog.call("publish", {"uid": uid, "installation": installation, "unique_id": "someone", "kind": "frame",
|
||||
"name": name, "description": "", "png": picture(shade)})["id"]
|
||||
self.registry.art_decide(art, "approved")
|
||||
return art
|
||||
|
||||
# -- signing in --
|
||||
def test_the_link_belongs_to_the_installation_that_asked_and_works_once(self):
|
||||
start = self.acc.call("tg_start", {"installation": INST_A})
|
||||
self.assertTrue(start["link"].startswith("https://t.me/lihonTauthbot?start="))
|
||||
token = start["token"]
|
||||
self.assertEqual("waiting", self.acc.call("tg_poll", {"installation": INST_A, "token": token})["status"])
|
||||
self.assertEqual("expired", self.acc.call("tg_poll", {"installation": INST_B, "token": token})["status"]) # another phone learns nothing
|
||||
self.assertTrue(self.acc.bot_link(token, 111)["ok"])
|
||||
reply = self.acc.call("tg_poll", {"installation": INST_A, "token": token})
|
||||
self.assertEqual(("linked", False), (reply["status"], reply["registered"]))
|
||||
self.assertFalse(self.acc.bot_link(token, 222)["ok"]) # the token is spent: a second person cannot take the session
|
||||
|
||||
def test_a_link_runs_out(self):
|
||||
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
|
||||
self.now += 901
|
||||
self.assertEqual("expired", self.acc.bot_link(token, 111)["reason"])
|
||||
|
||||
def test_open_links_are_limited(self):
|
||||
for _ in range(5):
|
||||
self.acc.call("tg_start", {"installation": INST_A})
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.call("tg_start", {"installation": INST_A})
|
||||
|
||||
def test_nicknames(self):
|
||||
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
|
||||
self.acc.bot_link(token, 111)
|
||||
self.acc.call("tg_poll", {"installation": INST_A, "token": token})
|
||||
for bad in ("ab", "x" * 21, "Привет", "has space", "admin", "lihont_official", "moderator1", "root"):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
self.acc.call("tg_register", {"installation": INST_A, "handle": bad})
|
||||
self.assertEqual("masha", self.acc.call("tg_register", {"installation": INST_A, "handle": "@Masha"})["handle"])
|
||||
self.sign_in(222, INST_B, "vova")
|
||||
with self.assertRaises(ValueError): # taken, whatever the case
|
||||
self.acc.call("tg_register", {"installation": INST_B, "handle": "MASHA"})
|
||||
with self.assertRaises(ValueError): # only once in 30 days
|
||||
self.acc.call("tg_register", {"installation": INST_A, "handle": "masha2"})
|
||||
self.now += 31 * 86400
|
||||
self.assertEqual("masha2", self.acc.call("tg_register", {"installation": INST_A, "handle": "masha2"})["handle"])
|
||||
|
||||
def test_member_calls_need_a_session_and_a_nickname(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.call("following", {"installation": INST_A})
|
||||
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
|
||||
self.acc.bot_link(token, 111)
|
||||
self.acc.call("tg_poll", {"installation": INST_A, "token": token})
|
||||
with self.assertRaises(ValueError): # signed in, no nickname yet
|
||||
self.acc.call("following", {"installation": INST_A})
|
||||
|
||||
# -- the author level --
|
||||
def test_the_tiktok_link_needs_this_installations_proof(self):
|
||||
self.sign_in(111, INST_A, "alice")
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
|
||||
self.prove(ALICE, INST_A)
|
||||
self.assertEqual(ALICE, self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})["uid"])
|
||||
self.assertEqual("author", self.acc.call("tg_me", {"installation": INST_A})["level"])
|
||||
self.sign_in(222, INST_B, "mallory")
|
||||
with self.assertRaises(ValueError): # someone else's proven account is not theirs
|
||||
self.acc.call("tg_link_tiktok", {"installation": INST_B, "uid": ALICE})
|
||||
|
||||
# -- follows and the inbox --
|
||||
def test_follow_counts_lists_and_limits(self):
|
||||
self.sign_in(111, INST_A, "alice")
|
||||
self.prove(ALICE, INST_A)
|
||||
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
|
||||
self.publish_approved(ALICE, INST_A)
|
||||
self.sign_in(222, INST_B, "bob")
|
||||
with self.assertRaises(ValueError): # nobody by that number
|
||||
self.acc.call("follow", {"installation": INST_B, "uid": "6877777777777777"})
|
||||
self.assertEqual(1, self.acc.call("follow", {"installation": INST_B, "uid": ALICE})["followers"])
|
||||
self.assertEqual(1, self.acc.call("follow", {"installation": INST_B, "uid": ALICE})["followers"]) # twice is once
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.call("follow", {"installation": INST_A, "uid": ALICE}) # not oneself
|
||||
self.assertEqual({"followers": 1, "following": True}, self.acc.call("follow_info", {"uid": ALICE, "installation": INST_B}))
|
||||
self.assertEqual({"followers": 1}, self.acc.call("follow_info", {"uid": ALICE})) # the public sees a number and no names
|
||||
self.assertEqual(["bob"], [i["handle"] for i in self.acc.call("followers", {"installation": INST_A})["items"]]) # the owner sees names
|
||||
self.assertEqual([ALICE], [i["uid"] for i in self.acc.call("following", {"installation": INST_B})["items"]])
|
||||
self.assertEqual({"items": [], "count": 0}, self.acc.call("followers", {"installation": INST_B})) # bob has no followers to show
|
||||
self.assertEqual(0, self.acc.call("unfollow", {"installation": INST_B, "uid": ALICE})["followers"])
|
||||
|
||||
def test_the_inbox_holds_only_followed_approved_work_and_counts_the_unread(self):
|
||||
self.sign_in(222, INST_B, "bob")
|
||||
first = self.publish_approved(ALICE, INST_A, "Первая", 10)
|
||||
self.acc.call("follow", {"installation": INST_B, "uid": ALICE})
|
||||
self.publish_approved(BOB, INST_B, "Чужая", 20) # not followed
|
||||
self.who, self.inst = ALICE, INST_A
|
||||
self.registry.catalog.call("publish", {"uid": ALICE, "installation": INST_A, "unique_id": "someone", "kind": "frame",
|
||||
"name": "Не принята", "description": "", "png": picture(30)}) # not approved
|
||||
box = self.acc.call("inbox", {"installation": INST_B})
|
||||
self.assertEqual([first], [i["id"] for i in box["items"]])
|
||||
self.assertEqual(1, box["unread"])
|
||||
self.now += 10
|
||||
self.acc.call("inbox_seen", {"installation": INST_B})
|
||||
self.now += 10
|
||||
self.assertEqual(0, self.acc.call("inbox", {"installation": INST_B})["unread"])
|
||||
self.publish_approved(ALICE, INST_A, "Новая", 40)
|
||||
self.assertEqual(1, self.acc.call("inbox", {"installation": INST_B})["unread"])
|
||||
|
||||
def test_follow_limit(self):
|
||||
self.sign_in(222, INST_B, "bob")
|
||||
self.acc.FOLLOW_LIMIT = 1
|
||||
import accounts as module
|
||||
saved, module.FOLLOW_LIMIT = module.FOLLOW_LIMIT, 1
|
||||
self.addCleanup(setattr, module, "FOLLOW_LIMIT", saved)
|
||||
self.publish_approved(ALICE, INST_A)
|
||||
self.publish_approved(BOB, INST_B, "Другая", 50)
|
||||
self.acc.call("follow", {"installation": INST_B, "uid": ALICE})
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.call("follow", {"installation": INST_B, "uid": BOB})
|
||||
|
||||
# -- hidden ids and bans --
|
||||
def test_hidden_ids_are_stable_and_join_when_the_accounts_are_linked(self):
|
||||
self.sign_in(111, INST_A, "alice")
|
||||
tg_pid = self.acc.pid_for_tg(111)
|
||||
uid_pid = self.acc.pid_for_uid(ALICE) # an author is known by number first
|
||||
self.assertNotEqual(tg_pid, uid_pid)
|
||||
self.assertEqual(uid_pid, self.acc.pid_for_uid(ALICE))
|
||||
self.assertRegex(uid_pid, r"\A[A-Z2-9]{3}-[A-Z2-9]{3}\Z")
|
||||
self.prove(ALICE, INST_A)
|
||||
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
|
||||
self.assertEqual(uid_pid, self.acc.pid_for_uid(ALICE)) # the id the owner already knows stays
|
||||
|
||||
def test_a_ban_closes_both_accounts_for_the_days_and_then_runs_out(self):
|
||||
self.sign_in(111, INST_A, "alice")
|
||||
self.prove(ALICE, INST_A)
|
||||
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
|
||||
art = self.publish_approved(ALICE, INST_A)
|
||||
pid = self.acc.pid_for_uid(ALICE)
|
||||
result = self.acc.ban(pid, 7, "spam")
|
||||
self.assertEqual((True, True), (result["tg"], result["tiktok"]))
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.call("tg_me", {"installation": INST_A}) # the session is gone
|
||||
self.assertEqual([], self.registry.catalog.call("catalog", {})["items"]) # the work is hidden
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.catalog.call("unpublish", {"uid": ALICE, "installation": INST_A, "id": art}) # no rights on the TikTok side
|
||||
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
|
||||
self.assertEqual("banned", self.acc.bot_link(token, 111)["reason"])
|
||||
self.assertTrue(self.acc.who(pid)["banned"])
|
||||
self.acc.unban(pid)
|
||||
self.assertFalse(self.acc.who(pid)["banned"])
|
||||
self.assertTrue(self.acc.bot_link(token, 111)["ok"])
|
||||
|
||||
def test_a_timed_ban_of_a_tiktok_account_ends_by_itself(self):
|
||||
self.publish_approved(ALICE, INST_A)
|
||||
pid = self.acc.pid_for_uid(ALICE)
|
||||
with self.registry.connect() as db:
|
||||
db.execute("INSERT INTO blocked(uid, until) VALUES(?, ?) ON CONFLICT(uid) DO UPDATE SET until=excluded.until",
|
||||
(ALICE, int(real_time.time()) + 3600))
|
||||
self.assertEqual([], self.registry.catalog.call("catalog", {})["items"])
|
||||
with self.registry.connect() as db:
|
||||
db.execute("UPDATE blocked SET until=? WHERE uid=?", (int(real_time.time()) - 5, ALICE))
|
||||
self.assertEqual(1, len(self.registry.catalog.call("catalog", {})["items"]))
|
||||
self.assertTrue(pid)
|
||||
|
||||
def test_ban_input_is_checked(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.ban("nonsense", 1)
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.ban("AAA-AAA", 1) # unknown
|
||||
pid = self.acc.pid_for_uid(ALICE)
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.ban(pid, -1)
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.ban(pid, 100000)
|
||||
|
||||
# -- the bot --
|
||||
def say(self, user_id, text, chat_type="private"):
|
||||
self.bot.handle({"message": {"from": {"id": user_id}, "chat": {"id": user_id, "type": chat_type}, "text": text}})
|
||||
|
||||
def test_the_bot_links_a_person_and_explains_a_stale_link(self):
|
||||
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
|
||||
self.say(111, "/start " + token)
|
||||
self.assertIn("выберите себе ник", self.telegram.sent[-1][1])
|
||||
self.say(222, "/start " + token) # a copy of the link in other hands
|
||||
self.assertIn("устарела", self.telegram.sent[-1][1])
|
||||
|
||||
def test_only_the_owner_bans_and_only_in_a_private_chat(self):
|
||||
pid = self.acc.pid_for_uid(ALICE)
|
||||
self.say(555, "/ban %s 3" % pid)
|
||||
self.assertFalse(self.acc.who(pid)["banned"]) # a stranger gets the help text and nothing happens
|
||||
self.say(OWNER, "/ban %s 3" % pid, chat_type="group")
|
||||
self.assertFalse(self.acc.who(pid)["banned"])
|
||||
self.say(OWNER, "/ban %s 3 плохая картинка" % pid)
|
||||
self.assertTrue(self.acc.who(pid)["banned"])
|
||||
self.assertIn("Забанен", self.telegram.sent[-1][1])
|
||||
self.say(OWNER, "/who " + pid)
|
||||
self.assertIn("Бан: да", self.telegram.sent[-1][1])
|
||||
self.say(OWNER, "/unban " + pid)
|
||||
self.assertFalse(self.acc.who(pid)["banned"])
|
||||
self.say(OWNER, "/ban nonsense 3")
|
||||
self.assertIn("Не получилось", self.telegram.sent[-1][1])
|
||||
|
||||
def test_delete_needs_a_second_message_and_removes_the_follows(self):
|
||||
self.sign_in(222, INST_B, "bob")
|
||||
self.publish_approved(ALICE, INST_A)
|
||||
self.acc.call("follow", {"installation": INST_B, "uid": ALICE})
|
||||
self.say(222, "/delete yes") # not asked first
|
||||
self.assertEqual(1, self.acc.call("follow_info", {"uid": ALICE})["followers"])
|
||||
self.say(222, "/delete")
|
||||
self.say(222, "/delete yes")
|
||||
self.assertEqual(0, self.acc.call("follow_info", {"uid": ALICE})["followers"])
|
||||
with self.assertRaises(ValueError):
|
||||
self.acc.call("tg_me", {"installation": INST_B})
|
||||
|
||||
def test_notifications_go_to_followers_who_want_them_and_a_blocked_bot_is_muted(self):
|
||||
self.sign_in(111, INST_A, "alice")
|
||||
self.prove(ALICE, INST_A)
|
||||
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
|
||||
art = self.publish_approved(ALICE, INST_A, "Венок")
|
||||
self.sign_in(222, INST_B, "bob")
|
||||
self.sign_in(333, "c" * 64, "carol")
|
||||
self.sign_in(444, "d" * 64, "dave")
|
||||
for inst in (INST_B, "c" * 64, "d" * 64):
|
||||
self.acc.call("follow", {"installation": inst, "uid": ALICE})
|
||||
self.acc.call("tg_notify", {"installation": "c" * 64, "on": False})
|
||||
self.telegram.fail[444] = "Forbidden: bot was blocked by the user"
|
||||
sent = self.bot.notify_new(self.registry.art(art))
|
||||
self.assertEqual(1, sent)
|
||||
self.assertEqual([222], [chat for chat, _ in self.telegram.sent if "Венок" in _])
|
||||
self.assertIn("@alice", self.telegram.sent[-1][1])
|
||||
self.assertEqual([], self.acc.followers_to_notify(ALICE, 10)[1:]) # dave is muted now: only bob is left
|
||||
self.say(222, "/stop")
|
||||
self.assertEqual([], self.acc.followers_to_notify(ALICE))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,5 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import tempfile
|
||||
@@ -18,6 +19,10 @@ INSTALL_A = "a" * 64
|
||||
INSTALL_B = "b" * 64
|
||||
|
||||
|
||||
def sha(installation):
|
||||
return hashlib.sha256(installation.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
def picture(shade, size=(120, 80)):
|
||||
out = io.BytesIO()
|
||||
Image.new("RGBA", size, (shade, 40, 90, 255)).save(out, "PNG")
|
||||
@@ -29,13 +34,13 @@ class CatalogTest(unittest.TestCase):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.now = 1_790_000_000
|
||||
self.who = UID
|
||||
self.who, self.inst = UID, INSTALL_A
|
||||
self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now,
|
||||
fetcher=lambda unique_id: (self.who, self.registry.code(self.who)))
|
||||
fetcher=lambda unique_id: (self.who, self.registry.code(self.who, sha(self.inst))))
|
||||
self.cat = self.registry.catalog
|
||||
|
||||
def publish(self, kind="frame", shade=10, name="Венок", description="Из веток", uid=UID, installation=INSTALL_A):
|
||||
self.who = uid
|
||||
self.who, self.inst = uid, installation
|
||||
return self.cat.call("publish", {"uid": uid, "installation": installation, "unique_id": "someone", "kind": kind,
|
||||
"name": name, "description": description, "png": picture(shade)})
|
||||
|
||||
@@ -57,7 +62,7 @@ class CatalogTest(unittest.TestCase):
|
||||
|
||||
def test_the_picture_is_remade_by_kind(self):
|
||||
frame = self.registry.art_bytes(self.publish("frame", 1)["id"], approved_only=False)
|
||||
self.who = UID
|
||||
self.who, self.inst = UID, INSTALL_A
|
||||
wide = self.cat.call("publish", {"uid": UID, "installation": INSTALL_A, "unique_id": "someone", "kind": "bubble",
|
||||
"name": "B", "png": picture(2, (1024, 683))})
|
||||
bubble = self.registry.art_bytes(wide["id"], approved_only=False)
|
||||
@@ -127,10 +132,25 @@ class CatalogTest(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
self.cat.call("mine", {"uid": OTHER, "installation": INSTALL_A})
|
||||
|
||||
def test_the_report_of_a_rejection_goes_to_its_author_only(self):
|
||||
art = self.publish()["id"]
|
||||
with self.assertRaises(ValueError): # not rejected, no report
|
||||
self.cat.call("report", {"uid": UID, "installation": INSTALL_A, "id": art})
|
||||
self.registry.art_decide(art, "rejected", "ai: плохо")
|
||||
self.registry.art_report_save(art, b"%PDF-test")
|
||||
reply = self.cat.call("report", {"uid": UID, "installation": INSTALL_A, "id": art})
|
||||
self.assertEqual(b"%PDF-test", base64.b64decode(reply["pdf"]))
|
||||
with self.assertRaises(ValueError): # another installation of the same account is not the author
|
||||
self.cat.call("report", {"uid": UID, "installation": INSTALL_B, "id": art})
|
||||
self.who, self.inst = OTHER, INSTALL_B
|
||||
self.registry.shape(OTHER, INSTALL_B, "flower", "peer")
|
||||
with self.assertRaises(ValueError):
|
||||
self.cat.call("report", {"uid": OTHER, "installation": INSTALL_B, "id": art})
|
||||
|
||||
def test_unpublish_is_the_authors_alone(self):
|
||||
art = self.publish()["id"]
|
||||
self.approve(art)
|
||||
self.who = OTHER
|
||||
self.who, self.inst = OTHER, INSTALL_B
|
||||
self.registry.shape(OTHER, INSTALL_B, "flower", "peer")
|
||||
with self.assertRaises(ValueError):
|
||||
self.cat.call("unpublish", {"uid": OTHER, "installation": INSTALL_B, "id": art})
|
||||
@@ -148,7 +168,7 @@ class CatalogTest(unittest.TestCase):
|
||||
private = self.registry.frame_upload(UID, INSTALL_A, "someone", "Своя", picture(33))
|
||||
art = private["id"][2:]
|
||||
self.approve(art)
|
||||
self.who = UID
|
||||
self.who, self.inst = UID, INSTALL_A
|
||||
again = self.cat.call("publish", {"uid": UID, "installation": INSTALL_A, "kind": "frame", "name": "Новое",
|
||||
"description": "d", "png": picture(33)})
|
||||
self.assertEqual(art, again["id"])
|
||||
@@ -156,14 +176,14 @@ class CatalogTest(unittest.TestCase):
|
||||
self.assertEqual([], self.listing()["items"])
|
||||
|
||||
def test_bad_publish_requests(self):
|
||||
self.who = UID
|
||||
self.who, self.inst = UID, INSTALL_A
|
||||
for payload in ({"kind": "sticker"}, {"kind": "frame", "png": "###"}, {"kind": "frame", "uid": "1"}):
|
||||
with self.assertRaises(ValueError):
|
||||
self.cat.call("publish", dict({"uid": UID, "installation": INSTALL_A, "unique_id": "someone", "name": "x"}, **payload))
|
||||
|
||||
def test_anyone_may_wear_a_catalog_frame_but_not_a_pending_one(self):
|
||||
art = self.publish("frame", 3)["id"]
|
||||
self.who = OTHER
|
||||
self.who, self.inst = OTHER, INSTALL_B
|
||||
self.registry.shape(OTHER, INSTALL_B, "flower", "peer")
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.avatar_frame(OTHER, INSTALL_B, "u." + art)
|
||||
@@ -177,7 +197,7 @@ class CatalogTest(unittest.TestCase):
|
||||
self.assertEqual({}, self.registry.lookup([UID])["bubbles"])
|
||||
self.approve(art)
|
||||
self.assertEqual({UID: art}, self.registry.lookup([UID, OTHER])["bubbles"])
|
||||
self.who = OTHER
|
||||
self.who, self.inst = OTHER, INSTALL_B
|
||||
self.registry.shape(OTHER, INSTALL_B, "flower", "peer")
|
||||
self.assertTrue(self.cat.call("bubble_choose", {"uid": OTHER, "installation": INSTALL_B, "id": art})["published"])
|
||||
self.assertEqual({UID: art, OTHER: art}, self.registry.lookup([UID, OTHER])["bubbles"])
|
||||
@@ -201,10 +221,10 @@ class LibraryTest(unittest.TestCase):
|
||||
approve = CatalogTest.approve
|
||||
|
||||
def test_prove_binds_an_installation_once(self):
|
||||
self.who = UID
|
||||
self.who, self.inst = UID, INSTALL_A
|
||||
self.registry.fetcher = lambda unique_id: (UID, "")
|
||||
self.assertEqual("code_missing", self.cat.call("prove", {"uid": UID, "installation": INSTALL_A, "unique_id": "someone"})["reason"])
|
||||
self.registry.fetcher = lambda unique_id: (UID, self.registry.code(UID))
|
||||
self.registry.fetcher = lambda unique_id: (UID, self.registry.code(UID, sha(INSTALL_A)))
|
||||
self.assertTrue(self.cat.call("prove", {"uid": UID, "installation": INSTALL_A, "unique_id": "someone"})["published"])
|
||||
self.registry.fetcher = lambda unique_id: (_ for _ in ()).throw(AssertionError("the profile is read only once"))
|
||||
self.assertTrue(self.cat.call("prove", {"uid": UID, "installation": INSTALL_A})["published"])
|
||||
@@ -212,8 +232,8 @@ class LibraryTest(unittest.TestCase):
|
||||
def test_add_list_remove(self):
|
||||
art = self.publish("frame", 12)["id"]
|
||||
self.approve(art)
|
||||
self.who = OTHER
|
||||
self.registry.fetcher = lambda unique_id: (OTHER, self.registry.code(OTHER))
|
||||
self.who, self.inst = OTHER, INSTALL_B
|
||||
self.registry.fetcher = lambda unique_id: (OTHER, self.registry.code(OTHER, sha(INSTALL_B)))
|
||||
self.cat.call("prove", {"uid": OTHER, "installation": INSTALL_B, "unique_id": "peer"})
|
||||
self.assertEqual({"items": []}, self.cat.call("library", {"uid": OTHER, "installation": INSTALL_B}))
|
||||
self.assertEqual(1, self.cat.call("library_add", {"uid": OTHER, "installation": INSTALL_B, "id": art})["installs"])
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import base64
|
||||
import importlib.util
|
||||
import hashlib
|
||||
import io
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -23,6 +24,10 @@ def picture(width=300, height=200, color=(200, 30, 30, 255), fmt="PNG"):
|
||||
Image.new("RGBA" if fmt == "PNG" else "RGB", (width, height), color if fmt == "PNG" else color[:3]).save(out, fmt)
|
||||
return out.getvalue()
|
||||
|
||||
def bound(registry, uid):
|
||||
"""The proof code of an account for the installation the tests use for it (the first account uses "a"*64, the other "b"*64)."""
|
||||
return registry.code(uid, hashlib.sha256((INSTALLATION if uid == UID else "b" * 64).encode("ascii")).hexdigest())
|
||||
|
||||
|
||||
def encoded(data):
|
||||
return base64.b64encode(data).decode("ascii")
|
||||
@@ -80,7 +85,7 @@ class UploadTest(unittest.TestCase):
|
||||
return self.registry.frame_upload(uid, installation, "someone", name, encoded(data or picture()))
|
||||
|
||||
def prove(self):
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = bound(self.registry, UID)
|
||||
|
||||
def test_needs_the_code_in_the_bio_first(self):
|
||||
self.assertEqual("code_missing", self.upload()["reason"])
|
||||
@@ -122,7 +127,7 @@ class UploadTest(unittest.TestCase):
|
||||
self.registry.art_decide(frame[2:], "approved")
|
||||
self.registry.avatar_frame(UID, INSTALLATION, "none")
|
||||
other = "b" * 64
|
||||
self.registry.fetcher = lambda unique_id: (OTHER, self.registry.code(OTHER))
|
||||
self.registry.fetcher = lambda unique_id: (OTHER, bound(self.registry, OTHER))
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.avatar_frame(OTHER, other, frame, "someone")
|
||||
with self.assertRaises(ValueError):
|
||||
@@ -134,7 +139,7 @@ class UploadTest(unittest.TestCase):
|
||||
again = self.upload()
|
||||
self.assertEqual(first["id"], again["id"])
|
||||
self.assertEqual({"new": 1}, self.registry.art_counts())
|
||||
self.registry.fetcher = lambda unique_id: (OTHER, self.registry.code(OTHER))
|
||||
self.registry.fetcher = lambda unique_id: (OTHER, bound(self.registry, OTHER))
|
||||
with self.assertRaises(ValueError):
|
||||
self.upload(uid=OTHER, installation="b" * 64)
|
||||
|
||||
@@ -170,7 +175,7 @@ class ChatPictureTest(unittest.TestCase):
|
||||
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,
|
||||
fetcher=lambda unique_id: (self.who, self.registry.code(self.who)))
|
||||
fetcher=lambda unique_id: (self.who, bound(self.registry, self.who)))
|
||||
self.who = UID
|
||||
self.peer_install = "b" * 64
|
||||
|
||||
|
||||
34
tests/test_dead_slots.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from lihont import app_icons, dead_slots
|
||||
from lihont.apkzip import Apk
|
||||
from lihont.arsc import Arsc
|
||||
|
||||
BASE = Path("OriginalAPKtiktok/com.zhiliaoapp.musically_47.1.3-2024701030_minAPI23(arm64-v8a)(nodpi)_apkmirror.com.apk")
|
||||
|
||||
|
||||
class DeadSlotsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not BASE.exists():
|
||||
raise unittest.SkipTest("clean TikTok base APK is not available")
|
||||
cls.apk = Apk(str(BASE))
|
||||
cls.arsc = Arsc(cls.apk.read("resources.arsc"))
|
||||
cls.addClassCleanup(cls.apk.close)
|
||||
|
||||
def test_the_slots_pinned_by_hand_are_found_by_the_build_itself(self):
|
||||
found = {res_id for res_id, _ in dead_slots.find(self.apk, self.arsc, 500)}
|
||||
for res_id, path in app_icons.SLOTS:
|
||||
self.assertIn(res_id, found, hex(res_id))
|
||||
|
||||
def test_every_slot_is_a_file_of_the_apk_and_the_order_is_by_id(self):
|
||||
slots = dead_slots.find(self.apk, self.arsc, 8)
|
||||
self.assertEqual(8, len(slots))
|
||||
self.assertEqual(sorted(slots), slots)
|
||||
for _, path in slots:
|
||||
self.assertTrue(self.apk.has(path), path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -137,8 +137,8 @@ class StoryViewTest(unittest.TestCase):
|
||||
def test_another_shape_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_story_view(SAMPLE.replace("reportStoryViewed", "reportSomething"))
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_story_view(SAMPLE.replace(".registers 8", ".registers 9"))
|
||||
# the register count differs between TikTok builds (8 in 47.1.3, 7 in 47.7.2): it is not part of the shape
|
||||
self.assertIn("Ghost;", ghost_patch.rewrite_story_view(SAMPLE.replace(".registers 8", ".registers 9")))
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_story_view(SAMPLE.replace("if-eqz p1, :cond_3c", "if-nez p1, :cond_3c"))
|
||||
with self.assertRaises(ValueError):
|
||||
|
||||
@@ -44,6 +44,21 @@ class ManifestActivityTest(unittest.TestCase):
|
||||
self.assertNotEqual(0, reparsed.attr(node, 'exported').data)
|
||||
self.assertEqual(0x01030055, reparsed.attr(node, 'theme').data)
|
||||
|
||||
def test_the_gift_activity_opens_the_pet_links(self):
|
||||
xml = self._manifest()
|
||||
name = 'lihont.two.pet.GiftActivity'
|
||||
add_activity(xml, name, 'LihonT', 0x7F120364, exported=True,
|
||||
links=(('https', 'lihont.space', '/pet'), ('lihont', 'pet', None)))
|
||||
reparsed = Axml.parse(xml.build())
|
||||
self.assertTrue(has_activity(reparsed, name))
|
||||
schemes = [reparsed.attr_string(n, 'scheme') for n in reparsed.elements('data')]
|
||||
self.assertIn('https', schemes)
|
||||
self.assertIn('lihont', schemes)
|
||||
prefixes = [reparsed.attr_string(n, 'pathPrefix') for n in reparsed.elements('data')]
|
||||
self.assertIn('/pet', prefixes)
|
||||
views = [reparsed.attr_string(n, 'name') for n in reparsed.elements('action')]
|
||||
self.assertIn('android.intent.action.VIEW', views)
|
||||
|
||||
def test_launcher_activity_must_explicitly_be_exported(self):
|
||||
xml = self._manifest()
|
||||
with self.assertRaises(ManifestError):
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -10,6 +11,10 @@ SPEC.loader.exec_module(server)
|
||||
UID = "6812345678901234"
|
||||
|
||||
|
||||
def sha(installation):
|
||||
return hashlib.sha256(installation.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
class ClaimTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
@@ -96,12 +101,12 @@ class ShapeTest(unittest.TestCase):
|
||||
self.assertEqual("proof_needed", self.registry.shape(UID, INSTALLATION, "flower")["reason"])
|
||||
|
||||
def test_the_code_in_the_bio_publishes_the_shape(self):
|
||||
self.bio = "me " + self.registry.code(UID)
|
||||
self.bio = "me " + self.registry.code(UID, sha(INSTALLATION))
|
||||
self.assertTrue(self.publish("flower")["published"])
|
||||
self.assertEqual({UID: "flower"}, self.registry.lookup([UID])["shapes"])
|
||||
|
||||
def test_the_proven_installation_changes_it_without_another_proof(self):
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(INSTALLATION))
|
||||
self.publish("flower")
|
||||
fetched = self.fetches
|
||||
self.bio = ""
|
||||
@@ -110,20 +115,39 @@ class ShapeTest(unittest.TestCase):
|
||||
self.assertEqual({UID: "heart"}, self.registry.lookup([UID])["shapes"])
|
||||
|
||||
def test_another_installation_must_prove_the_account_itself(self):
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(INSTALLATION))
|
||||
self.publish("flower")
|
||||
self.bio = ""
|
||||
self.assertFalse(self.publish("hexagon", OTHER_INSTALLATION)["published"])
|
||||
self.assertEqual({UID: "flower"}, self.registry.lookup([UID])["shapes"])
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(OTHER_INSTALLATION))
|
||||
self.assertTrue(self.publish("hexagon", OTHER_INSTALLATION)["published"])
|
||||
self.assertEqual({UID: "hexagon"}, self.registry.lookup([UID])["shapes"])
|
||||
# the first installation lost its right with that
|
||||
self.bio = ""
|
||||
self.assertFalse(self.publish("heart", INSTALLATION)["published"])
|
||||
|
||||
def test_a_code_left_in_the_bio_cannot_be_replayed_by_another_installation(self):
|
||||
self.bio = "me " + self.registry.code(UID, sha(INSTALLATION)) # the owner's code stays visible in the public bio
|
||||
self.assertTrue(self.publish("flower")["published"])
|
||||
reply = self.publish("hexagon", OTHER_INSTALLATION) # an attacker names the owner's account and profile
|
||||
self.assertFalse(reply["published"])
|
||||
self.assertEqual("code_missing", reply["reason"])
|
||||
self.assertNotEqual(reply["code"], self.registry.code(UID, sha(INSTALLATION)))
|
||||
self.assertEqual({UID: "flower"}, self.registry.lookup([UID])["shapes"])
|
||||
|
||||
def test_the_profile_reads_are_limited_so_the_server_is_not_a_bot(self):
|
||||
self.bio = ""
|
||||
self.registry.FETCH_PER_HOUR = 3
|
||||
for _ in range(3):
|
||||
self.publish("flower")
|
||||
with self.assertRaises(ValueError):
|
||||
self.publish("flower")
|
||||
self.now += 3601
|
||||
self.publish("flower")
|
||||
|
||||
def test_circle_withdraws_the_shape(self):
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(INSTALLATION))
|
||||
self.publish("triangle")
|
||||
self.assertTrue(self.registry.shape(UID, INSTALLATION, "circle")["published"])
|
||||
self.assertEqual({}, self.registry.lookup([UID])["shapes"])
|
||||
@@ -134,7 +158,7 @@ class ShapeTest(unittest.TestCase):
|
||||
|
||||
def test_someone_elses_profile_and_blocked_accounts_are_refused(self):
|
||||
self.found = "999999999"
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(INSTALLATION))
|
||||
with self.assertRaises(ValueError):
|
||||
self.publish("flower")
|
||||
self.found = UID
|
||||
@@ -144,7 +168,7 @@ class ShapeTest(unittest.TestCase):
|
||||
self.publish("flower")
|
||||
|
||||
def test_a_blocked_account_loses_its_shape_in_lookups(self):
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(INSTALLATION))
|
||||
self.publish("flower")
|
||||
with self.registry.connect() as db:
|
||||
db.execute("INSERT INTO blocked(uid) VALUES(?)", (UID,))
|
||||
@@ -186,12 +210,12 @@ class AvatarFrameTest(unittest.TestCase):
|
||||
self.assertEqual("proof_needed", self.registry.avatar_frame(UID, INSTALLATION, "basic.cat")["reason"])
|
||||
|
||||
def test_the_code_in_the_bio_publishes_the_frame(self):
|
||||
self.bio = "me " + self.registry.code(UID)
|
||||
self.bio = "me " + self.registry.code(UID, sha(INSTALLATION))
|
||||
self.assertTrue(self.publish("basic.cat")["published"])
|
||||
self.assertEqual({UID: "basic.cat"}, self.registry.lookup([UID])["avatar_frames"])
|
||||
|
||||
def test_the_shape_proof_also_covers_frames(self):
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(INSTALLATION))
|
||||
self.registry.shape(UID, INSTALLATION, "flower", "someone")
|
||||
fetched = self.fetches
|
||||
self.bio = ""
|
||||
@@ -202,14 +226,14 @@ class AvatarFrameTest(unittest.TestCase):
|
||||
self.assertEqual({UID: "basic.crown"}, both["avatar_frames"])
|
||||
|
||||
def test_another_installation_must_prove_the_account_itself(self):
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(INSTALLATION))
|
||||
self.publish("basic.cat")
|
||||
self.bio = ""
|
||||
self.assertFalse(self.publish("basic.flame", OTHER_INSTALLATION)["published"])
|
||||
self.assertEqual({UID: "basic.cat"}, self.registry.lookup([UID])["avatar_frames"])
|
||||
|
||||
def test_none_withdraws_the_frame(self):
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(INSTALLATION))
|
||||
self.publish("basic.helmet")
|
||||
self.assertTrue(self.registry.avatar_frame(UID, INSTALLATION, "none")["published"])
|
||||
self.assertEqual({}, self.registry.lookup([UID])["avatar_frames"])
|
||||
@@ -219,7 +243,7 @@ class AvatarFrameTest(unittest.TestCase):
|
||||
self.assertEqual(0, self.fetches)
|
||||
|
||||
def test_blocked_accounts_are_refused_and_vanish_from_lookups(self):
|
||||
self.bio = self.registry.code(UID)
|
||||
self.bio = self.registry.code(UID, sha(INSTALLATION))
|
||||
self.publish("basic.cat")
|
||||
with self.registry.connect() as db:
|
||||
db.execute("INSERT INTO blocked(uid) VALUES(?)", (UID,))
|
||||
@@ -239,3 +263,15 @@ class AvatarFrameTest(unittest.TestCase):
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class CodeShapeTest(unittest.TestCase):
|
||||
def test_the_code_of_an_installation_is_nine_letters_and_digits(self):
|
||||
import re
|
||||
import tempfile as tf
|
||||
with tf.TemporaryDirectory() as tmp:
|
||||
registry = server.Registry(Path(tmp) / "r.sqlite3")
|
||||
code = registry.code(UID, sha("a" * 64))
|
||||
self.assertRegex(code, r"\ALT-[A-Z2-7]{9}\Z")
|
||||
self.assertNotEqual(code, registry.code(UID, sha("b" * 64)))
|
||||
self.assertEqual(11, len(registry.code(UID))) # the badge code keeps its old length
|
||||
|
||||
143
tests/test_pair_pet.py
Normal file
@@ -0,0 +1,143 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] / "services" / "members"
|
||||
SPEC = importlib.util.spec_from_file_location("members_server", ROOT / "server.py")
|
||||
server = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(server)
|
||||
|
||||
ALICE, BOB, STRANGER = "6812345678901234", "6899999999999999", "6877777777777777"
|
||||
INST = {ALICE: "a" * 64, BOB: "b" * 64, STRANGER: "c" * 64}
|
||||
|
||||
|
||||
def sha(value):
|
||||
return hashlib.sha256(value.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
def drawing(shade, size=(300, 200)):
|
||||
out = io.BytesIO()
|
||||
Image.new("RGBA", size, (shade, 120, 60, 200)).save(out, "PNG")
|
||||
return base64.b64encode(out.getvalue()).decode("ascii")
|
||||
|
||||
|
||||
class PairPetTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.now = 1_790_000_000
|
||||
self.who = ALICE
|
||||
self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now,
|
||||
fetcher=lambda unique_id: (self.who, self.registry.code(self.who, sha(INST[self.who]))))
|
||||
for uid in (ALICE, BOB):
|
||||
self.who = uid
|
||||
self.assertTrue(self.registry.shape(uid, INST[uid], "flower", "someone")["published"])
|
||||
|
||||
def upload(self, uid, peer, shade):
|
||||
self.who = uid
|
||||
return self.registry.pet_upload(uid, INST[uid], "someone", peer, "Серийчик", drawing(shade))
|
||||
|
||||
def look(self, uid, peer, installation=None):
|
||||
return self.registry.pet_lookup(uid, installation or INST[uid], peer)
|
||||
|
||||
def approve(self, art_id):
|
||||
self.registry.art_decide(art_id, "approved", "owner")
|
||||
|
||||
def test_a_new_picture_waits_for_approval_and_then_both_of_them_see_it(self):
|
||||
art = self.upload(ALICE, BOB, 10)
|
||||
self.assertEqual(("new", True), (art["status"], art["published"]))
|
||||
self.assertEqual({"id": None, "pending": True, "history": []}, self.look(ALICE, BOB))
|
||||
self.approve(art["id"])
|
||||
self.assertEqual({"id": art["id"], "pending": False, "history": []}, self.look(ALICE, BOB))
|
||||
self.assertEqual(art["id"], self.look(BOB, ALICE)["id"]) # the same picture for the other one
|
||||
self.assertEqual({"id": None, "pending": False, "history": []}, self.look(STRANGER, BOB, INST[STRANGER])) # a stranger sees nothing
|
||||
self.assertIsNone(self.look(ALICE, BOB, "d" * 64)["id"]) # nor does an installation that did not prove the account
|
||||
|
||||
def test_the_picture_is_kept_whole(self):
|
||||
art = self.upload(ALICE, BOB, 10)
|
||||
data = self.registry.art_bytes(art["id"], approved_only=False)
|
||||
self.assertEqual((300, 200), Image.open(io.BytesIO(data)).size) # not cropped to a square
|
||||
self.assertEqual("RGBA", Image.open(io.BytesIO(data)).mode)
|
||||
|
||||
def test_either_of_them_changes_it_and_the_old_one_stays_until_the_new_one_is_approved(self):
|
||||
first = self.upload(ALICE, BOB, 10)
|
||||
self.approve(first["id"])
|
||||
self.now += 3601
|
||||
second = self.upload(BOB, ALICE, 40) # the other one changes it
|
||||
shown = self.look(ALICE, BOB)
|
||||
self.assertEqual((first["id"], True), (shown["id"], shown["pending"])) # the old one is still shown
|
||||
self.approve(second["id"])
|
||||
shown = self.look(ALICE, BOB)
|
||||
self.assertEqual((second["id"], False, [first["id"]]), (shown["id"], shown["pending"], shown["history"]))
|
||||
|
||||
def test_a_rejected_picture_never_replaces_the_shown_one(self):
|
||||
first = self.upload(ALICE, BOB, 10)
|
||||
self.approve(first["id"])
|
||||
self.now += 3601
|
||||
second = self.upload(ALICE, BOB, 40)
|
||||
self.registry.art_decide(second["id"], "rejected", "ai: no")
|
||||
self.assertEqual(first["id"], self.look(BOB, ALICE)["id"])
|
||||
|
||||
def test_the_pair_changes_its_picture_once_an_hour_and_a_refusal_costs_no_review(self):
|
||||
self.upload(ALICE, BOB, 10)
|
||||
before = self.registry.art_counts()
|
||||
with self.assertRaises(ValueError):
|
||||
self.upload(BOB, ALICE, 40)
|
||||
self.assertEqual(before, self.registry.art_counts()) # nothing new was taken for the owner to judge
|
||||
self.now += 3601
|
||||
self.assertTrue(self.upload(BOB, ALICE, 40)["published"])
|
||||
|
||||
def test_the_same_picture_twice_is_one_entry(self):
|
||||
first = self.upload(ALICE, BOB, 10)
|
||||
again = self.upload(ALICE, BOB, 10)
|
||||
self.assertEqual(first["id"], again["id"])
|
||||
with self.registry.connect() as db:
|
||||
self.assertEqual(1, db.execute("SELECT COUNT(*) FROM pair_pet").fetchone()[0])
|
||||
|
||||
def test_an_earlier_picture_can_be_brought_back(self):
|
||||
first = self.upload(ALICE, BOB, 10)
|
||||
self.approve(first["id"])
|
||||
self.now += 3601
|
||||
second = self.upload(ALICE, BOB, 40)
|
||||
self.approve(second["id"])
|
||||
self.now += 3601
|
||||
self.registry.pet_revert(BOB, INST[BOB], ALICE, first["id"])
|
||||
self.assertEqual(first["id"], self.look(ALICE, BOB)["id"])
|
||||
with self.assertRaises(ValueError): # once an hour, the same as any change
|
||||
self.registry.pet_revert(ALICE, INST[ALICE], BOB, second["id"])
|
||||
self.now += 3601
|
||||
with self.assertRaises(ValueError): # a picture that was never theirs
|
||||
self.registry.pet_revert(ALICE, INST[ALICE], BOB, "0" * 24)
|
||||
with self.assertRaises(ValueError): # no proof, no say
|
||||
self.registry.pet_revert(STRANGER, INST[STRANGER], BOB, first["id"])
|
||||
|
||||
def test_either_side_clears_it(self):
|
||||
art = self.upload(ALICE, BOB, 10)
|
||||
self.approve(art["id"])
|
||||
self.registry.pet_clear(BOB, INST[BOB], ALICE)
|
||||
self.assertEqual({"id": None, "pending": False, "history": []}, self.look(ALICE, BOB))
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.pet_clear(STRANGER, INST[STRANGER], ALICE)
|
||||
|
||||
def test_a_banned_person_hides_the_picture(self):
|
||||
art = self.upload(ALICE, BOB, 10)
|
||||
self.approve(art["id"])
|
||||
with self.registry.connect() as db:
|
||||
db.execute("INSERT INTO blocked(uid, until) VALUES(?, 0)", (BOB,))
|
||||
self.assertIsNone(self.look(ALICE, BOB)["id"])
|
||||
with self.assertRaises(ValueError):
|
||||
self.upload(BOB, ALICE, 90)
|
||||
|
||||
def test_oneself_is_not_a_pair(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.pet_upload(ALICE, INST[ALICE], "someone", ALICE, "x", drawing(5))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
73
tests/test_pair_species.py
Normal file
@@ -0,0 +1,73 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] / "services" / "members"
|
||||
SPEC = importlib.util.spec_from_file_location("members_server", ROOT / "server.py")
|
||||
server = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(server)
|
||||
|
||||
ALICE, BOB, STRANGER = "6812345678901234", "6899999999999999", "6877777777777777"
|
||||
INST = {ALICE: "a" * 64, BOB: "b" * 64, STRANGER: "c" * 64}
|
||||
|
||||
|
||||
def sha(value):
|
||||
return hashlib.sha256(value.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
class PairSpeciesTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.now = 1_790_000_000
|
||||
self.who = ALICE
|
||||
self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now,
|
||||
fetcher=lambda unique_id: (self.who, self.registry.code(self.who, sha(INST[self.who]))))
|
||||
for uid in (ALICE, BOB, STRANGER):
|
||||
self.who = uid
|
||||
self.assertTrue(self.registry.shape(uid, INST[uid], "flower", "someone")["published"])
|
||||
|
||||
def test_offer_waits_for_the_other_one(self):
|
||||
self.registry.species_offer(ALICE, INST[ALICE], BOB, "cat")
|
||||
self.assertEqual(self.registry.species_lookup(ALICE, INST[ALICE], BOB), {"kind": "", "offer": ""}) # the giver sees no offer to answer
|
||||
self.assertEqual(self.registry.species_lookup(BOB, INST[BOB], ALICE), {"kind": "", "offer": "cat"})
|
||||
self.registry.species_answer(BOB, INST[BOB], ALICE, True)
|
||||
for me, other in ((ALICE, BOB), (BOB, ALICE)):
|
||||
self.assertEqual(self.registry.species_lookup(me, INST[me], other), {"kind": "cat", "offer": ""})
|
||||
|
||||
def test_decline_keeps_the_old_animal(self):
|
||||
self.registry.species_offer(ALICE, INST[ALICE], BOB, "dog")
|
||||
self.registry.species_answer(BOB, INST[BOB], ALICE, True)
|
||||
self.registry.species_offer(ALICE, INST[ALICE], BOB, "lion")
|
||||
self.assertEqual(self.registry.species_answer(BOB, INST[BOB], ALICE, False)["kind"], "dog")
|
||||
self.assertEqual(self.registry.species_lookup(BOB, INST[BOB], ALICE), {"kind": "dog", "offer": ""})
|
||||
|
||||
def test_cannot_accept_your_own_offer(self):
|
||||
self.registry.species_offer(ALICE, INST[ALICE], BOB, "cat")
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.species_answer(ALICE, INST[ALICE], BOB, True)
|
||||
|
||||
def test_a_third_person_sees_nothing(self):
|
||||
self.registry.species_offer(ALICE, INST[ALICE], BOB, "cat")
|
||||
self.assertEqual(self.registry.species_lookup(STRANGER, INST[STRANGER], ALICE), {"kind": "", "offer": ""})
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.species_answer(STRANGER, INST[STRANGER], ALICE, True)
|
||||
|
||||
def test_unknown_animal_and_wrong_proof(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.species_offer(ALICE, INST[ALICE], BOB, "dragon")
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.species_offer(ALICE, "d" * 64, BOB, "cat")
|
||||
|
||||
def test_old_offer_goes_stale(self):
|
||||
self.registry.species_offer(ALICE, INST[ALICE], BOB, "cat")
|
||||
self.now += 8 * 86400
|
||||
self.assertEqual(self.registry.species_lookup(BOB, INST[BOB], ALICE)["offer"], "")
|
||||
with self.assertRaises(ValueError):
|
||||
self.registry.species_answer(BOB, INST[BOB], ALICE, True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
91
tests/test_report.py
Normal file
@@ -0,0 +1,91 @@
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "services" / "members"))
|
||||
|
||||
from PIL import Image # noqa: E402
|
||||
|
||||
import report # noqa: E402
|
||||
|
||||
|
||||
def png(width, height):
|
||||
out = io.BytesIO()
|
||||
Image.new("RGBA", (width, height), (200, 100, 150, 255)).save(out, "PNG")
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def reply(data):
|
||||
return {"choices": [{"message": {"content": "<think>x</think>" + json.dumps(data)}}]}
|
||||
|
||||
|
||||
class DetailCheckTest(unittest.TestCase):
|
||||
def test_boxes_of_a_wide_picture_are_scaled_by_the_longer_side(self):
|
||||
data = {"verdict": "reject", "reason": "r", "reason_ru": "р", "regions": [{"label": "a", "label_ru": "б", "box": [0, 100, 500, 400]}]}
|
||||
result = report.detail_check(png(500, 250), post=lambda body: reply(data))
|
||||
x1, y1, x2, y2 = result["regions"][0]["box"]
|
||||
self.assertAlmostEqual(0.0, x1)
|
||||
self.assertAlmostEqual(0.2, y1) # 100/1000 * 500 / 250
|
||||
self.assertAlmostEqual(0.5, x2) # 500/1000 of the longer side (= the width here)
|
||||
self.assertAlmostEqual(0.8, y2)
|
||||
|
||||
def test_a_broken_reply_is_not_checked_and_a_nonsense_box_is_dropped(self):
|
||||
self.assertIsNone(report.detail_check(png(10, 10), post=lambda body: {"choices": []})["ok"])
|
||||
data = {"verdict": "reject", "reason": "r", "regions": [{"box": [1, 2]}, {"box": [10, 10, 11, 11]}, "x"]}
|
||||
self.assertEqual([], report.detail_check(png(10, 10), post=lambda body: reply(data))["regions"])
|
||||
|
||||
def test_pdf_is_made_with_and_without_regions(self):
|
||||
for regions in ([], [{"label": "a", "label_ru": "б", "box": [0.1, 0.1, 0.5, 0.5]}]):
|
||||
detail = {"ok": False, "reason": "Bad", "reason_ru": "Плохо", "regions": regions, "model": "m"}
|
||||
pdf = report.build_pdf(png(512, 246), detail, name="n", kind="bubble", art_id="a" * 24)
|
||||
self.assertTrue(pdf.startswith(b"%PDF"))
|
||||
self.assertIn("t.me/cheb0chik", report.CONTACT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class ChainTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
import os
|
||||
self.env = {k: os.environ.get(k) for k in ("GROQ_KEY", "GEMINI_KEY", "GEMINI_MODEL")}
|
||||
os.environ["GROQ_KEY"], os.environ["GEMINI_KEY"] = "g", "m"
|
||||
os.environ.pop("GEMINI_MODEL", None)
|
||||
self.moderation = report.moderation
|
||||
self.moderation._cooldown.clear()
|
||||
self.saved = self.moderation._post_to
|
||||
|
||||
def tearDown(self):
|
||||
import os
|
||||
self.moderation._post_to = self.saved
|
||||
self.moderation._cooldown.clear()
|
||||
for k, v in self.env.items():
|
||||
os.environ.pop(k, None)
|
||||
if v is not None:
|
||||
os.environ[k] = v
|
||||
|
||||
def test_a_provider_out_of_quota_hands_over_to_the_next_and_is_left_alone(self):
|
||||
import urllib.error
|
||||
calls = []
|
||||
|
||||
def fake(base_url, key, body, timeout=30.0):
|
||||
calls.append(key)
|
||||
if key == "g":
|
||||
raise urllib.error.HTTPError(base_url, 429, "quota", {}, None)
|
||||
return {"choices": [{"message": {"content": "{}"}}]}
|
||||
|
||||
self.moderation._post_to = fake
|
||||
body = {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "x"}}]}]}
|
||||
first = self.moderation.chain_post(body)
|
||||
self.assertEqual("gemini", first["_provider"])
|
||||
self.assertEqual("gemini-3.5-flash-lite", first["_model"])
|
||||
self.moderation.chain_post(body)
|
||||
self.assertEqual(["g", "m", "m"], calls) # Groq is not asked again while it cools down
|
||||
|
||||
def test_without_any_key_the_check_is_not_made(self):
|
||||
import os
|
||||
os.environ.pop("GROQ_KEY"), os.environ.pop("GEMINI_KEY")
|
||||
self.assertIsNone(report.detail_check(png(10, 10))["ok"])
|
||||
@@ -22,6 +22,9 @@ class FakeApk:
|
||||
def replace(self, name, data):
|
||||
self.replaced[name] = data
|
||||
|
||||
def add(self, name, data, method=None):
|
||||
self.replaced[name] = data
|
||||
|
||||
|
||||
@unittest.skipUnless(APKS, "the original TikTok apk is not in OriginalAPKtiktok/")
|
||||
class StreakPatchTest(unittest.TestCase):
|
||||
|
||||
@@ -23,6 +23,9 @@ class FakeApk:
|
||||
def replace(self, name, data):
|
||||
self.replaced[name] = data
|
||||
|
||||
def add(self, name, data, method=None):
|
||||
self.replaced[name] = data
|
||||
|
||||
|
||||
def provider_node(axml):
|
||||
return next(n for n in axml.nodes
|
||||
@@ -127,13 +130,46 @@ class WidgetPatchTest(unittest.TestCase):
|
||||
self.assertIn("FrameLayout", names)
|
||||
self.assertIn("TextView", names)
|
||||
|
||||
def test_the_java_side_uses_the_same_view_ids(self):
|
||||
source = (ROOT / "src" / "lihont" / "two" / "widget" / "StreakWidget.java").read_text(encoding="utf-8")
|
||||
import re
|
||||
picture = int(re.search(r"PICTURE\s*=\s*(0x[0-9A-Fa-f]+)", source).group(1), 16)
|
||||
frames = re.search(r"FRAME_VIEWS\s*=\s*\{([^}]*)\}", source).group(1)
|
||||
self.assertEqual(widget_patch.PICTURE, picture)
|
||||
self.assertEqual(list(widget_patch.FRAME_VIEWS), [int(h, 16) for h in re.findall(r"0x[0-9A-Fa-f]+", frames)])
|
||||
def run_java(self, *args):
|
||||
"""WidgetIds compiled against the Android stubs and run on a plain JVM (its parser touches no Android class)."""
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
javac, java = shutil.which("javac"), shutil.which("java")
|
||||
if not javac or not java:
|
||||
self.skipTest("a JDK is needed")
|
||||
jar = ROOT / "tools" / "android.jar"
|
||||
with tempfile.TemporaryDirectory() as out:
|
||||
done = subprocess.run([javac, "-encoding", "UTF-8", "-cp", str(jar), "-d", out,
|
||||
str(ROOT / "src" / "lihont" / "two" / "widget" / "WidgetIds.java"),
|
||||
str(ROOT / "tests" / "java" / "lihont" / "two" / "widget" / "WidgetIdsTest.java")], capture_output=True, text=True)
|
||||
self.assertEqual(0, done.returncode, done.stdout + done.stderr)
|
||||
run = subprocess.run([java, "-cp", out + __import__("os").pathsep + str(jar), "lihont.two.widget.WidgetIdsTest", *args], capture_output=True, text=True)
|
||||
self.assertEqual(0, run.returncode, run.stderr)
|
||||
return run.stdout.strip()
|
||||
|
||||
@staticmethod
|
||||
def line(ids):
|
||||
return "layout=0x%08X picture=0x%08X badge=0x%08X label=0x%08X frames=%s" % (
|
||||
ids.layout, ids.picture, ids.badge, ids.label, ",".join("0x%08X" % f for f in ids.frames))
|
||||
|
||||
def test_the_java_side_has_the_numbers_of_47_1_3_for_builds_without_the_file(self):
|
||||
self.assertEqual(self.line(widget_patch.DEFAULT), self.run_java())
|
||||
|
||||
def test_the_java_side_reads_the_file_the_patch_writes(self):
|
||||
table = __import__("lihont.arsc", fromlist=["Arsc"]).Arsc(self.apk.zip.read("resources.arsc"))
|
||||
ids = widget_patch.discover(self.apk, self.xml, table) # looked up in the build as TikTok made it, before the patch changes the layout
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
text = self.apk.replaced[widget_patch.IDS_ASSET].decode("ascii")
|
||||
self.assertEqual(self.line(ids), self.run_java(text.replace(chr(10), "|")))
|
||||
|
||||
def test_a_broken_ids_file_is_refused_by_the_java_side(self):
|
||||
self.assertEqual("NULL", self.run_java("layout=0x7F0D0178|picture=0x7F0A1DAB"))
|
||||
self.assertEqual("NULL", self.run_java("garbage"))
|
||||
|
||||
def test_discovery_finds_what_was_typed_in_for_47_1_3(self):
|
||||
table = __import__("lihont.arsc", fromlist=["Arsc"]).Arsc(self.apk.zip.read("resources.arsc"))
|
||||
self.assertEqual(widget_patch.DEFAULT, widget_patch.discover(self.apk, self.xml, table))
|
||||
|
||||
def test_the_widget_list_shows_our_flower_instead_of_tiktoks_pictures(self):
|
||||
report = widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
|
||||