Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

2.7 KB
Raw Blame
import { validZone } from "../host/check-plan.ts";
import type { PresenceAnswer } from "../host/brief.ts";
import type { RequestAuth } from "../request-auth.ts";
import { PASS, type RouteHandler } from "./table.ts";

export interface PresenceRouteDeps {
  isOwner(auth: RequestAuth): boolean;
  active(source: "desktop" | "phone", timeZone?: string, language?: string): Promise<PresenceAnswer>;
  /** A Team Cloud: every member's arrival counts, for their own brief, in the language their app shows. */
  member?(auth: RequestAuth, language?: string): PresenceAnswer;
  /** The language the app of a ping that counts shows (the owner's, or a member's), for the lines the server writes for
   * that person (host/person-languages.ts). */
  heard?(auth: RequestAuth, language: string): void;
  /** The conversation open in the app while a person who counts was active (the owner, or on a Team Cloud any
   * member): it is the one in front of them. */
  sawChat?(auth: RequestAuth, threadId: string, typing: boolean): void;
}

const IANA_ZONE = /^(?:UTC|[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)+)$/;
const LANGUAGE_TAG = /^[a-z]{2,3}(?:-[a-z0-9]{2,8}){0,3}$/i;
const THREAD_ID = /^[\w-]{1,100}$/;

/** POST /api/presence/active {source, timeZone, language, threadId, typing}: the person opened or used the app, with that
 * conversation open (`typing`: a key in its composer). Only the owner's counts. */
export function createPresenceRoutes(deps: PresenceRouteDeps): RouteHandler {
  return async ({ req, res, path, method, auth, json, readBody }) => {
    if (method !== "POST" || path !== "/api/presence/active") return PASS;
    const body: unknown = await readBody(req, 4096);
    const given = body && typeof body === "object" && !Array.isArray(body) ? body as Record<string, unknown> : {};
    const source = given.source === "phone" ? "phone" : "desktop";
    const timeZone = typeof given.timeZone === "string" && given.timeZone.length <= 128 && IANA_ZONE.test(given.timeZone) ? validZone(given.timeZone) : undefined;
    const language = typeof given.language === "string" && LANGUAGE_TAG.test(given.language) ? given.language.toLowerCase() : undefined;
    const counts = Boolean(deps.member) || deps.isOwner(auth);
    if (language && counts) deps.heard?.(auth, language);
    if (counts && typeof given.threadId === "string" && THREAD_ID.test(given.threadId)) deps.sawChat?.(auth, given.threadId, given.typing === true);
    if (deps.member) return json(res, 200, { ok: true, ...deps.member(auth, language) });
    // A guest's activation is not the person's: answered, never recorded.
    if (!deps.isOwner(auth)) return json(res, 200, { ok: true, returned: false });
    return json(res, 200, { ok: true, ...(await deps.active(source, timeZone, language)) });
  };
}