From e8277bb7e81858853d336b9ce34c94ced1251c99 Mon Sep 17 00:00:00 2001 From: cheb0chik Date: Thu, 5 Nov 2026 15:40:01 +0300 Subject: [PATCH] LihonT Store 0.1 A catalog app for the LihonT mod: avatar frames and chat bubbles made by members. Browse, add with the plus button, author profiles, publishing with a check before anything is shown. Signs in through the TikTok that carries the mod, which hands over only the public account data to an app signed with the same key. Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 7 + AndroidManifest.xml | 33 +++ LICENSE | 53 +++++ README.md | 43 ++++ build.py | 102 +++++++++ create_by.md | 7 + res/drawable/ic_launcher.xml | 11 + res/values/strings.xml | 4 + src/lihonstore/app/Account.java | 46 ++++ src/lihonstore/app/Api.java | 90 ++++++++ src/lihonstore/app/ArtView.java | 100 +++++++++ src/lihonstore/app/CatalogPage.java | 71 +++++++ src/lihonstore/app/Cut.java | 60 ++++++ src/lihonstore/app/Images.java | 83 ++++++++ src/lihonstore/app/Item.java | 58 +++++ src/lihonstore/app/ItemGrid.java | 162 ++++++++++++++ src/lihonstore/app/ItemPage.java | 138 ++++++++++++ src/lihonstore/app/LoginPage.java | 43 ++++ src/lihonstore/app/MainActivity.java | 307 +++++++++++++++++++++++++++ src/lihonstore/app/Pictures.java | 70 ++++++ src/lihonstore/app/ProfilePage.java | 153 +++++++++++++ src/lihonstore/app/PublishPage.java | 202 ++++++++++++++++++ src/lihonstore/app/Texts.java | 38 ++++ src/lihonstore/app/Theme.java | 103 +++++++++ src/lihonstore/app/Work.java | 46 ++++ tests/lihonstore/app/CutTest.java | 49 +++++ tests/test_cut.py | 39 ++++ 27 files changed, 2118 insertions(+) create mode 100644 .gitignore create mode 100644 AndroidManifest.xml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 build.py create mode 100644 create_by.md create mode 100644 res/drawable/ic_launcher.xml create mode 100644 res/values/strings.xml create mode 100644 src/lihonstore/app/Account.java create mode 100644 src/lihonstore/app/Api.java create mode 100644 src/lihonstore/app/ArtView.java create mode 100644 src/lihonstore/app/CatalogPage.java create mode 100644 src/lihonstore/app/Cut.java create mode 100644 src/lihonstore/app/Images.java create mode 100644 src/lihonstore/app/Item.java create mode 100644 src/lihonstore/app/ItemGrid.java create mode 100644 src/lihonstore/app/ItemPage.java create mode 100644 src/lihonstore/app/LoginPage.java create mode 100644 src/lihonstore/app/MainActivity.java create mode 100644 src/lihonstore/app/Pictures.java create mode 100644 src/lihonstore/app/ProfilePage.java create mode 100644 src/lihonstore/app/PublishPage.java create mode 100644 src/lihonstore/app/Texts.java create mode 100644 src/lihonstore/app/Theme.java create mode 100644 src/lihonstore/app/Work.java create mode 100644 tests/lihonstore/app/CutTest.java create mode 100644 tests/test_cut.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e9b9076 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +build/ +dist/ +tools/ +__pycache__/ +*.pyc +*.apk +*.jar diff --git a/AndroidManifest.xml b/AndroidManifest.xml new file mode 100644 index 0000000..7d4a24b --- /dev/null +++ b/AndroidManifest.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..76b1efa --- /dev/null +++ b/LICENSE @@ -0,0 +1,53 @@ +VCBFU v2 licence (Vibe Code But Free Use) + +Copyright (c) 2026 intcatsite + +ПРАВИЛА / RULES + + 1. СВОБОДНОЕ ИСПОЛЬЗОВАНИЕ / FREE USE + Используй, копируй, изменяй, объединяй, публикуй, распространяй и продавай + программу и её производные для любой цели, бесплатно. Указывать автора + не нужно. + You may use, copy, modify, merge, publish, distribute and sell the software + and derivative works for any purpose, free of charge. Crediting the author + is not required. + + 2. УВЕДОМЛЕНИЕ / THE NOTICE (единственная обязанность / the only duty) + Если любая часть того, что ты распространяешь, написана с помощью ИИ + (вайбкод), укажи, какой моделью ты пользовался, в файле create_by.md рядом + с кодом. Достаточно честно и примерно: «Claude Sonnet 5.5 через Claude Code». + If any part of what you distribute was written with the help of an AI model + (vibe coding), name the model(s) in a file called create_by.md next to the + code. Honest and approximate is enough. + + 3. ЭТОТ ФАЙЛ / THIS FILE + Передавая код дальше, передавай этот файл вместе с ним, правила 1-3 + без изменений. + When you pass the code on, pass this file with it, rules 1-3 unchanged. + + 4. ЧУЖОЕ / THIRD PARTIES + Лицензия относится только к собственному коду автора. Код TikTok и + материалы других авторов (например, значки других модов) в неё не входят + и принадлежат своим владельцам. + This licence covers the author's own code only. TikTok's code and other + people's materials (for example the badge art of other mods) are not + included and belong to their owners. + +ДУХ ЛИЦЕНЗИИ / THE SPIRIT + + • (по желанию / if you like) Люби маму, папу, бабушек и дедушек. + • (добровольно-принудительно / voluntary-compulsory) На деловых встречах и + переговорах разговаривай так, как будто тебя на клапан придавило. + +БЕЗ ГАРАНТИЙ / NO WARRANTY + + Программа предоставляется «КАК ЕСТЬ» (AS IS), без каких-либо гарантий, + явных или подразумеваемых, включая гарантии пригодности для какой-либо + цели и отсутствия нарушений чьих-либо прав. Авторы не несут + ответственности за любой ущерб, возникший из-за использования программы. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY ARISING FROM THE USE OF THE SOFTWARE. + +(Шуточные правила из «духа лицензии» созданы на базе ООСД) diff --git a/README.md b/README.md new file mode 100644 index 0000000..5d1ac6b --- /dev/null +++ b/README.md @@ -0,0 +1,43 @@ +# LihonT Store + +Приложение-каталог для мода **LihonT** (TikTok): рамки для аватарок и картинки для пузырей чата, которые делают люди. + +Основной проект: https://git.lihont.space/lihont/LihonT · канал: https://t.me/lihont + +## Что умеет + +- **Каталог** с двумя разделами, «Рамки» и «Пузыри чата» (плагины появятся позже). Новые сверху, лента подгружается при прокрутке. +- **Карточка вещи:** описание, автор, сколько людей добавили. Кнопка «+» кладёт вещь в вашу библиотеку, а мод показывает её у себя: + рамка в «Рамка аватарки → Из магазина», пузырь в «Пузыри чата → Пузырь из магазина». +- **Профили.** Нажмите на ник автора, и увидите всё, что он опубликовал. Свой профиль: опубликовано, на проверке (с причиной, если не приняли), библиотека. +- **Публикация.** Кнопка «+» внизу: рамка или пузырь, картинка, название, описание. Фото для рамки само вырезается в кольцо. Сначала работу + проверяют, и пока её не приняли, никто её не видит. + +## Как входит + +Пароль никуда не передаётся. Магазин просит у TikTok с модом LihonT только публичное: номер и имя аккаунта и «секрет установки» мода, которым сервер +уже знает аккаунт как подтверждённый. Мод отдаёт это только приложению `lihonstore.app`, подписанному тем же ключом, что и сам TikTok с модом +(активность `lihont.two.store.LoginActivity` в моде). Поэтому **магазин и мод должны быть подписаны одним ключом**. Первый раз аккаунт подтверждают кодом +в описании профиля, как для формы аватарки и рамок в моде. + +## Сборка + +Нужны: JDK 17+, Android SDK (build-tools с `aapt2`, платформа 34), `r8.jar` из build-tools и `uber-apk-signer.jar`. + +``` +set ANDROID_HOME=C:\path\to\Sdk +set R8_JAR=C:\path\to\r8.jar +set UBER_SIGNER=C:\path\to\uber-apk-signer.jar +py build.py +``` + +Готовый файл: `dist/lihonstore.apk`. Тесты картинок: `py -m unittest discover tests`. + +## Устройство + +Простые Android-экраны без библиотек: `MainActivity` (нижняя панель, вход через мод, подтверждение аккаунта), `CatalogPage`, `ItemPage`, `ProfilePage`, +`PublishPage`, сетка карточек `ItemGrid`, загрузчик картинок `Images`, запросы к сервису LihonT `Api`. Математика рамки (`Cut`) та же, что в моде. + +## Лицензия + +VCBFU v2, файл `LICENSE`. Код написан с помощью ИИ, модели названы в `create_by.md`. diff --git a/build.py b/build.py new file mode 100644 index 0000000..a066f56 --- /dev/null +++ b/build.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Builds LihonT Store into dist/lihonstore.apk: aapt2 (resources), javac, D8 (dex) and a signature. + +What it needs, found by itself or named in the environment: + ANDROID_HOME the Android SDK (build-tools with aapt2, platforms/android-34/android.jar); default: the usual place of the platform + R8_JAR r8.jar of the Android build tools (it holds D8); default: tools/r8.jar + UBER_SIGNER uber-apk-signer.jar; default: tools/uber-apk-signer.jar + JDK 17 or newer with javac and java on the PATH. + +Signing: LihonT Store and the TikTok that carries the LihonT mod must be signed with the same key, or the mod will not hand over the +account. uber-apk-signer signs with its built-in debug key unless you give it your own (see its --ks option), the same as the mod. + + py build.py +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +BUILD = ROOT / "build" +DIST = ROOT / "dist" +FINAL = DIST / "lihonstore.apk" + + +def sdk() -> Path: + home = os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") + if home: + return Path(home) + for candidate in (Path.home() / "AppData" / "Local" / "Android" / "Sdk", Path.home() / "Android" / "Sdk", Path.home() / "Library" / "Android" / "sdk"): + if candidate.is_dir(): + return candidate + sys.exit("Android SDK not found: set ANDROID_HOME") + + +def newest(folder: Path) -> Path: + versions = sorted(p for p in folder.iterdir() if p.is_dir()) + if not versions: + sys.exit("nothing in " + str(folder)) + return versions[-1] + + +def tool(path: Path, what: str) -> Path: + if not path.is_file(): + sys.exit("%s not found: %s" % (what, path)) + return path + + +def run(command: list, what: str) -> None: + print("->", what) + done = subprocess.run([str(part) for part in command], capture_output=True, text=True) + if done.returncode != 0: + print(done.stdout + done.stderr) + sys.exit("failed: " + what) + + +def main() -> None: + home = sdk() + suffix = ".exe" if os.name == "nt" else "" + aapt2 = tool(newest(home / "build-tools") / ("aapt2" + suffix), "aapt2") + android_jar = tool(home / "platforms" / "android-34" / "android.jar", "android.jar of platform 34") + r8 = tool(Path(os.environ.get("R8_JAR", ROOT / "tools" / "r8.jar")), "r8.jar") + signer = tool(Path(os.environ.get("UBER_SIGNER", ROOT / "tools" / "uber-apk-signer.jar")), "uber-apk-signer.jar") + + shutil.rmtree(BUILD, ignore_errors=True) + classes, dex, gen = BUILD / "classes", BUILD / "dex", BUILD / "gen" + for folder in (classes, dex, gen, DIST): + folder.mkdir(parents=True, exist_ok=True) + + compiled = BUILD / "resources.zip" + run([aapt2, "compile", "--dir", ROOT / "res", "-o", compiled], "compiling resources") + unaligned = BUILD / "unaligned.apk" + run([aapt2, "link", "-I", android_jar, "--manifest", ROOT / "AndroidManifest.xml", "-o", unaligned, + "--java", gen, "--auto-add-overlay", compiled], "linking the package and generating R.java") + + sources = list((ROOT / "src").rglob("*.java")) + list(gen.rglob("*.java")) + run(["javac", "--release", "17", "-encoding", "UTF-8", "-cp", android_jar, "-d", classes] + sources, "compiling %d sources" % len(sources)) + + class_files = [str(path) for path in classes.rglob("*.class")] + run(["java", "-cp", r8, "com.android.tools.r8.D8", "--release", "--min-api", "31", "--lib", android_jar, "--output", dex] + class_files, + "making classes.dex") + with zipfile.ZipFile(unaligned, "a") as package: + package.write(dex / "classes.dex", "classes.dex") + + signed = BUILD / "signed" + run(["java", "-jar", signer, "--apks", unaligned, "--out", signed], "signing") + built = sorted(signed.glob("*.apk")) + if not built: + sys.exit("no signed apk was produced") + shutil.copy2(built[0], FINAL) + print("built %s (%d KB)" % (FINAL, FINAL.stat().st_size // 1024)) + + +if __name__ == "__main__": + main() diff --git a/create_by.md b/create_by.md new file mode 100644 index 0000000..08f2a2c --- /dev/null +++ b/create_by.md @@ -0,0 +1,7 @@ +# create_by + +LihonT Store написан с помощью ИИ. По правилу лицензии VCBFU вот модели. + +- Claude Sonnet 5.5 (Anthropic), через Claude Code. + +Решения, проверки на телефоне и выпуск релизов на стороне автора. diff --git a/res/drawable/ic_launcher.xml b/res/drawable/ic_launcher.xml new file mode 100644 index 0000000..b277c4d --- /dev/null +++ b/res/drawable/ic_launcher.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/res/values/strings.xml b/res/values/strings.xml new file mode 100644 index 0000000..b6c1ecb --- /dev/null +++ b/res/values/strings.xml @@ -0,0 +1,4 @@ + + + LihonT Store + diff --git a/src/lihonstore/app/Account.java b/src/lihonstore/app/Account.java new file mode 100644 index 0000000..d50f438 --- /dev/null +++ b/src/lihonstore/app/Account.java @@ -0,0 +1,46 @@ +package lihonstore.app; + +import android.content.Context; +import android.content.SharedPreferences; + +/** + * The account the store works for: its public id and username, and the installation secret of the mod that was asked for them. The + * service knows that installation as the proven holder of the account, so the store may act for it. All of it stays in this app's private + * storage; the password of TikTok is never involved. + */ +final class Account { + private static final String PREFS = "lihonstore"; + + final String uid; + final String uniqueId; + final String installation; + + private Account(String uid, String uniqueId, String installation) { + this.uid = uid; + this.uniqueId = uniqueId; + this.installation = installation; + } + + static Account get(Context context) { + SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + String uid = prefs.getString("uid", null); + String installation = prefs.getString("installation", null); + if (uid == null || installation == null) return null; + return new Account(uid, prefs.getString("unique_id", ""), installation); + } + + static Account save(Context context, String uid, String uniqueId, String installation) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putString("uid", uid).putString("unique_id", uniqueId).putString("installation", installation).apply(); + return new Account(uid, uniqueId, installation); + } + + static void forget(Context context) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().clear().apply(); + } + + /** True for what the mod hands over: a numeric account id of a sane length and a 64-digit hex installation secret. */ + static boolean valid(String uid, String installation) { + return uid != null && uid.matches("[1-9][0-9]{4,24}") && installation != null && installation.matches("[a-f0-9]{64}"); + } +} diff --git a/src/lihonstore/app/Api.java b/src/lihonstore/app/Api.java new file mode 100644 index 0000000..0ce25b4 --- /dev/null +++ b/src/lihonstore/app/Api.java @@ -0,0 +1,90 @@ +package lihonstore.app; + +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +/** The LihonT service: JSON posts to /members/v1/ and the approved pictures from /members/v1/art/.png. */ +final class Api { + static final String BASE = "https://lihont.space/members/v1/"; + private static final int ART_LIMIT = 200 * 1024; + + private Api() {} + + /** A failed call: the message is the service's own (or a short note about the network). */ + static final class Failure extends Exception { + Failure(String message) { + super(message); + } + } + + static JSONObject post(String operation, JSONObject body) throws Failure { + HttpURLConnection connection = null; + try { + connection = (HttpURLConnection) new URL(BASE + operation).openConnection(); + connection.setConnectTimeout(6000); + connection.setReadTimeout(30000); + connection.setInstanceFollowRedirects(false); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); + connection.setRequestProperty("User-Agent", "LihonT-Store/1"); + byte[] data = body.toString().getBytes(StandardCharsets.UTF_8); + connection.setFixedLengthStreamingMode(data.length); + try (OutputStream out = connection.getOutputStream()) { + out.write(data); + } + int status = connection.getResponseCode(); + InputStream stream = status < 400 ? connection.getInputStream() : connection.getErrorStream(); + String text = stream == null ? "" : new String(readAll(stream, 1 << 20), StandardCharsets.UTF_8); + JSONObject json = text.length() == 0 ? new JSONObject() : new JSONObject(text); + if (status >= 400) throw new Failure(Texts.error(json.optString("error", ""))); + return json; + } catch (Failure failure) { + throw failure; + } catch (Exception unreachable) { + android.util.Log.w("LIHONSTORE", "post " + operation + " failed: " + unreachable); + throw new Failure("Нет связи с сервером"); + } finally { + if (connection != null) connection.disconnect(); + } + } + + /** The picture of an approved item. */ + static byte[] art(String id) throws Failure { + HttpURLConnection connection = null; + try { + connection = (HttpURLConnection) new URL(BASE + "art/" + id + ".png").openConnection(); + connection.setConnectTimeout(6000); + connection.setReadTimeout(20000); + connection.setInstanceFollowRedirects(false); + connection.setRequestProperty("User-Agent", "LihonT-Store/1"); + if (connection.getResponseCode() != 200) throw new Failure("Картинки нет"); + return readAll(connection.getInputStream(), ART_LIMIT); + } catch (Failure failure) { + throw failure; + } catch (Exception unreachable) { + throw new Failure("Нет связи с сервером"); + } finally { + if (connection != null) connection.disconnect(); + } + } + + private static byte[] readAll(InputStream in, int limit) throws IOException { + try (InputStream source = in; ByteArrayOutputStream out = new ByteArrayOutputStream()) { + byte[] buffer = new byte[8192]; + int count; + while ((count = source.read(buffer)) >= 0) { + out.write(buffer, 0, count); + if (out.size() > limit) throw new IOException("too large"); + } + return out.toByteArray(); + } + } +} diff --git a/src/lihonstore/app/ArtView.java b/src/lihonstore/app/ArtView.java new file mode 100644 index 0000000..7409289 --- /dev/null +++ b/src/lihonstore/app/ArtView.java @@ -0,0 +1,100 @@ +package lihonstore.app; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.RectF; +import android.view.View; + +/** + * How an item looks on a card: a frame is drawn round a plain avatar the way the mod draws it (the picture is OVERLAY times as wide as + * the avatar), a chat picture is drawn as the background of a small message. + */ +final class ArtView extends View implements Images.Ready { + private final Theme theme; + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); + private final RectF box = new RectF(); + private final Path clip = new Path(); + private String id; + private boolean frame; + private Bitmap bitmap; + + ArtView(Context context, Theme theme) { + super(context); + this.theme = theme; + } + + void show(String id, boolean frame) { + this.id = id; + this.frame = frame; + bitmap = id == null ? null : Images.get(id, this); + invalidate(); + } + + @Override public void done(Bitmap ready) { + bitmap = ready; + invalidate(); + } + + @Override protected void onDraw(Canvas canvas) { + float w = getWidth(); + float h = getHeight(); + box.set(0, 0, w, h); + paint.setColor(theme.surfaceHigh); + canvas.drawRoundRect(box, theme.dp(16), theme.dp(16), paint); + if (frame) drawFrame(canvas, w, h); else drawBubble(canvas, w, h); + } + + private void drawFrame(Canvas canvas, float w, float h) { + float side = Math.min(w, h) * 0.92f; + float cx = w / 2f; + float cy = h / 2f; + float disc = side / Cut.OVERLAY / 2f; + paint.setColor(theme.accentSoft); + canvas.drawCircle(cx, cy, disc, paint); + paint.setColor(theme.onAccentSoft); + canvas.drawCircle(cx, cy - disc * 0.18f, disc * 0.3f, paint); + RectF body = new RectF(cx - disc * 0.55f, cy + disc * 0.25f, cx + disc * 0.55f, cy + disc * 1.2f); + canvas.save(); + clip.reset(); + clip.addCircle(cx, cy, disc, Path.Direction.CW); + canvas.clipPath(clip); + canvas.drawOval(body, paint); + canvas.restore(); + if (bitmap != null) { + box.set(cx - side / 2f, cy - side / 2f, cx + side / 2f, cy + side / 2f); + canvas.drawBitmap(bitmap, null, box, paint); + } + } + + private void drawBubble(Canvas canvas, float w, float h) { + float bw = w * 0.82f; + float bh = Math.min(h * 0.5f, bw * 0.5f); + box.set((w - bw) / 2f, (h - bh) / 2f, (w + bw) / 2f, (h + bh) / 2f); + float radius = theme.dp(18); + if (bitmap == null) { + paint.setColor(theme.accentSoft); + canvas.drawRoundRect(box, radius, radius, paint); + return; + } + canvas.save(); + clip.reset(); + clip.addRoundRect(box, radius, radius, Path.Direction.CW); + canvas.clipPath(clip); + float scale = Math.max(box.width() / bitmap.getWidth(), box.height() / bitmap.getHeight()); + float sw = box.width() / scale; + float sh = box.height() / scale; + android.graphics.Rect source = new android.graphics.Rect(Math.round((bitmap.getWidth() - sw) / 2f), Math.round((bitmap.getHeight() - sh) / 2f), + Math.round((bitmap.getWidth() + sw) / 2f), Math.round((bitmap.getHeight() + sh) / 2f)); + canvas.drawBitmap(bitmap, source, box, paint); + canvas.restore(); + int middle = bitmap.getPixel(bitmap.getWidth() / 2, bitmap.getHeight() / 2); + float light = (0.299f * ((middle >> 16) & 0xFF) + 0.587f * ((middle >> 8) & 0xFF) + 0.114f * (middle & 0xFF)) / 255f; + paint.setColor(light < 0.55f ? 0xFFFFFFFF : 0xFF111111); + paint.setTextSize(theme.dp(15)); + paint.setTextAlign(Paint.Align.CENTER); + canvas.drawText("Привет!", box.centerX(), box.centerY() + theme.dp(5), paint); + } +} diff --git a/src/lihonstore/app/CatalogPage.java b/src/lihonstore/app/CatalogPage.java new file mode 100644 index 0000000..90fe494 --- /dev/null +++ b/src/lihonstore/app/CatalogPage.java @@ -0,0 +1,71 @@ +package lihonstore.app; + +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.json.JSONObject; + +/** The main screen: every approved item, newest first, with a switch between frames and chat bubbles (plugins will come as a third). */ +final class CatalogPage { + private final MainActivity host; + private final LinearLayout page; + private final TextView framesChip; + private final TextView bubblesChip; + private final ItemGrid[] grids = new ItemGrid[2]; + private int shown = 0; + + CatalogPage(final MainActivity host) { + this.host = host; + Theme theme = host.theme(); + page = theme.column(host); + TextView title = theme.text(host, "Каталог", 26f, theme.onSurface, true); + title.setPadding(theme.dp(20), theme.dp(16), theme.dp(20), theme.dp(8)); + page.addView(title); + LinearLayout chips = theme.row(host); + chips.setPadding(theme.dp(16), 0, theme.dp(16), theme.dp(8)); + framesChip = theme.chip(host, "Рамки", true); + bubblesChip = theme.chip(host, "Пузыри чата", false); + framesChip.setOnClickListener(v -> select(0)); + bubblesChip.setOnClickListener(v -> select(1)); + LinearLayout.LayoutParams gap = new LinearLayout.LayoutParams(-2, -2); + gap.rightMargin = theme.dp(8); + chips.addView(framesChip, gap); + chips.addView(bubblesChip); + page.addView(chips); + select(0); + } + + View view() { + return page; + } + + private void select(int index) { + Theme theme = host.theme(); + if (page.getChildCount() > 2) page.removeViewAt(2); + shown = index; + if (grids[index] == null) { + final String kind = index == 0 ? "frame" : "bubble"; + grids[index] = new ItemGrid(host, cursor -> { + JSONObject request = new JSONObject(); + try { + request.put("kind", kind); + if (cursor != null) request.put("cursor", cursor); + } catch (org.json.JSONException impossible) { + throw new IllegalStateException(impossible); + } + return ItemGrid.Page.of(Api.post("catalog", request)); + }, index == 0 ? "Рамок пока нет. Станьте первым: кнопка «+» внизу." : "Пузырей пока нет. Станьте первым: кнопка «+» внизу."); + grids[index].reload(); + } + page.addView(grids[index].view(), new LinearLayout.LayoutParams(-1, 0, 1f)); + recolor(framesChip, index == 0, theme); + recolor(bubblesChip, index == 1, theme); + } + + private void recolor(TextView chip, boolean selected, Theme theme) { + chip.setTextColor(selected ? theme.onAccent : theme.onSurface); + chip.setTypeface(selected ? android.graphics.Typeface.DEFAULT_BOLD : android.graphics.Typeface.DEFAULT); + chip.setBackground(theme.round(selected ? theme.accent : theme.surfaceHigh, 20)); + } +} diff --git a/src/lihonstore/app/Cut.java b/src/lihonstore/app/Cut.java new file mode 100644 index 0000000..f96c09f --- /dev/null +++ b/src/lihonstore/app/Cut.java @@ -0,0 +1,60 @@ +package lihonstore.app; + +/** + * The pixel maths that turns a picture into a frame, on plain ARGB arrays (so it is tested without a phone). The same as the mod's: + * a frame is a square picture drawn OVERLAY times as wide as the avatar, and the avatar fills the middle 1/OVERLAY of it. + */ +final class Cut { + static final int SIDE = 256; + static final float OVERLAY = 1.3f; + + private Cut() {} + + /** True when most of the middle disc is see-through: the picture is a frame already and is kept as it is. */ + static boolean seeThroughMiddle(int[] pixels) { + float middle = SIDE / 2f; + float reach = SIDE * 0.3f; + int total = 0; + int solid = 0; + for (int y = 0; y < SIDE; y++) { + for (int x = 0; x < SIDE; x++) { + float dx = x + 0.5f - middle; + float dy = y + 0.5f - middle; + if (dx * dx + dy * dy > reach * reach) continue; + total++; + if ((pixels[y * SIDE + x] >>> 24) > 128) solid++; + } + } + return total > 0 && solid < total / 2; + } + + /** Keeps only the ring between the hole (1/OVERLAY of the width, a little less so the ring overlaps the avatar) and the circle. */ + static void ring(int[] pixels) { + float middle = SIDE / 2f; + float inner = SIDE / OVERLAY / 2f * 0.96f; + float outer = SIDE / 2f - 1f; + for (int y = 0; y < SIDE; y++) { + for (int x = 0; x < SIDE; x++) { + float dx = x + 0.5f - middle; + float dy = y + 0.5f - middle; + float distance = (float) Math.sqrt(dx * dx + dy * dy); + float keep = Math.min(clamp(distance - inner + 1f), clamp(outer - distance + 1f)); + int color = pixels[y * SIDE + x]; + int alpha = Math.round(((color >>> 24) & 0xFF) * keep); + pixels[y * SIDE + x] = (alpha << 24) | (color & 0x00FFFFFF); + } + } + } + + /** The size a picture is scaled to so that its longer side is at most `limit` (never enlarged), as {width, height}. */ + static int[] fit(int width, int height, int limit) { + int longer = Math.max(width, height); + if (longer <= limit) return new int[] {width, height}; + float scale = limit / (float) longer; + return new int[] {Math.max(3, Math.round(width * scale)), Math.max(3, Math.round(height * scale))}; + } + + private static float clamp(float value) { + return value < 0f ? 0f : (value > 1f ? 1f : value); + } +} diff --git a/src/lihonstore/app/Images.java b/src/lihonstore/app/Images.java new file mode 100644 index 0000000..0245af4 --- /dev/null +++ b/src/lihonstore/app/Images.java @@ -0,0 +1,83 @@ +package lihonstore.app; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.Handler; +import android.os.Looper; +import android.util.LruCache; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** The pictures of the catalog, fetched in the background and kept in a small memory cache (they never change under their id). */ +final class Images { + interface Ready { + void done(Bitmap bitmap); + } + + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + private static final ExecutorService POOL = Executors.newFixedThreadPool(3); + private static final LruCache CACHE = new LruCache(12 * 1024 * 1024) { + @Override protected int sizeOf(String key, Bitmap value) { + return value.getByteCount(); + } + }; + private static final Map> WAITING = new HashMap>(); + private static final Set BROKEN = new HashSet(); + + private Images() {} + + /** The bitmap at once when it is cached, else it is fetched and `ready` is called on the main thread (not at all if it is missing). */ + static Bitmap get(final String id, Ready ready) { + Bitmap cached = CACHE.get(id); + if (cached != null) return cached; + if (BROKEN.contains(id)) return null; + synchronized (WAITING) { + java.util.List list = WAITING.get(id); + if (list != null) { + list.add(ready); + return null; + } + list = new java.util.ArrayList(); + list.add(ready); + WAITING.put(id, list); + } + final String key = id; + POOL.execute(new Runnable() { + @Override public void run() { + Bitmap bitmap = null; + try { + byte[] data = Api.art(key); + bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); + } catch (Exception unavailable) { + bitmap = null; + } + final Bitmap decoded = bitmap; + MAIN.post(new Runnable() { + @Override public void run() { + java.util.List list; + synchronized (WAITING) { + list = WAITING.remove(key); + } + if (decoded == null) { + BROKEN.add(key); + return; + } + CACHE.put(key, decoded); + if (list != null) for (Ready item : list) item.done(decoded); + } + }); + } + }); + return null; + } + + /** Keeps a picture made on the phone (a preview before publishing) under a temporary id. */ + static void put(String id, Bitmap bitmap) { + CACHE.put(id, bitmap); + } +} diff --git a/src/lihonstore/app/Item.java b/src/lihonstore/app/Item.java new file mode 100644 index 0000000..d205bde --- /dev/null +++ b/src/lihonstore/app/Item.java @@ -0,0 +1,58 @@ +package lihonstore.app; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; + +/** One catalog item as the service describes it (a public one, or one of the account's own with its state). */ +final class Item { + final String id; + final String kind; + final String name; + final String description; + final String authorUid; + final String authorName; + final int installs; + /** For the account's own items: approved, new, review or rejected; empty for the public ones. */ + final String status; + final String reason; + final boolean listed; + + private Item(JSONObject json) { + id = json.optString("id", ""); + kind = json.optString("kind", "frame"); + name = json.optString("name", ""); + description = json.optString("description", ""); + JSONObject author = json.optJSONObject("author"); + authorUid = author == null ? "" : author.optString("uid", ""); + authorName = author == null || author.isNull("name") ? "" : author.optString("name", ""); + installs = json.optInt("installs", 0); + status = json.optString("status", ""); + reason = json.optString("reason", ""); + listed = json.optBoolean("listed", true); + } + + static Item of(JSONObject json) { + return new Item(json); + } + + static List list(JSONArray array) { + List items = new ArrayList(); + if (array == null) return items; + for (int i = 0; i < array.length(); i++) { + JSONObject json = array.optJSONObject(i); + if (json != null && json.optString("id", "").matches("[0-9a-f]{24}")) items.add(new Item(json)); + } + return items; + } + + boolean isFrame() { + return "frame".equals(kind); + } + + String author() { + return authorName.length() == 0 ? "автор" : "@" + authorName; + } +} diff --git a/src/lihonstore/app/ItemGrid.java b/src/lihonstore/app/ItemGrid.java new file mode 100644 index 0000000..57ce824 --- /dev/null +++ b/src/lihonstore/app/ItemGrid.java @@ -0,0 +1,162 @@ +package lihonstore.app; + +import android.content.Context; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; + +/** Items as a grid of two columns in a scrolling list, newest first; the next page is fetched when the end is reached. */ +final class ItemGrid { + /** Asks the service for one page: `cursor` is null for the first. */ + interface Pager { + Page load(String cursor) throws Api.Failure; + } + + static final class Page { + final List items; + final String next; + + Page(List items, String next) { + this.items = items; + this.next = next; + } + + static Page of(JSONObject reply) { + return new Page(Item.list(reply.optJSONArray("items")), reply.isNull("next") ? null : reply.optString("next", null)); + } + } + + private final MainActivity host; + private final Pager pager; + private final String empty; + private final ScrollView scroll; + private final LinearLayout list; + private final TextView note; + private String next; + private boolean loading; + private boolean finished; + private int count; + private LinearLayout line; + private int generation; + + ItemGrid(MainActivity host, Pager pager, String empty) { + this.host = host; + this.pager = pager; + this.empty = empty; + Theme theme = host.theme(); + Context context = host; + scroll = new ScrollView(context); + scroll.setFillViewport(true); + list = theme.column(context); + list.setPadding(theme.dp(12), theme.dp(4), theme.dp(12), theme.dp(16)); + note = theme.text(context, "", 14f, theme.muted, false); + note.setGravity(Gravity.CENTER); + note.setPadding(0, theme.dp(24), 0, theme.dp(24)); + scroll.addView(list, new ViewGroup.LayoutParams(-1, -2)); + scroll.setOnScrollChangeListener((v, x, y, oldX, oldY) -> { + View last = scroll.getChildAt(0); + if (last != null && last.getBottom() - (scroll.getHeight() + scroll.getScrollY()) < theme.dp(300)) more(); + }); + } + + View view() { + return scroll; + } + + /** Starts again from the newest (after a change, or for another filter). */ + void reload() { + generation++; + list.removeAllViews(); + next = null; + finished = false; + loading = false; + count = 0; + line = null; + more(); + } + + private void more() { + if (loading || finished) return; + loading = true; + final int mine = generation; + final String cursor = next; + if (count == 0) show("Загружаем…"); + Work.run(() -> pager.load(cursor), new Work.Done() { + @Override public void ok(Page page) { + if (mine != generation) return; + loading = false; + hideNote(); + next = page.next; + finished = page.next == null; + for (Item item : page.items) add(item); + if (count == 0) show(empty); + if (!finished) scroll.post(() -> { + View last = scroll.getChildAt(0); + if (last != null && last.getHeight() < scroll.getHeight()) more(); + }); + } + + @Override public void failed(String message) { + if (mine != generation) return; + loading = false; + if (count == 0) show(message + ". Нажмите, чтобы повторить"); + else host.toast(message); + note.setOnClickListener(v -> reload()); + } + }); + } + + private void show(String text) { + note.setText(text); + if (note.getParent() == null) list.addView(note); + } + + private void hideNote() { + if (note.getParent() != null) list.removeView(note); + } + + private void add(final Item item) { + Theme theme = host.theme(); + if (count % 2 == 0) { + line = theme.row(host); + line.setGravity(Gravity.TOP); + list.addView(line, new LinearLayout.LayoutParams(-1, -2)); + } + count++; + LinearLayout card = theme.column(host); + card.setPadding(theme.dp(6), theme.dp(6), theme.dp(6), theme.dp(10)); + ArtView art = new ArtView(host, theme); + art.show(item.id, item.isFrame()); + card.addView(art, new LinearLayout.LayoutParams(-1, theme.dp(150))); + TextView name = theme.text(host, item.name, 15f, theme.onSurface, true); + name.setSingleLine(true); + name.setEllipsize(android.text.TextUtils.TruncateAt.END); + name.setPadding(theme.dp(4), theme.dp(8), theme.dp(4), 0); + card.addView(name); + String sub = item.status.length() > 0 ? Texts.status(item.status) + (item.reason.length() > 0 ? ": " + Texts.reason(item.reason) : "") + : item.author() + " · " + item.installs; + TextView meta = theme.text(host, sub, 12f, "rejected".equals(item.status) ? theme.danger : theme.muted, false); + meta.setSingleLine(true); + meta.setEllipsize(android.text.TextUtils.TruncateAt.END); + meta.setPadding(theme.dp(4), theme.dp(2), theme.dp(4), 0); + card.addView(meta); + card.setClickable(true); + card.setOnClickListener(v -> host.openItem(item)); + if (count % 2 == 1) { + // an unfinished row gets an empty second cell so that the first card keeps half the width + line.addView(card, new LinearLayout.LayoutParams(0, -2, 1f)); + line.addView(new View(host), new LinearLayout.LayoutParams(0, 1, 1f)); + } else { + line.removeViewAt(1); + line.addView(card, new LinearLayout.LayoutParams(0, -2, 1f)); + } + } +} diff --git a/src/lihonstore/app/ItemPage.java b/src/lihonstore/app/ItemPage.java new file mode 100644 index 0000000..862aed7 --- /dev/null +++ b/src/lihonstore/app/ItemPage.java @@ -0,0 +1,138 @@ +package lihonstore.app; + +import android.view.Gravity; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import org.json.JSONObject; + +/** One item: a large preview, the description, the author (a tap opens their profile) and the "+" that adds it to the account's library. */ +final class ItemPage { + private final MainActivity host; + private final Item item; + private final TextView action; + private final TextView meta; + + ItemPage(MainActivity host, Item item) { + this.host = host; + this.item = item; + Theme theme = host.theme(); + action = theme.button(host, "", true); + meta = theme.text(host, "", 13f, theme.muted, false); + } + + View view() { + final Theme theme = host.theme(); + ScrollView scroll = new ScrollView(host); + LinearLayout page = theme.column(host); + page.setPadding(theme.dp(20), theme.dp(8), theme.dp(20), theme.dp(24)); + scroll.addView(page); + TextView back = theme.text(host, "← Назад", 15f, theme.accent, true); + back.setPadding(0, theme.dp(8), 0, theme.dp(12)); + back.setClickable(true); + back.setOnClickListener(v -> host.back()); + page.addView(back); + ArtView art = new ArtView(host, theme); + art.show(item.id, item.isFrame()); + page.addView(art, new LinearLayout.LayoutParams(-1, theme.dp(280))); + TextView name = theme.text(host, item.name, 24f, theme.onSurface, true); + name.setPadding(0, theme.dp(16), 0, 0); + page.addView(name); + TextView kind = theme.text(host, Texts.kind(item.kind), 13f, theme.muted, false); + page.addView(kind); + if (item.description.length() > 0) { + TextView about = theme.text(host, item.description, 16f, theme.onSurface, false); + about.setPadding(0, theme.dp(12), 0, 0); + page.addView(about); + } + if (item.authorUid.length() > 0) { + TextView author = theme.text(host, "Автор: " + item.author(), 15f, theme.accent, true); + author.setPadding(0, theme.dp(16), 0, 0); + author.setClickable(true); + author.setOnClickListener(v -> host.openProfile(item.authorUid, item.authorName)); + page.addView(author); + } + meta.setPadding(0, theme.dp(4), 0, theme.dp(20)); + page.addView(meta); + if (item.status.length() > 0) { + TextView state = theme.text(host, Texts.status(item.status) + (item.reason.length() > 0 ? ": " + Texts.reason(item.reason) : ""), + 14f, "rejected".equals(item.status) ? theme.danger : theme.muted, false); + state.setPadding(0, 0, 0, theme.dp(16)); + page.addView(state); + } + if ("approved".equals(item.status) || item.status.length() == 0) { + page.addView(action, new LinearLayout.LayoutParams(-1, -2)); + refresh(); + action.setOnClickListener(v -> toggle()); + } + Account account = host.account(); + if (account != null && account.uid.equals(item.authorUid) && item.listed && "approved".equals(item.status)) { + TextView off = theme.button(host, "Снять с публикации", false); + off.setOnClickListener(v -> unpublish()); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); + params.topMargin = theme.dp(12); + page.addView(off, params); + } + return scroll; + } + + private void refresh() { + boolean added = host.library().contains(item.id); + action.setText(added ? "Убрать из моих" : "+ Добавить в мои"); + Theme theme = host.theme(); + action.setTextColor(added ? theme.onAccentSoft : theme.onAccent); + action.setBackground(theme.round(added ? theme.accentSoft : theme.accent, 24)); + meta.setText("Добавили: " + item.installs + " · " + (item.isFrame() ? "в приложении LihonT её можно выбрать как рамку" : "в приложении LihonT её можно выбрать как пузырь")); + } + + private void toggle() { + final boolean add = !host.library().contains(item.id); + action.setEnabled(false); + host.proven(() -> Work.run(() -> { + JSONObject request = host.body(); + try { + request.put("id", item.id); + } catch (org.json.JSONException impossible) { + throw new IllegalStateException(impossible); + } + return Api.post(add ? "library_add" : "library_remove", request); + }, new Work.Done() { + @Override public void ok(JSONObject reply) { + action.setEnabled(true); + if (add) host.library().add(item.id); else host.library().remove(item.id); + refresh(); + host.toast(add ? "Добавлено. Откройте выбор в TikTok: она уже там" : "Убрано"); + } + + @Override public void failed(String message) { + action.setEnabled(true); + host.toast(message); + } + })); + // the proof dialog may be shown instead: the button must not stay dead + action.postDelayed(() -> action.setEnabled(true), 3000L); + } + + private void unpublish() { + Work.run(() -> { + JSONObject request = host.body(); + try { + request.put("id", item.id); + } catch (org.json.JSONException impossible) { + throw new IllegalStateException(impossible); + } + return Api.post("unpublish", request); + }, new Work.Done() { + @Override public void ok(JSONObject reply) { + host.toast("Снято с публикации"); + host.back(); + } + + @Override public void failed(String message) { + host.toast(message); + } + }); + } +} diff --git a/src/lihonstore/app/LoginPage.java b/src/lihonstore/app/LoginPage.java new file mode 100644 index 0000000..6165226 --- /dev/null +++ b/src/lihonstore/app/LoginPage.java @@ -0,0 +1,43 @@ +package lihonstore.app; + +import android.view.Gravity; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +/** The first screen: one button, which asks the TikTok with the LihonT mod for the signed-in account. */ +final class LoginPage { + private final MainActivity host; + private final String problem; + + LoginPage(MainActivity host, String problem) { + this.host = host; + this.problem = problem; + } + + View view() { + Theme theme = host.theme(); + LinearLayout page = theme.column(host); + page.setGravity(Gravity.CENTER); + page.setPadding(theme.dp(32), theme.dp(32), theme.dp(32), theme.dp(32)); + TextView title = theme.text(host, "LihonT Store", 30f, theme.onSurface, true); + title.setGravity(Gravity.CENTER); + page.addView(title); + TextView about = theme.text(host, "Рамки для аватарок и картинки для пузырей чата от тех, кто пользуется LihonT. " + + "Нажмите, и магазин попросит у TikTok только публичное: имя аккаунта и его номер. Пароль никому не передаётся.", + 15f, theme.muted, false); + about.setGravity(Gravity.CENTER); + about.setPadding(0, theme.dp(16), 0, theme.dp(24)); + page.addView(about); + if (problem != null) { + TextView warning = theme.text(host, problem, 14f, theme.danger, false); + warning.setGravity(Gravity.CENTER); + warning.setPadding(0, 0, 0, theme.dp(16)); + page.addView(warning); + } + TextView login = theme.button(host, "Войти через TikTok", true); + login.setOnClickListener(v -> host.startLogin()); + page.addView(login, new LinearLayout.LayoutParams(-2, -2)); + return page; + } +} diff --git a/src/lihonstore/app/MainActivity.java b/src/lihonstore/app/MainActivity.java new file mode 100644 index 0000000..b2b8029 --- /dev/null +++ b/src/lihonstore/app/MainActivity.java @@ -0,0 +1,307 @@ +package lihonstore.app; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ActivityNotFoundException; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowInsetsController; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * LihonT Store: the catalog of frames and chat bubbles that members make. The account comes from the TikTok that carries the LihonT mod + * (it hands over the public id and username and the secret of its installation, only to an app signed with the same key); the + * rest is the LihonT service. The bottom bar has the catalog, a button to publish something of one's own, and the profile. + */ +public final class MainActivity extends Activity { + static final String[] TIKTOK = {"com.zhiliaoapp.musically", "com.ss.android.ugc.trill", "online.lihon.tiktok"}; + private static final String LOGIN_ACTIVITY = "lihont.two.store.LoginActivity"; + private static final int REQUEST_LOGIN = 5101; + private static final int REQUEST_PICK = 5102; + + private Theme theme; + private Account account; + private final Set library = new HashSet(); + private FrameLayout content; + private LinearLayout bar; + private final List stack = new ArrayList(); + private View root; + private int tab = -1; + private PublishPage publishing; + + @Override protected void onCreate(Bundle state) { + super.onCreate(state); + theme = new Theme(this); + if (getActionBar() != null) getActionBar().hide(); // the screens draw their own titles + getWindow().setStatusBarColor(theme.background); + getWindow().setNavigationBarColor(theme.surface); + LinearLayout screen = theme.column(this); + screen.setBackgroundColor(theme.background); + screen.setFitsSystemWindows(true); + content = new FrameLayout(this); + screen.addView(content, new LinearLayout.LayoutParams(-1, 0, 1f)); + bar = theme.row(this); + bar.setBackgroundColor(theme.surface); + bar.setPadding(theme.dp(8), theme.dp(6), theme.dp(8), theme.dp(6)); + screen.addView(bar, new LinearLayout.LayoutParams(-1, -2)); + setContentView(screen); + // the window's controller exists only once the content is set + WindowInsetsController controller = getWindow().getInsetsController(); + if (controller != null && !theme.dark) { + controller.setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS | WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS, + WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS | WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS); + } + account = Account.get(this); + if (account == null) showLogin(null); + else start(); + } + + // ---- what the pages use ------------------------------------------------------------------------------------- + + Theme theme() { + return theme; + } + + Account account() { + return account; + } + + Set library() { + return library; + } + + void toast(String text) { + Toast.makeText(this, text, Toast.LENGTH_LONG).show(); + } + + // ---- login: the mod gives the account ---------------------------------------------------------------------- + + private Intent loginIntent() { + for (String pack : TIKTOK) { + Intent intent = new Intent().setClassName(pack, LOGIN_ACTIVITY); + if (getPackageManager().resolveActivity(intent, 0) != null) return intent; + } + return null; + } + + /** Shows the login screen; `problem` is what went wrong the last time, if anything. */ + void showLogin(String problem) { + bar.setVisibility(View.GONE); + stack.clear(); + setRoot(new LoginPage(this, problem).view()); + } + + void startLogin() { + Intent intent = loginIntent(); + if (intent == null) { + showLogin("Не нашли TikTok с модом LihonT. Установите его (версия с входом в магазин) и откройте TikTok один раз."); + return; + } + try { + startActivityForResult(intent, REQUEST_LOGIN); + } catch (ActivityNotFoundException | SecurityException refused) { + showLogin("TikTok не отдал данные аккаунта. Обновите мод до версии с магазином."); + } + } + + @Override protected void onActivityResult(int request, int result, Intent data) { + super.onActivityResult(request, result, data); + if (request == REQUEST_PICK) { + if (result == RESULT_OK && data != null && data.getData() != null && publishing != null) publishing.picked(data.getData()); + return; + } + if (request != REQUEST_LOGIN) return; + if (result != RESULT_OK || data == null) { + showLogin("Вход отменён или в TikTok никто не вошёл. Войдите в аккаунт в TikTok и повторите."); + return; + } + String uid = data.getStringExtra("uid"); + String name = data.getStringExtra("unique_id"); + String installation = data.getStringExtra("installation"); + if (!Account.valid(uid, installation) || name == null) { + showLogin("TikTok отдал странные данные. Обновите мод."); + return; + } + account = Account.save(this, uid, name, installation); + start(); + } + + void logout() { + Account.forget(this); + account = null; + library.clear(); + showLogin(null); + } + + /** After login (or at start): the account is proven to the service, the library is read and the catalog opens. */ + private void start() { + bar.setVisibility(View.VISIBLE); + buildBar(); + showTab(0); + proven(() -> Work.run(() -> Api.post("library", body()), new Work.Done() { + @Override public void ok(JSONObject reply) { + library.clear(); + for (Item item : Item.list(reply.optJSONArray("items"))) library.add(item.id); + } + + @Override public void failed(String message) { + // the catalog works without it + } + })); + } + + JSONObject body() { + try { + return new JSONObject().put("uid", account.uid).put("installation", account.installation).put("unique_id", account.uniqueId); + } catch (org.json.JSONException impossible) { + throw new IllegalStateException(impossible); + } + } + + /** + * Runs `then` once the service knows this installation as the holder of the account. The first time the account has to put a code + * in its public bio (the same proof the mod uses); the screen shows it and asks again. + */ + void proven(final Runnable then) { + Work.run(() -> Api.post("prove", body()), new Work.Done() { + @Override public void ok(JSONObject reply) { + if (reply.optBoolean("published", false)) { + then.run(); + return; + } + final String code = reply.optString("code", ""); + if (code.length() == 0) { + toast("Не удалось подтвердить аккаунт"); + return; + } + askCode(code, then); + } + + @Override public void failed(String message) { + toast(message); + } + }); + } + + private void askCode(final String code, final Runnable then) { + LinearLayout box = theme.column(this); + box.setPadding(theme.dp(24), theme.dp(8), theme.dp(24), 0); + TextView say = theme.text(this, "Чтобы публиковать и добавлять, подтвердите аккаунт: вставьте этот код в описание профиля TikTok, " + + "подождите минуту и нажмите «Проверить». Потом код можно убрать.", 14f, theme.onSurface, false); + TextView shown = theme.text(this, code, 22f, theme.accent, true); + shown.setGravity(Gravity.CENTER); + shown.setPadding(0, theme.dp(16), 0, theme.dp(8)); + box.addView(say); + box.addView(shown); + new AlertDialog.Builder(this).setTitle("Подтверждение аккаунта").setView(box) + .setPositiveButton("Проверить", (d, w) -> proven(then)) + .setNeutralButton("Скопировать код", (d, w) -> { + ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setPrimaryClip(ClipData.newPlainText("LihonT", code)); + toast("Код скопирован"); + }) + .setNegativeButton("Позже", null).show(); + } + + // ---- navigation ------------------------------------------------------------------------------------------- + + private void buildBar() { + bar.removeAllViews(); + String[] names = {"Каталог", "+", "Профиль"}; + for (int i = 0; i < names.length; i++) { + final int index = i; + TextView item = theme.text(this, names[i], i == 1 ? 24f : 14f, i == 1 ? theme.onAccent : (tab == i ? theme.accent : theme.muted), i == 1 || tab == i); + item.setGravity(Gravity.CENTER); + item.setClickable(true); + if (i == 1) { + item.setBackground(theme.round(theme.accent, 22)); + item.setPadding(theme.dp(22), theme.dp(4), theme.dp(22), theme.dp(6)); + LinearLayout.LayoutParams plus = new LinearLayout.LayoutParams(-2, -2); + plus.gravity = Gravity.CENTER; + bar.addView(item, plus); + } else { + item.setPadding(0, theme.dp(12), 0, theme.dp(12)); + bar.addView(item, new LinearLayout.LayoutParams(0, -2, 1f)); + } + item.setOnClickListener(v -> showTab(index)); + } + } + + void showTab(int index) { + if (account == null) return; + tab = index; + stack.clear(); + publishing = null; + View page; + if (index == 0) page = new CatalogPage(this).view(); + else if (index == 1) { + PublishPage publish = new PublishPage(this); + publishing = publish; + page = publish.view(); + } else page = new ProfilePage(this, account.uid, account.uniqueId, true).view(); + setRoot(page); + buildBar(); + } + + private void setRoot(View page) { + content.removeAllViews(); + root = page; + content.addView(page, new ViewGroup.LayoutParams(-1, -1)); + } + + void push(View page) { + stack.add(page); + content.removeAllViews(); + content.addView(page, new ViewGroup.LayoutParams(-1, -1)); + } + + void openItem(Item item) { + push(new ItemPage(this, item).view()); + } + + void openProfile(String uid, String name) { + push(new ProfilePage(this, uid, name, account != null && uid.equals(account.uid)).view()); + } + + void pickPicture() { + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.setType("image/*"); + intent.addCategory(Intent.CATEGORY_OPENABLE); + try { + startActivityForResult(intent, REQUEST_PICK); + } catch (ActivityNotFoundException none) { + toast("Не нашлось приложения для выбора фото"); + } + } + + @Override public void onBackPressed() { + if (stack.isEmpty()) { + super.onBackPressed(); + return; + } + stack.remove(stack.size() - 1); + content.removeAllViews(); + content.addView(stack.isEmpty() ? root : stack.get(stack.size() - 1), new ViewGroup.LayoutParams(-1, -1)); + } + + void back() { + onBackPressed(); + } +} diff --git a/src/lihonstore/app/Pictures.java b/src/lihonstore/app/Pictures.java new file mode 100644 index 0000000..0e1c854 --- /dev/null +++ b/src/lihonstore/app/Pictures.java @@ -0,0 +1,70 @@ +package lihonstore.app; + +import android.content.ContentResolver; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.net.Uri; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +/** Turning a picture the person chose into what the service takes: a frame (a ring) or a chat picture, as a PNG of at most 140 KB. */ +final class Pictures { + private static final int MAX_BYTES = 140 * 1024; + + private Pictures() {} + + static Bitmap decode(ContentResolver resolver, Uri uri, int limit) throws IOException { + BitmapFactory.Options bounds = new BitmapFactory.Options(); + bounds.inJustDecodeBounds = true; + try (InputStream in = resolver.openInputStream(uri)) { + BitmapFactory.decodeStream(in, null, bounds); + } + int sample = 1; + while (bounds.outWidth / (sample * 2) >= limit || bounds.outHeight / (sample * 2) >= limit) sample *= 2; + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inSampleSize = sample; + try (InputStream in = resolver.openInputStream(uri)) { + return BitmapFactory.decodeStream(in, null, options); + } + } + + /** Cut square, scaled to Cut.SIDE and, unless its middle is already see-through, cut into a ring. Null when it cannot be used. */ + static byte[] frame(Bitmap source) { + try { + int edge = Math.min(source.getWidth(), source.getHeight()); + if (edge < 16) return null; + Bitmap square = Bitmap.createBitmap(source, (source.getWidth() - edge) / 2, (source.getHeight() - edge) / 2, edge, edge); + Bitmap scaled = Bitmap.createScaledBitmap(square, Cut.SIDE, Cut.SIDE, true); + int[] pixels = new int[Cut.SIDE * Cut.SIDE]; + scaled.getPixels(pixels, 0, Cut.SIDE, 0, 0, Cut.SIDE, Cut.SIDE); + if (!Cut.seeThroughMiddle(pixels)) Cut.ring(pixels); + Bitmap result = Bitmap.createBitmap(pixels, Cut.SIDE, Cut.SIDE, Bitmap.Config.ARGB_8888); + return png(result); + } catch (Throwable unusable) { + return null; + } + } + + /** A chat picture: at most 512 pixels on the longer side, made smaller step by step until it fits the size limit. */ + static byte[] bubble(Bitmap source) { + try { + for (int side = 512; side >= 160; side = side * 3 / 4) { + int[] size = Cut.fit(source.getWidth(), source.getHeight(), side); + Bitmap scaled = size[0] == source.getWidth() ? source : Bitmap.createScaledBitmap(source, size[0], size[1], true); + byte[] data = png(scaled); + if (data != null && data.length <= MAX_BYTES) return data; + } + } catch (Throwable unusable) { + // falls through + } + return null; + } + + private static byte[] png(Bitmap bitmap) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); + return out.size() <= MAX_BYTES * 2 ? out.toByteArray() : null; + } +} diff --git a/src/lihonstore/app/ProfilePage.java b/src/lihonstore/app/ProfilePage.java new file mode 100644 index 0000000..c47887a --- /dev/null +++ b/src/lihonstore/app/ProfilePage.java @@ -0,0 +1,153 @@ +package lihonstore.app; + +import android.view.Gravity; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; + +/** + * A profile: the author's name and what they have published. For the signed-in account it is also "everything of mine": what is published, + * what waits for the check (or was not accepted, with the reason) and the library of what was added with "+". + */ +final class ProfilePage { + private final MainActivity host; + private final String uid; + private final String name; + private final boolean own; + private final LinearLayout page; + private final TextView totals; + private final List chips = new ArrayList(); + private final ItemGrid[] grids = new ItemGrid[3]; + + ProfilePage(final MainActivity host, String uid, String name, boolean own) { + this.host = host; + this.uid = uid; + this.name = name == null ? "" : name; + this.own = own; + Theme theme = host.theme(); + page = theme.column(host); + if (!own) { + TextView back = theme.text(host, "← Назад", 15f, theme.accent, true); + back.setPadding(theme.dp(20), theme.dp(16), 0, 0); + back.setClickable(true); + back.setOnClickListener(v -> host.back()); + page.addView(back); + } + LinearLayout head = theme.row(host); + head.setPadding(theme.dp(20), theme.dp(16), theme.dp(20), theme.dp(8)); + TextView avatar = theme.text(host, initial(this.name), 26f, theme.onAccent, true); + avatar.setGravity(Gravity.CENTER); + avatar.setBackground(theme.round(theme.accent, 32)); + head.addView(avatar, new LinearLayout.LayoutParams(theme.dp(64), theme.dp(64))); + LinearLayout words = theme.column(host); + words.setPadding(theme.dp(16), 0, 0, 0); + words.addView(theme.text(host, this.name.length() == 0 ? "Автор" : "@" + this.name, 22f, theme.onSurface, true)); + totals = theme.text(host, own ? "Это ваш профиль" : "", 13f, theme.muted, false); + words.addView(totals); + head.addView(words, new LinearLayout.LayoutParams(0, -2, 1f)); + page.addView(head); + if (own) { + LinearLayout chipsRow = theme.row(host); + chipsRow.setPadding(theme.dp(16), theme.dp(4), theme.dp(16), theme.dp(8)); + String[] titles = {"Опубликовано", "Проверка", "Библиотека"}; + for (int i = 0; i < titles.length; i++) { + final int index = i; + TextView chip = theme.chip(host, titles[i], false); + chip.setSingleLine(true); + chip.setPadding(theme.dp(6), theme.dp(8), theme.dp(6), theme.dp(8)); + chip.setOnClickListener(v -> select(index)); + // three chips share the width equally, so no title is ever squeezed into several lines + LinearLayout.LayoutParams gap = new LinearLayout.LayoutParams(0, -2, 1f); + gap.rightMargin = i < titles.length - 1 ? theme.dp(8) : 0; + chipsRow.addView(chip, gap); + chips.add(chip); + } + page.addView(chipsRow); + select(0); + TextView out = theme.button(host, "Сменить аккаунт", false); + out.setOnClickListener(v -> host.logout()); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); + params.setMargins(theme.dp(16), theme.dp(4), theme.dp(16), theme.dp(12)); + page.addView(out, params); + } else { + grids[0] = new ItemGrid(host, cursor -> { + JSONObject reply = Api.post("profile", with(cursor)); + return ItemGrid.Page.of(reply); + }, "Здесь пока ничего нет"); + page.addView(grids[0].view(), new LinearLayout.LayoutParams(-1, 0, 1f)); + grids[0].reload(); + loadTotals(); + } + } + + View view() { + return page; + } + + private static String initial(String name) { + return name.length() == 0 ? "?" : name.substring(0, 1).toUpperCase(java.util.Locale.ROOT); + } + + private JSONObject with(String cursor) { + try { + JSONObject request = new JSONObject().put("uid", uid); + if (cursor != null) request.put("cursor", cursor); + return request; + } catch (org.json.JSONException impossible) { + throw new IllegalStateException(impossible); + } + } + + private void loadTotals() { + Work.run(() -> Api.post("profile", with(null)), new Work.Done() { + @Override public void ok(JSONObject reply) { + JSONObject sums = reply.optJSONObject("totals"); + if (sums == null) return; + JSONObject frames = sums.optJSONObject("frame"); + JSONObject bubbles = sums.optJSONObject("bubble"); + int installs = (frames == null ? 0 : frames.optInt("installs")) + (bubbles == null ? 0 : bubbles.optInt("installs")); + totals.setText("Рамок: " + (frames == null ? 0 : frames.optInt("count")) + " · Пузырей: " + + (bubbles == null ? 0 : bubbles.optInt("count")) + " · Добавили: " + installs); + } + + @Override public void failed(String message) { + // the list below says what is wrong + } + }); + } + + private void select(int index) { + Theme theme = host.theme(); + for (int i = 0; i < chips.size(); i++) { + boolean selected = i == index; + TextView chip = chips.get(i); + chip.setTextColor(selected ? theme.onAccent : theme.onSurface); + chip.setTypeface(selected ? android.graphics.Typeface.DEFAULT_BOLD : android.graphics.Typeface.DEFAULT); + chip.setBackground(theme.round(selected ? theme.accent : theme.surfaceHigh, 20)); + } + // the grid sits after the head and the chips; it is replaced when another chip is chosen + if (page.getChildCount() > 2 && page.getChildAt(2) instanceof android.widget.ScrollView) page.removeViewAt(2); + if (grids[index] == null) { + final String mode = index == 0 ? "published" : index == 1 ? "pending" : "library"; + grids[index] = new ItemGrid(host, cursor -> { + if ("library".equals(mode)) { + return new ItemGrid.Page(Item.list(Api.post("library", host.body()).optJSONArray("items")), null); + } + JSONObject reply = Api.post("mine", host.body()); + List picked = new ArrayList(); + for (Item item : Item.list(reply.optJSONArray("items"))) { + boolean live = "approved".equals(item.status) && item.listed; + if ("published".equals(mode) ? live : !live && !"approved".equals(item.status)) picked.add(item); + } + return new ItemGrid.Page(picked, null); + }, index == 0 ? "Вы ещё ничего не опубликовали" : index == 1 ? "Ничего не ждёт проверки" : "Вы ещё ничего не добавили через «+»"); + grids[index].reload(); + } + page.addView(grids[index].view(), 2, new LinearLayout.LayoutParams(-1, 0, 1f)); + } +} diff --git a/src/lihonstore/app/PublishPage.java b/src/lihonstore/app/PublishPage.java new file mode 100644 index 0000000..2134926 --- /dev/null +++ b/src/lihonstore/app/PublishPage.java @@ -0,0 +1,202 @@ +package lihonstore.app; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.net.Uri; +import android.text.InputFilter; +import android.view.View; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import org.json.JSONObject; + +import java.io.IOException; + +/** + * The "+" of the bottom bar: choose what it is (a frame or a chat bubble), a picture, a name and a description, and publish. A picture + * that is not a frame is cut into a ring here, the same way the mod does it. It goes to the AI and then to the owner before anyone sees it. + */ +final class PublishPage { + private final MainActivity host; + private final ScrollView scroll; + private final TextView frameChip; + private final TextView bubbleChip; + private final ArtView preview; + private final EditText name; + private final EditText description; + private final TextView send; + private final TextView hint; + private boolean frame = true; + private byte[] png; + private Bitmap source; + private int previews; + + PublishPage(final MainActivity host) { + this.host = host; + Theme theme = host.theme(); + scroll = new ScrollView(host); + LinearLayout page = theme.column(host); + page.setPadding(theme.dp(20), theme.dp(16), theme.dp(20), theme.dp(24)); + scroll.addView(page); + page.addView(theme.text(host, "Опубликовать", 26f, theme.onSurface, true)); + TextView about = theme.text(host, "Сначала картинку проверит ИИ, потом модератор. Пока не примут, её никто не увидит.", 14f, theme.muted, false); + about.setPadding(0, theme.dp(4), 0, theme.dp(12)); + page.addView(about); + + LinearLayout chips = theme.row(host); + frameChip = theme.chip(host, "Рамка", true); + bubbleChip = theme.chip(host, "Пузырь чата", false); + frameChip.setOnClickListener(v -> kind(true)); + bubbleChip.setOnClickListener(v -> kind(false)); + LinearLayout.LayoutParams gap = new LinearLayout.LayoutParams(-2, -2); + gap.rightMargin = theme.dp(8); + chips.addView(frameChip, gap); + chips.addView(bubbleChip); + page.addView(chips); + + preview = new ArtView(host, theme); + LinearLayout.LayoutParams previewParams = new LinearLayout.LayoutParams(-1, theme.dp(220)); + previewParams.topMargin = theme.dp(16); + page.addView(preview, previewParams); + hint = theme.text(host, "", 13f, theme.muted, false); + hint.setPadding(0, theme.dp(8), 0, theme.dp(8)); + page.addView(hint); + + TextView choose = theme.button(host, "Выбрать картинку", false); + choose.setOnClickListener(v -> host.pickPicture()); + page.addView(choose, new LinearLayout.LayoutParams(-1, -2)); + + name = field(theme, "Название", 30, false); + description = field(theme, "Описание (необязательно)", 200, true); + page.addView(name, fieldParams(theme)); + page.addView(description, fieldParams(theme)); + + send = theme.button(host, "Опубликовать", true); + send.setOnClickListener(v -> publish()); + LinearLayout.LayoutParams sendParams = new LinearLayout.LayoutParams(-1, -2); + sendParams.topMargin = theme.dp(20); + page.addView(send, sendParams); + kind(true); + } + + View view() { + return scroll; + } + + private EditText field(Theme theme, String label, int limit, boolean multiline) { + EditText field = new EditText(host); + field.setHint(label); + field.setHintTextColor(theme.muted); + field.setTextColor(theme.onSurface); + field.setFilters(new InputFilter[] {new InputFilter.LengthFilter(limit)}); + field.setBackground(theme.round(theme.surfaceHigh, 14)); + field.setPadding(theme.dp(16), theme.dp(12), theme.dp(16), theme.dp(12)); + if (multiline) { + field.setMinLines(2); + field.setGravity(android.view.Gravity.TOP); + } else { + field.setSingleLine(true); + } + return field; + } + + private LinearLayout.LayoutParams fieldParams(Theme theme) { + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); + params.topMargin = theme.dp(12); + return params; + } + + private void kind(boolean isFrame) { + frame = isFrame; + Theme theme = host.theme(); + paint(frameChip, isFrame, theme); + paint(bubbleChip, !isFrame, theme); + hint.setText(isFrame ? "Рамка: фото само вырежется в кольцо вокруг аватарки. Лучше всего подходит картинка с прозрачной серединой." + : "Пузырь: картинка станет фоном сообщений. Подойдёт любая, до 512 пикселей по длинной стороне."); + if (source != null) render(); + else preview.show(null, frame); + } + + private void paint(TextView chip, boolean selected, Theme theme) { + chip.setTextColor(selected ? theme.onAccent : theme.onSurface); + chip.setTypeface(selected ? android.graphics.Typeface.DEFAULT_BOLD : android.graphics.Typeface.DEFAULT); + chip.setBackground(theme.round(selected ? theme.accent : theme.surfaceHigh, 20)); + } + + /** The picture the person chose: it is made ready on a background thread and shown on the preview. */ + void picked(final Uri uri) { + Work.run(() -> { + try { + Bitmap bitmap = Pictures.decode(host.getContentResolver(), uri, 1024); + if (bitmap == null) throw new Api.Failure("Это не картинка"); + return bitmap; + } catch (IOException | RuntimeException | OutOfMemoryError unreadable) { + throw new Api.Failure("Не удалось открыть эту картинку"); + } + }, new Work.Done() { + @Override public void ok(Bitmap bitmap) { + source = bitmap; + render(); + } + + @Override public void failed(String message) { + host.toast(message); + } + }); + } + + private void render() { + byte[] made = frame ? Pictures.frame(source) : Pictures.bubble(source); + png = made; + if (made == null) { + host.toast("Эту картинку нельзя использовать"); + return; + } + Bitmap shown = BitmapFactory.decodeByteArray(made, 0, made.length); + String id = "local" + (previews++); + Images.put(id, shown); + preview.show(id, frame); + } + + private void publish() { + if (png == null) { + host.toast("Сначала выберите картинку"); + return; + } + if (name.getText().toString().trim().length() == 0) { + host.toast("Назовите её"); + return; + } + final byte[] data = png; + final boolean isFrame = frame; + final String title = name.getText().toString().trim(); + final String about = description.getText().toString().trim(); + send.setEnabled(false); + host.proven(() -> Work.run(() -> { + JSONObject request = host.body(); + try { + request.put("kind", isFrame ? "frame" : "bubble").put("name", title).put("description", about) + .put("png", android.util.Base64.encodeToString(data, android.util.Base64.NO_WRAP)); + } catch (org.json.JSONException impossible) { + throw new IllegalStateException(impossible); + } + return Api.post("publish", request); + }, new Work.Done() { + @Override public void ok(JSONObject reply) { + send.setEnabled(true); + String status = reply.optString("status", "new"); + host.toast("approved".equals(status) ? "Уже принято: смотрите в каталоге" + : "Отправлено на проверку. Статус смотрите в профиле: «Проверка»"); + host.showTab(2); + } + + @Override public void failed(String message) { + send.setEnabled(true); + host.toast(message); + } + })); + send.postDelayed(() -> send.setEnabled(true), 4000L); + } +} diff --git a/src/lihonstore/app/Texts.java b/src/lihonstore/app/Texts.java new file mode 100644 index 0000000..ae350b4 --- /dev/null +++ b/src/lihonstore/app/Texts.java @@ -0,0 +1,38 @@ +package lihonstore.app; + +/** The service answers in English; the screens speak Russian. */ +final class Texts { + private Texts() {} + + static String error(String message) { + if (message == null || message.length() == 0) return "Что-то пошло не так"; + if (message.startsWith("Prove the account")) return "Аккаунт ещё не подтверждён"; + if (message.startsWith("Too many pictures")) return "Слишком много картинок ждут проверки, попробуйте позже"; + if (message.startsWith("This picture is already taken")) return "Такая картинка уже есть у другого автора"; + if (message.startsWith("The picture is too")) return "Картинка слишком большая или сложная"; + if (message.startsWith("Not a picture")) return "Это не картинка"; + if (message.startsWith("Unknown item")) return "Такой вещи нет"; + if (message.startsWith("Account excluded")) return "Аккаунт исключён"; + if (message.startsWith("Try again later")) return "Слишком часто, подождите немного"; + if (message.startsWith("Could not read the TikTok profile")) return "Не удалось прочитать профиль TikTok, попробуйте позже"; + if (message.startsWith("Profile not found")) return "Профиль не найден"; + if (message.startsWith("That profile belongs")) return "Это профиль другого аккаунта"; + return message; + } + + static String kind(String kind) { + return "frame".equals(kind) ? "Рамка" : "Пузырь"; + } + + static String status(String status) { + if ("approved".equals(status)) return "Принято"; + if ("rejected".equals(status)) return "Не принято"; + return "На проверке"; + } + + static String reason(String reason) { + if (reason == null || reason.length() == 0) return ""; + if (reason.startsWith("ai: ")) return "ИИ: " + reason.substring(4); + return "модератор"; + } +} diff --git a/src/lihonstore/app/Theme.java b/src/lihonstore/app/Theme.java new file mode 100644 index 0000000..fd6c24a --- /dev/null +++ b/src/lihonstore/app/Theme.java @@ -0,0 +1,103 @@ +package lihonstore.app; + +import android.content.Context; +import android.content.res.Configuration; +import android.graphics.Color; +import android.graphics.drawable.GradientDrawable; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.TextView; + +/** Colours from the phone's own palette (Material You, dark or light) and the few widgets the screens are made of. */ +final class Theme { + final boolean dark; + final int background; + final int surface; + final int surfaceHigh; + final int onSurface; + final int muted; + final int accent; + final int onAccent; + final int accentSoft; + final int onAccentSoft; + final int danger; + private final float density; + + Theme(Context context) { + dark = (context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES; + density = context.getResources().getDisplayMetrics().density; + android.content.res.Resources.Theme t = context.getTheme(); + android.content.res.Resources r = context.getResources(); + background = dark ? r.getColor(android.R.color.system_neutral1_900, t) : r.getColor(android.R.color.system_neutral1_10, t); + surface = dark ? r.getColor(android.R.color.system_neutral1_800, t) : r.getColor(android.R.color.system_neutral1_50, t); + surfaceHigh = dark ? r.getColor(android.R.color.system_neutral1_700, t) : r.getColor(android.R.color.system_neutral1_100, t); + onSurface = dark ? r.getColor(android.R.color.system_neutral1_50, t) : r.getColor(android.R.color.system_neutral1_900, t); + muted = dark ? r.getColor(android.R.color.system_neutral2_300, t) : r.getColor(android.R.color.system_neutral2_600, t); + accent = dark ? r.getColor(android.R.color.system_accent1_200, t) : r.getColor(android.R.color.system_accent1_600, t); + onAccent = dark ? r.getColor(android.R.color.system_accent1_800, t) : r.getColor(android.R.color.system_accent1_0, t); + accentSoft = dark ? r.getColor(android.R.color.system_accent1_700, t) : r.getColor(android.R.color.system_accent1_100, t); + onAccentSoft = dark ? r.getColor(android.R.color.system_accent1_100, t) : r.getColor(android.R.color.system_accent1_900, t); + danger = dark ? Color.rgb(0xF2, 0xB8, 0xB5) : Color.rgb(0xB3, 0x26, 0x1E); + } + + int dp(float value) { + return Math.round(value * density); + } + + GradientDrawable round(int color, float radiusDp) { + GradientDrawable shape = new GradientDrawable(); + shape.setColor(color); + shape.setCornerRadius(dp(radiusDp)); + return shape; + } + + TextView text(Context context, String text, float sp, int color, boolean bold) { + TextView view = new TextView(context); + view.setText(text); + view.setTextSize(sp); + view.setTextColor(color); + if (bold) view.setTypeface(android.graphics.Typeface.DEFAULT_BOLD); + return view; + } + + /** A filled button (the main action) or a quiet one. */ + TextView button(Context context, String label, boolean filled) { + TextView view = text(context, label, 15f, filled ? onAccent : onAccentSoft, true); + view.setGravity(Gravity.CENTER); + view.setPadding(dp(20), dp(12), dp(20), dp(12)); + view.setBackground(round(filled ? accent : accentSoft, 24)); + view.setClickable(true); + return view; + } + + /** A chip: selected ones are filled with the accent. */ + TextView chip(Context context, String label, boolean selected) { + TextView view = text(context, label, 14f, selected ? onAccent : onSurface, selected); + view.setGravity(Gravity.CENTER); + view.setPadding(dp(16), dp(8), dp(16), dp(8)); + view.setBackground(round(selected ? accent : surfaceHigh, 20)); + view.setClickable(true); + return view; + } + + LinearLayout column(Context context) { + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + return layout; + } + + LinearLayout row(Context context) { + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.HORIZONTAL); + layout.setGravity(Gravity.CENTER_VERTICAL); + return layout; + } + + View spacer(Context context, int heightDp) { + View view = new View(context); + view.setLayoutParams(new ViewGroup.LayoutParams(1, dp(heightDp))); + return view; + } +} diff --git a/src/lihonstore/app/Work.java b/src/lihonstore/app/Work.java new file mode 100644 index 0000000..64aab63 --- /dev/null +++ b/src/lihonstore/app/Work.java @@ -0,0 +1,46 @@ +package lihonstore.app; + +import android.os.Handler; +import android.os.Looper; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** A task off the main thread whose result (or failure) comes back on it. */ +final class Work { + interface Done { + void ok(T value); + + void failed(String message); + } + + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + private static final ExecutorService POOL = Executors.newFixedThreadPool(2); + + private Work() {} + + static void run(final Callable task, final Done done) { + POOL.execute(new Runnable() { + @Override public void run() { + T value = null; + String error = null; + try { + value = task.call(); + } catch (Api.Failure failure) { + error = failure.getMessage(); + } catch (Exception other) { + error = "Что-то пошло не так"; + } + final T result = value; + final String message = error; + MAIN.post(new Runnable() { + @Override public void run() { + if (message != null) done.failed(message); + else done.ok(result); + } + }); + } + }); + } +} diff --git a/tests/lihonstore/app/CutTest.java b/tests/lihonstore/app/CutTest.java new file mode 100644 index 0000000..79b7e71 --- /dev/null +++ b/tests/lihonstore/app/CutTest.java @@ -0,0 +1,49 @@ +package lihonstore.app; + +import java.util.Arrays; + +/** The pixel maths of the store's frames on a plain JVM. Usage: CutTest scenario; prints "PASS scenario". */ +public final class CutTest { + private CutTest() {} + + public static void main(String[] args) { + switch (args[0]) { + case "ring": ring(); break; + case "fit": fit(); break; + default: throw new IllegalArgumentException(args[0]); + } + System.out.println("PASS " + args[0]); + } + + private static void check(boolean ok, String what) { + if (!ok) throw new AssertionError(what); + } + + private static void ring() { + int side = Cut.SIDE; + int[] solid = new int[side * side]; + Arrays.fill(solid, 0xFFCC3322); + check(!Cut.seeThroughMiddle(solid), "a solid picture is not a frame yet"); + Cut.ring(solid); + check((solid[(side / 2) * side + side / 2] >>> 24) == 0, "the middle is a hole"); + check((solid[0] >>> 24) == 0, "the corner is cut off"); + check((solid[(side / 2) * side + (side - 12)] >>> 24) == 255, "the ring itself is kept"); + check(Cut.seeThroughMiddle(solid), "a ring is a frame"); + int[] before = solid.clone(); + if (!Cut.seeThroughMiddle(solid)) Cut.ring(solid); + check(Arrays.equals(before, solid), "a frame is left as it is"); + // the colour of what is kept does not change, only its opacity + int[] one = new int[side * side]; + Arrays.fill(one, 0xFF123456); + Cut.ring(one); + check((one[(side / 2) * side + (side - 12)] & 0x00FFFFFF) == 0x123456, "colour kept"); + } + + private static void fit() { + check(Arrays.equals(Cut.fit(100, 80, 512), new int[] {100, 80}), "small pictures are not enlarged"); + check(Arrays.equals(Cut.fit(1024, 512, 512), new int[] {512, 256}), "the longer side is scaled to the limit"); + check(Arrays.equals(Cut.fit(500, 2000, 512), new int[] {128, 512}), "tall pictures too"); + int[] thin = Cut.fit(10000, 3, 512); + check(thin[0] == 512 && thin[1] >= 3, "never a zero side"); + } +} diff --git a/tests/test_cut.py b/tests/test_cut.py new file mode 100644 index 0000000..e195b91 --- /dev/null +++ b/tests/test_cut.py @@ -0,0 +1,39 @@ +"""The picture maths of LihonT Store (a photo becomes a ring, pictures are fitted) on a real JVM. Needs a JDK: py -m unittest discover tests""" + +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +CUT = ROOT / "src" / "lihonstore" / "app" / "Cut.java" +CASE = ROOT / "tests" / "lihonstore" / "app" / "CutTest.java" + + +class CutTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.javac, cls.java = shutil.which("javac"), shutil.which("java") + if not cls.javac or not cls.java: + raise RuntimeError("these tests need a JDK") + cls.temporary = tempfile.TemporaryDirectory(prefix="lihonstore-tests-") + cls.addClassCleanup(cls.temporary.cleanup) + cls.classes = Path(cls.temporary.name) + done = subprocess.run([cls.javac, "-encoding", "UTF-8", "-d", str(cls.classes), str(CUT), str(CASE)], capture_output=True, text=True) + if done.returncode != 0: + raise RuntimeError(done.stdout + done.stderr) + + def scenario(self, name): + done = subprocess.run([self.java, "-cp", str(self.classes), "lihonstore.app.CutTest", name], capture_output=True, text=True, timeout=60) + self.assertEqual(done.stdout.strip(), "PASS " + name, done.stdout + done.stderr) + + def test_a_photo_becomes_a_ring_and_a_frame_is_kept(self): + self.scenario("ring") + + def test_pictures_are_fitted_without_enlarging(self): + self.scenario("fit") + + +if __name__ == "__main__": + unittest.main()