51 lines
2.3 KiB
TypeScript
51 lines
2.3 KiB
TypeScript
// User interface language (PEP-98): `settings` `user.locale:<id>`, no column. Missing = Russian.
|
|
import { chats, projects, users, type Db } from "@peppa/db";
|
|
import { isLocale, normalizeLocale, type Locale } from "@peppa/shared/i18n";
|
|
import { eq } from "drizzle-orm";
|
|
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
|
|
|
const key = (userId: number) => `user.locale:${userId}`;
|
|
|
|
/** The language the user picked, or null when never chosen. */
|
|
export async function getUserLocaleSetting(db: Db, userId: number): Promise<Locale | null> {
|
|
const v = await getSetting<string>(db, key(userId));
|
|
return isLocale(v) ? v : null;
|
|
}
|
|
|
|
export async function getUserLocale(db: Db, userId: number): Promise<Locale> {
|
|
return normalizeLocale(await getUserLocaleSetting(db, userId));
|
|
}
|
|
|
|
export async function setUserLocale(db: Db, userId: number, locale: Locale | null): Promise<void> {
|
|
if (locale == null) await deleteSetting(db, key(userId));
|
|
else if (isLocale(locale)) await setSetting(db, key(userId), locale);
|
|
else throw new Error("Неизвестный язык");
|
|
}
|
|
|
|
const chatCache = new Map<number, { locale: Locale; at: number }>();
|
|
|
|
/** Language of the reader of a Telegram chat: the paired user, or for a linked group the user who linked it; Russian otherwise. */
|
|
export async function telegramChatLocale(db: Db, chatId: number, now = Date.now()): Promise<Locale> {
|
|
const hit = chatCache.get(chatId);
|
|
if (hit && now - hit.at < 60_000) return hit.locale;
|
|
const [u] = await db.select({ id: users.id }).from(users).where(eq(users.telegramChatId, chatId));
|
|
let userId: number | null = u?.id ?? null;
|
|
if (userId == null) {
|
|
// A linked group (PEP-62): the language of the user who linked it, else the project owner.
|
|
const [g] = await db
|
|
.select({ by: chats.tgLinkedBy, owner: projects.ownerId, master: chats.userId })
|
|
.from(chats)
|
|
.leftJoin(projects, eq(projects.id, chats.projectId))
|
|
.where(eq(chats.tgChatId, chatId));
|
|
userId = g ? (g.by ?? g.owner ?? g.master ?? null) : null;
|
|
}
|
|
const locale = userId != null ? await getUserLocale(db, userId) : "ru";
|
|
chatCache.set(chatId, { locale, at: now });
|
|
return locale;
|
|
}
|
|
|
|
/** Forget cached chat languages (after the user changes theirs). */
|
|
export function forgetChatLocales(): void {
|
|
chatCache.clear();
|
|
}
|