Files
LihonT/src/lihont/two/avatar/PairPictures.java
cheb0chik 9de69113b5 LihonT 2 Serena
LihonT Store: a separate app with a catalog of avatar frames and chat bubbles made by members (browse, add with "+", author
profiles, publishing), signed in through the TikTok that carries the mod (an exported no-window activity that answers only the
store, checked by package name and signing key). The mod gets frames made from any picture (a photo is cut into a ring), the
library of the store in the frame picker and for bubbles, other members' published bubbles and one picture per chat for both
people. The members service gets the catalog, the account library, uploads that are re-made with Pillow, an AI first pass
(Groq) and the owner's Telegram bot with accept and reject buttons. The build tools pass long file lists through an argument
file. Nothing a member sends is shown to others before it is approved.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 15:56:00 +03:00

301 lines
15 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package lihont.two.avatar;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import lihont.two.account.CurrentAccount;
import lihont.two.badge.NicheClaim;
import lihont.two.frame.FrameStore;
/**
* One picture for the chat between two accounts, the same on both phones: whichever of the two chose it, both see it behind the
* bubbles once it has been approved. The picture lives on the members service (asked about at most every few minutes, and only by
* one of the two accounts); the phone keeps the pictures it has seen under their checksums and the answer, so a chat dresses
* itself at once and without a network.
*
* A picture the member has just sent is shown to them straight away, before it is approved, for a few days.
*/
public final class PairPictures {
private static final String ART = "https://lihont.space/members/v1/art/";
private static final String PREFS = "lihont_pair_pictures";
private static final long CHECK_MS = 10L * 60L * 1000L;
private static final long PENDING_MS = 3L * 24L * 3600L * 1000L;
private static final int MAX_BYTES = 150 * 1024;
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 static final Set<String> FETCHING = new HashSet<String>();
private static final Map<String, Bitmap> BITMAPS = new LinkedHashMap<String, Bitmap>(4, 0.75f, true) {
@Override protected boolean removeEldestEntry(Map.Entry<String, Bitmap> eldest) {
return size() > 4;
}
};
private PairPictures() {}
/** The picture of the chat with `peerUid` for the signed-in account, or null (none chosen, not approved, or not fetched 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(context.getApplicationContext() != null ? context.getApplicationContext() : 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) {
hex = pending(prefs, key);
if (hex == null) return null;
}
Bitmap cached = BITMAPS.get(hex);
if (cached != null) return cached;
File file = new File(folder(context), hex + ".png");
if (file.isFile()) {
Bitmap decoded = BitmapFactory.decodeFile(file.getPath());
if (decoded != null) BITMAPS.put(hex, decoded);
return decoded;
}
fetch(context.getApplicationContext() != null ? context.getApplicationContext() : context, hex);
return null;
}
/** The picture with this id (24 hex digits) when it is on the phone, else null and it is fetched in the background. */
public static synchronized Bitmap artBitmap(Context context, String hex) {
if (hex == null || !hex.matches("[0-9a-f]{24}")) return null;
Bitmap cached = BITMAPS.get(hex);
if (cached != null) return cached;
File file = new File(folder(context), hex + ".png");
if (file.isFile()) {
Bitmap decoded = BitmapFactory.decodeFile(file.getPath());
if (decoded != null) BITMAPS.put(hex, decoded);
return decoded;
}
fetch(context.getApplicationContext() != null ? context.getApplicationContext() : context, hex);
return null;
}
/** The same, but fetched now on the calling thread (which must not be the main one); null when it cannot be had. */
public static Bitmap fetchNow(Context context, String hex) {
try {
File file = new File(folder(context), hex + ".png");
if (!file.isFile()) {
byte[] data = get(ART + hex + ".png");
if (data.length == 0 || !FrameStore.sha256(data).startsWith(hex)) return null;
save(context, hex, data);
}
return BitmapFactory.decodeFile(file.getPath());
} catch (Exception unreachable) {
return null;
}
}
private static String pending(SharedPreferences prefs, String key) {
long at = prefs.getLong("pending_at_" + key, 0L);
String hex = prefs.getString("pending_" + key, "");
return hex.length() == 0 || System.currentTimeMillis() - at > PENDING_MS ? null : hex;
}
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);
}
private static File folder(Context context) {
File folder = new File(context.getFilesDir(), "lihont-pair-pictures");
if (!folder.isDirectory()) folder.mkdirs();
return folder;
}
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("pair_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 = "";
synchronized (PairPictures.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();
}
} catch (Exception unreachable) {
// the last answer stays
}
}
}, "lihont-pair-lookup").start();
}
private static void fetch(final Context context, final String hex) {
if (!FETCHING.add(hex)) return;
new Thread(new Runnable() {
@Override public void run() {
try {
byte[] data = get(ART + hex + ".png");
if (data.length > 0 && FrameStore.sha256(data).startsWith(hex)) save(context, hex, data);
} catch (Exception unreachable) {
// not approved yet, or no network: asked again on a later frame of the chat
} finally {
synchronized (PairPictures.class) {
FETCHING.remove(hex);
}
}
}
}, "lihont-pair-art").start();
}
private 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)) {
out.write(data);
}
if (!part.renameTo(new File(folder, hex + ".png"))) throw new IOException("rename");
File[] files = folder.listFiles();
if (files != null && files.length > 40) {
java.util.Arrays.sort(files, new java.util.Comparator<File>() {
@Override public int compare(File a, File b) {
return Long.compare(a.lastModified(), b.lastModified());
}
});
for (int i = 0; i < files.length - 40; i++) if (!files[i].getName().equals(hex + ".png")) files[i].delete();
}
}
private static byte[] get(String address) throws IOException {
URL url = new URL(address);
if (!"https".equals(url.getProtocol())) throw new IOException("not https");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(6000);
connection.setReadTimeout(15000);
connection.setInstanceFollowRedirects(false);
try {
if (connection.getResponseCode() != 200) throw new IOException("status " + connection.getResponseCode());
try (InputStream in = connection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) >= 0) {
out.write(buffer, 0, count);
if (out.size() > MAX_BYTES) throw new IOException("too large");
}
return out.toByteArray();
}
} finally {
connection.disconnect();
}
}
/** Sends the picture for the chat with `peerUid` to be checked; 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 = context.getApplicationContext() != null ? context.getApplicationContext() : context;
new Thread(new Runnable() {
@Override public void run() {
ShapePublisher.Result result;
try {
JSONObject reply = lihont.two.badge.MemberClient.post("bubble_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 (PairPictures.class) {
save(app, id, png);
BITMAPS.remove(id);
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, error.getMessage() == null ? "Нет связи с сервером" : error.getMessage());
}
final ShapePublisher.Result outcome = result;
MAIN.post(new Runnable() {
@Override public void run() {
callback.done(outcome);
}
});
}
}, "lihont-pair-upload").start();
}
/** Takes the shared picture of the chat 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 = context.getApplicationContext() != null ? context.getApplicationContext() : 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("pair_clear", new JSONObject()
.put("uid", mine).put("peer", peerUid).put("installation", Installation.secret(app)));
String key = key(mine, peerUid);
synchronized (PairPictures.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, error.getMessage() == null ? "Нет связи с сервером" : error.getMessage());
}
final ShapePublisher.Result outcome = result;
MAIN.post(new Runnable() {
@Override public void run() {
callback.done(outcome);
}
});
}
}, "lihont-pair-clear").start();
}
}