Cotton code
273 lines · 13.3 KB · TypeScriptRaw
/** * The reads the import engine asks the object — the port of the Rust * engine's driver (`ImportDriver` + `ContactDriver`, answered on the Mac by * `messages_import::FileContacts`). One method per QUESTION, each a fixed * statement over the object's `rows`, so the engine never composes one. The * personal tables hold the Rust tables' columns under the storage map's names * (`cotton_msg_threads` → `thread`, …); there is one database per object, so * the Rust statements' workspace filter has nothing left to filter. A list of * ids is bound as ONE JSON parameter (`IN (SELECT value FROM json_each(?))`): * a Durable Object's SQLite takes at most 100 bound parameters, and a batch * asks about 500 ids at once. */import type { Store } from "../store.ts";import type { HandleKind } from "./handles.ts";import { normalizePhone, regionOf, type Region } from "./phone.ts";const j = (column: string): string => `json_extract(data, '$.${column}')`;const LIVE = (table: string): string => `table_id = '${table}' AND deleted = 0`;/** * A person an import may name, as row `p`: held (never a tombstone, `deleted = * 1`), not in the bin (`trashed_at`: merge_people bins the duplicate it folds * away) and not archived. A binned or merged duplicate is never matched again, * so nothing is pointed back at it. */export const LIVE_PERSON = (p: string): string =>  `${p}.table_id = 'person' AND ${p}.deleted = 0 AND json_extract(${p}.data, '$.trashed_at') IS NULL AND json_extract(${p}.data, '$.archived_at') IS NULL`;/** A contact's person, only while that person is one an import may name ([`LIVE_PERSON`]). */const CONTACT_PERSON = (c: string): string =>  `(SELECT p.id FROM rows p WHERE ${LIVE_PERSON("p")} AND p.id = json_extract(${c}.data, '$.person_id'))`;export interface ContactRow {  id: string;  display_name: string | null;  person_id: string | null;}export interface ParticipantRow {  id: string;  contact_id: string | null;  display_name: string | null;}export interface ThreadHit {  id: string;  contact_id: string | null;}export interface MinuteRow {  id: string;  external_id: string | null;  direction: string;  body: string | null;  meta: unknown;}export interface BareRow {  id: string;  external_id: string;  body: string | null;  meta: unknown;}export interface ChangeTarget {  id: string;  thread_id: string;  meta: Record<string, unknown>;  media: unknown;  newest: boolean;}type Text = string | null;/** A JSON column read through `json_extract` comes back as text; anything else is what it is. */function parsed(value: unknown): unknown {  if (typeof value !== "string") return value;  try {    return JSON.parse(value);  } catch {    return value;  }}/** The change lookup — (external id, channel) — a statement of its own so a test can ask SQLite which index answers it. */export const MESSAGE_BY_EXTERNAL_ID_SQL = `SELECT m.id AS id, json_extract(m.data, '$.thread_id') AS thread_id, json_extract(m.data, '$.meta') AS meta, json_extract(m.data, '$.media') AS media,        (json_extract(t.data, '$.last_message_at') IS json_extract(m.data, '$.sent_at')) AS newest   FROM rows m LEFT JOIN rows t ON t.table_id = 'thread' AND t.deleted = 0 AND t.id = json_extract(m.data, '$.thread_id')  WHERE m.table_id = 'message' AND m.deleted = 0 AND json_extract(m.data, '$.external_id') = ? AND json_extract(m.data, '$.channel') = ?  ORDER BY json_extract(m.data, '$.sent_at') DESC LIMIT 1`;export class Reader {  private readonly store: Store;  private readonly ownerPhone: string | null;  constructor(store: Store, ownerPhone: string | null) {    this.store = store;    this.ownerPhone = ownerPhone;  }  /** Every person handle of a kind, with its person: archived and binned people are left out. */  peopleHandles(kind: HandleKind): { id: string; full_name: Text; value: unknown }[] {    return this.store.query<{ id: string; full_name: Text; value: string }>(      `SELECT p.id AS id, json_extract(p.data, '$.full_name') AS full_name, json_extract(h.data, '$.normalised') AS value         FROM rows h JOIN rows p ON ${LIVE_PERSON("p")} AND p.id = json_extract(h.data, '$.person_id')        WHERE h.table_id = 'person_handle' AND h.deleted = 0 AND json_extract(h.data, '$.kind') = ?`,      kind,    );  }  contactByHandle(kind: HandleKind, value: string): ContactRow | null {    return (      this.store.query<{ id: string; display_name: Text; person_id: Text }>(        `SELECT c.id AS id, json_extract(c.data, '$.display_name') AS display_name, ${CONTACT_PERSON("c")} AS person_id           FROM rows h JOIN rows c ON c.table_id = 'message_contact' AND c.deleted = 0 AND c.id = json_extract(h.data, '$.contact_id')          WHERE h.table_id = 'message_contact_handle' AND h.deleted = 0 AND json_extract(h.data, '$.value') = ? AND json_extract(h.data, '$.kind') = ?          ORDER BY h.created_at, h.id LIMIT 1`,        value,        kind,      )[0] ?? null    );  }  contactByPhone(phone: string): ContactRow | null {    return (      this.store.query<{ id: string; display_name: Text; person_id: Text }>(        `SELECT c.id AS id, json_extract(c.data, '$.display_name') AS display_name, ${CONTACT_PERSON("c")} AS person_id           FROM rows c WHERE c.table_id = 'message_contact' AND c.deleted = 0 AND json_extract(c.data, '$.phone_e164') = ? ORDER BY c.created_at, c.id LIMIT 1`,        phone,      )[0] ?? null    );  }  dmThreadForContact(contactId: string): string | null {    return this.store.query<{ id: string }>(`SELECT id FROM rows WHERE ${LIVE("thread")} AND ${j("contact_id")} = ? AND ${j("kind")} = 'dm' ORDER BY created_at, id LIMIT 1`, contactId)[0]?.id ?? null;  }  threadById(id: string, kind: "dm" | "group"): ThreadHit | null {    return this.store.query<{ id: string; contact_id: Text }>(`SELECT id, ${j("contact_id")} AS contact_id FROM rows WHERE ${LIVE("thread")} AND id = ? AND ${j("kind")} = ?`, id, kind)[0] ?? null;  }  knownExternalIds(threadId: string, channel: string, ids: string[]): Set<string> {    const rows = this.store.query<{ external_id: string }>(      `SELECT ${j("external_id")} AS external_id FROM rows WHERE ${LIVE("message")} AND ${j("external_id")} IN (SELECT value FROM json_each(?)) AND ${j("thread_id")} = ? AND ${j("channel")} = ?`,      JSON.stringify(ids),      threadId,      channel,    );    return new Set(rows.map((r) => r.external_id));  }  threadStats(threadId: string, channel: string): { count: number; oldestSentAt: Text; newestSentAt: Text } {    const r = this.store.query<{ n: number; oldest: Text; newest: Text }>(      `SELECT COUNT(*) AS n, MIN(${j("sent_at")}) AS oldest, MAX(${j("sent_at")}) AS newest FROM rows WHERE ${LIVE("message")} AND ${j("thread_id")} = ? AND ${j("channel")} = ?`,      threadId,      channel,    )[0];    return { count: Number(r?.n ?? 0), oldestSentAt: r?.oldest ?? null, newestSentAt: r?.newest ?? null };  }  groupThreadByKey(externalKey: string): { id: string; title: Text } | null {    return this.store.query<{ id: string; title: Text }>(`SELECT id, ${j("title")} AS title FROM rows WHERE ${LIVE("thread")} AND ${j("external_key")} = ? AND ${j("kind")} = 'group' ORDER BY created_at, id LIMIT 1`, externalKey)[0] ?? null;  }  jidGroupThreads(): { id: string; title: Text }[] {    return this.store.query<{ id: string; title: Text }>(`SELECT id, ${j("title")} AS title FROM rows WHERE ${LIVE("thread")} AND ${j("kind")} = 'group' AND ${j("external_key")} LIKE 'wa:group:%@g.us'`);  }  /** The thread holding the most of these ids, and how many — the majority test is the engine's. */  threadByOverlap(channel: string, kind: "dm" | "group", ids: string[]): { thread_id: string; contact_id: Text; matched: number } | null {    const r = this.store.query<{ thread_id: string; contact_id: Text; n: number }>(      `SELECT json_extract(m.data, '$.thread_id') AS thread_id, json_extract(t.data, '$.contact_id') AS contact_id, COUNT(*) AS n         FROM rows m JOIN rows t ON t.table_id = 'thread' AND t.deleted = 0 AND t.id = json_extract(m.data, '$.thread_id')        WHERE m.table_id = 'message' AND m.deleted = 0 AND json_extract(m.data, '$.external_id') IN (SELECT value FROM json_each(?))          AND json_extract(t.data, '$.kind') = ? AND json_extract(m.data, '$.channel') = ?        GROUP BY thread_id ORDER BY n DESC LIMIT 1`,      JSON.stringify(ids),      kind,      channel,    )[0];    return r ? { thread_id: r.thread_id, contact_id: r.contact_id, matched: Number(r.n) } : null;  }  participantsOf(threadId: string): ParticipantRow[] {    return this.store.query<{ id: string; contact_id: Text; display_name: Text }>(      `SELECT id, ${j("contact_id")} AS contact_id, ${j("display_name")} AS display_name FROM rows WHERE ${LIVE("thread_member")} AND ${j("thread_id")} = ? ORDER BY created_at, id`,      threadId,    );  }  /** The outer null: no such thread at all, which is "advance from nothing". */  threadLastMessageAt(threadId: string): { at: Text } | null {    const r = this.store.query<{ at: Text }>(`SELECT ${j("last_message_at")} AS at FROM rows WHERE ${LIVE("thread")} AND id = ?`, threadId)[0];    return r ? { at: r.at } : null;  }  threadExternalKey(threadId: string): Text {    return this.store.query<{ key: Text }>(`SELECT ${j("external_key")} AS key FROM rows WHERE ${LIVE("thread")} AND id = ?`, threadId)[0]?.key ?? null;  }  unlinkedReplies(threadId: string): { id: string; reply_to_external_id: string }[] {    return this.store.query<{ id: string; reply_to_external_id: string }>(      `SELECT id, ${j("reply_to_external_id")} AS reply_to_external_id FROM rows WHERE ${LIVE("message")} AND ${j("thread_id")} = ? AND ${j("reply_to_id")} IS NULL AND ${j("reply_to_external_id")} IS NOT NULL ORDER BY created_at, id`,      threadId,    );  }  messagesByExternalIds(threadId: string, channel: string, ids: string[]): { id: string; external_id: string }[] {    return this.store.query<{ id: string; external_id: string }>(      `SELECT id, ${j("external_id")} AS external_id FROM rows WHERE ${LIVE("message")} AND ${j("external_id")} IN (SELECT value FROM json_each(?)) AND ${j("thread_id")} = ? AND ${j("channel")} = ? ORDER BY created_at, id`,      JSON.stringify(ids),      threadId,      channel,    );  }  heldWithoutMedia(threadId: string, channel: string, ids: string[]): BareRow[] {    return this.store      .query<{ id: string; external_id: string; body: Text; meta: Text }>(        `SELECT id, ${j("external_id")} AS external_id, ${j("body")} AS body, ${j("meta")} AS meta FROM rows          WHERE ${LIVE("message")} AND ${j("external_id")} IN (SELECT value FROM json_each(?)) AND ${j("thread_id")} = ? AND ${j("channel")} = ?            AND ${j("deleted_at")} IS NULL AND json_array_length(data, '$.media') = 0 ORDER BY created_at, id`,        JSON.stringify(ids),        threadId,        channel,      )      .map((r) => ({ ...r, meta: parsed(r.meta) }));  }  realIdBodiesInMinute(threadId: string, channel: string, minute: string): string[] {    return this.store      .query<{ body: string }>(        `SELECT ${j("body")} AS body FROM rows WHERE ${LIVE("message")} AND ${j("thread_id")} = ? AND ${j("sent_at")} >= ? || ':00' AND ${j("sent_at")} < ? || ':60'            AND ${j("channel")} = ? AND ${j("external_id")} IS NOT NULL AND ${j("external_id")} NOT LIKE 'txt2:%' AND ${j("body")} IS NOT NULL ORDER BY ${j("sent_at")}, id`,        threadId,        minute,        minute,        channel,      )      .map((r) => r.body);  }  rowsInMinute(threadId: string, channel: string, minute: string): MinuteRow[] {    return this.store      .query<{ id: string; external_id: Text; direction: string; body: Text; meta: Text }>(        `SELECT id, ${j("external_id")} AS external_id, ${j("direction")} AS direction, ${j("body")} AS body, ${j("meta")} AS meta FROM rows          WHERE ${LIVE("message")} AND ${j("thread_id")} = ? AND ${j("sent_at")} >= ? || ':00' AND ${j("sent_at")} < ? || ':60' AND ${j("channel")} = ? ORDER BY ${j("sent_at")}, id`,        threadId,        minute,        minute,        channel,      )      .map((r) => ({ ...r, meta: parsed(r.meta) }));  }  /** The newest row with this id on this channel, and whether the thread's list line was made from it. */  messageByExternalId(channel: string, externalId: string): ChangeTarget | null {    const r = this.store.query<{ id: string; thread_id: string; meta: Text; media: Text; newest: number }>(MESSAGE_BY_EXTERNAL_ID_SQL, externalId, channel)[0];    if (!r) return null;    const meta = parsed(r.meta);    const media = parsed(r.media);    return { id: r.id, thread_id: r.thread_id ?? "", meta: meta && typeof meta === "object" && !Array.isArray(meta) ? (meta as Record<string, unknown>) : {}, media: Array.isArray(media) ? media : [], newest: Number(r.newest) === 1 };  }  /** Every person by the key of their name, for a call's name to snap to: archived and binned people are left out. */  peopleByName(): { id: string; full_name: string }[] {    return this.store.query<{ id: string; full_name: string }>(`SELECT p.id AS id, json_extract(p.data, '$.full_name') AS full_name FROM rows p WHERE ${LIVE_PERSON("p")} AND json_extract(p.data, '$.full_name') IS NOT NULL`);  }  /** The country a code-less number is read in: the owner's own number's (the object's `owner_phone`). */  ownerRegion(): Region | null {    const phone = this.ownerPhone ? normalizePhone(this.ownerPhone) : null;    return phone ? regionOf(phone) : null;  }}