import { MatrixClient } from 'matrix-js-sdk'; import { AccountDataEvent } from '../../types/matrix/accountData'; import { getAccountData } from './room'; /** * [Gitea #300] The status message's auto-clear time, in account data so every * Lotus device knows it. Before, only the device that set "clear after 1 hour" * (localStorage) ever cleared it, and only while it was open. */ export type StatusExpiry = { statusMsg: string; expiresAt: number }; /** Pure: parse `io.lotus.status_expiry` content. */ export function parseStatusExpiry(content: unknown): StatusExpiry | undefined { const c = content as { status_msg?: unknown; expires_at?: unknown } | undefined; if (!c || typeof c.status_msg !== 'string' || typeof c.expires_at !== 'number') return undefined; if (!c.status_msg || !Number.isFinite(c.expires_at)) return undefined; return { statusMsg: c.status_msg, expiresAt: c.expires_at }; } /** * Pure: what to do with a due expiry. Clear the server status only if it is * still the one that was set to expire; if it has since changed (e.g. on * another device), just forget the expiry. */ export function statusExpiryAction( entry: StatusExpiry | undefined, currentStatusMsg: string | undefined, now: number, ): 'none' | 'clear' | 'forget' { if (!entry || now < entry.expiresAt) return 'none'; return (currentStatusMsg ?? '') === entry.statusMsg ? 'clear' : 'forget'; } export const readStatusExpiry = (mx: MatrixClient): StatusExpiry | undefined => parseStatusExpiry(getAccountData(mx, AccountDataEvent.LotusStatusExpiry)?.getContent()); /** Record (or with no `expiresAt`, remove) the shared auto-clear time. */ export async function writeStatusExpiry( mx: MatrixClient, statusMsg: string, expiresAt?: number, ): Promise { const content = statusMsg && expiresAt !== undefined ? { status_msg: statusMsg, expires_at: expiresAt } : {}; await mx.setAccountData(AccountDataEvent.LotusStatusExpiry as never, content as never); }