Something went wrong. Try again.
message board on atproto atchan.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464import type { DidString, UriString } from '@atproto/syntax'import { AtUri } from '@atproto/syntax'import { sql } from 'kysely'import { get_db } from './connection'import { forget_author_names } from './author-names'import type { NewThread, Thread } from './schema'import { backlinks_from_refs } from '#lib/domain/post.js'import { hydrate_reply } from '#lib/domain/post.js'import { feed_segments, feed_title, type FeedPost } from './feed'import { thumb_of } from '#lib/richtext/embed.js'import { thumbnail_formats } from '#lib/server/blob/thumbnail.js'import { hydrate_thread, post_href, type ThreadWithReplies} from '#lib/domain/thread.js'import { subject_effects, load_visibility, flag_times } from './label'import { index_embed_blob } from './blob'import { upsert_post_values, retire_post_row } from './post-lifecycle'import { resolve_foreign_posts, drop_hidden_foreign, foreign_refs, hydrate_foreign_ref, index_refs} from './refs'import { confirmed_or_own } from './visibility'import { get_yeah_summaries } from './yeah'import { refresh_effective_board, get_move_origin } from './move'import { effective_spoiler } from '#lib/domain/moderation.js'import { parse_board_labels, is_permissive } from '#lib/domain/board.js'
export async function upsert_thread( thread: Omit<NewThread, 'rkey' | 'updatedAt' | 'effectiveBoard'>): Promise<void> { const row = { ...thread, rkey: new AtUri(thread.uri).rkey, // where the author says it goes. refresh_effective_board below has the // final say — a thread under an honoured move stays where the moderator // put it, so re-ingesting the record (an edit, a backfill) can't quietly // walk it back to the board its author still names. effectiveBoard: thread.board } await get_db() .transaction() .execute(async (tx) => { const current = await tx .selectFrom('thread') .select(['cid', 'createdAt', 'updatedAt', 'deletedAt']) .where('uri', '=', row.uri) .executeTakeFirst() const values = upsert_post_values(current, row, row.indexedAt) if (!values) return
await tx .insertInto('thread') .values(values) // an optimistic write (no indexedAt) must never clobber an already // confirmed row, so it inserts only when absent; a confirmed write // from the indexer is authoritative and overwrites in place. .onConflict((oc) => row.indexedAt === undefined ? oc.column('uri').doNothing() : oc.column('uri').doUpdateSet(values) ) .execute() await refresh_effective_board(tx, row.uri) await index_embed_blob(tx, row.embed) await index_refs( tx, row.uri, row.rkey, row.uri, values.body, values.facets, values.createdAt ) }) forget_author_names(row.uri)}
/** The board slug a thread belongs to, without hydrating the rest of it. */export async function get_thread_board( uri: UriString): Promise<string | undefined> { const row = await get_db() .selectFrom('thread') .innerJoin('board', 'board.uri', 'thread.effectiveBoard') .select('board.rkey') .where('thread.uri', '=', uri) .executeTakeFirst() return row?.rkey}
export async function list_threads_by_author( did: DidString): Promise<Thread[]> { return get_db() .selectFrom('thread') .selectAll() .where('authorDid', '=', did) .orderBy('createdAt', 'desc') .execute()}
// Every thread and reply the user authored, merged and newest first, sliced to a// page. Backs /account, which renders it with the same <Feed> as the site feed,// so it returns FeedPost rows. These are the viewer's own posts, so no visibility// gating applies; the only filter is authorDid. See count_authored_posts for the// total. The union keeps offset paging correct across the merged set.export async function list_authored_posts( did: DidString, { limit, offset }: { limit: number; offset: number }): Promise<FeedPost[]> { const db = get_db() // both union operands must have structurally identical column types, so every // column is cast to the same shape on each side. A reply borrows its parent // thread's subject and board; a thread uses its own. const threads = db .selectFrom('thread') .innerJoin('board', 'board.uri', 'thread.effectiveBoard') .leftJoin('account', 'account.did', 'thread.authorDid') .where('thread.authorDid', '=', did) .select((eb) => [ sql<0 | 1>`0`.as('is_reply'), eb.ref('thread.uri').as('uri'), eb.ref('thread.uri').as('thread_uri'), eb.ref('thread.authorDid').as('authorDid'), eb.ref('thread.name').$castTo<string | null>().as('name'), eb.ref('account.handle').$castTo<string | null>().as('handle'), eb.ref('board.rkey').$castTo<string>().as('board'), eb.ref('thread.subject').$castTo<string | null>().as('subject'), eb.ref('thread.body').$castTo<string | null>().as('body'), eb.ref('thread.body').$castTo<string | null>().as('thread_body'), eb.ref('thread.facets').$castTo<string | null>().as('facets'), eb.ref('thread.embed').$castTo<string | null>().as('embed'), eb.ref('thread.spoiler').$castTo<number | null>().as('spoiler'), // threads carry no sage flag of their own sql<number | null>`0`.as('sage'), eb.ref('thread.createdAt').$castTo<string>().as('createdAt') ]) const replies = db .selectFrom('reply') .innerJoin('thread', 'thread.uri', 'reply.thread') .innerJoin('board', 'board.uri', 'thread.effectiveBoard') .leftJoin('account', 'account.did', 'reply.authorDid') .where('reply.authorDid', '=', did) .select((eb) => [ sql<0 | 1>`1`.as('is_reply'), eb.ref('reply.uri').as('uri'), eb.ref('reply.thread').as('thread_uri'), eb.ref('reply.authorDid').as('authorDid'), eb.ref('reply.name').$castTo<string | null>().as('name'), eb.ref('account.handle').$castTo<string | null>().as('handle'), eb.ref('board.rkey').$castTo<string>().as('board'), eb.ref('thread.subject').$castTo<string | null>().as('subject'), eb.ref('reply.body').$castTo<string | null>().as('body'), eb.ref('thread.body').$castTo<string | null>().as('thread_body'), eb.ref('reply.facets').$castTo<string | null>().as('facets'), eb.ref('reply.embed').$castTo<string | null>().as('embed'), eb.ref('reply.spoiler').$castTo<number | null>().as('spoiler'), eb.ref('reply.sage').$castTo<number | null>().as('sage'), eb.ref('reply.createdAt').$castTo<string>().as('createdAt') ]) const rows = await threads .unionAll(replies) .orderBy('createdAt', 'desc') .limit(limit) .offset(offset) .execute()
const yeahs = await get_yeah_summaries(rows.map((r) => r.uri))
return rows.map((r) => ({ uri: r.uri, thread_uri: r.thread_uri, href: post_href(r.board, new AtUri(r.thread_uri).rkey, r.uri), board: r.board, name: r.name, handle: r.handle, authorDid: r.authorDid, ...feed_title({ ...r, is_reply: r.is_reply === 1 }), body: r.body ?? '', body_segments: feed_segments(r.body ?? '', r.facets, r.createdAt), thumb: thumb_of(r.embed, r.authorDid, r.spoiler, thumbnail_formats), createdAt: r.createdAt, is_reply: r.is_reply === 1, sage: r.sage === 1, yeah: yeahs.get(r.uri)?.count ?? 0 }))}
// Total threads + replies the user authored, for paging /account.export async function count_authored_posts(did: DidString): Promise<number> { const db = get_db() const [threads, replies] = await Promise.all([ db .selectFrom('thread') .select((e) => e.fn.countAll<number>().as('n')) .where('authorDid', '=', did) .executeTakeFirstOrThrow(), db .selectFrom('reply') .select((e) => e.fn.countAll<number>().as('n')) .where('authorDid', '=', did) .executeTakeFirstOrThrow() ]) return Number(threads.n) + Number(replies.n)}
// Deleting a thread blanks its content in place and stamps `deletedAt`, so it// renders as a tombstone (see DeletedPost) instead of vanishing — replies stay// attached to it. Its refs and embed blob are still released; only the shell of// the row survives. To reap a never-confirmed thread outright, see purge_thread.export async function delete_thread(uri: UriString): Promise<string[]> { const released = await get_db() .transaction() .execute((tx) => retire_post_row( tx, uri, () => tx .selectFrom('thread') .select('embed') .where('uri', '=', uri) .executeTakeFirst(), () => tx .updateTable('thread') .set({ // blanked like the other content columns; an empty subject // renders the same as a thread that never had one subject: '', body: '', facets: '', embed: '{}', name: '', deletedAt: new Date().toISOString() }) .where('uri', '=', uri) .execute() ) ) forget_author_names(uri) return released}
// A genuine hard delete: the row is gone, not tombstoned. Only for threads that// were never confirmed — those were never publicly visible, so there's nothing// to leave behind as a tombstone.export async function purge_thread(uri: UriString): Promise<string[]> { return get_db() .transaction() .execute((tx) => retire_post_row( tx, uri, () => tx .selectFrom('thread') .select('embed') .where('uri', '=', uri) .executeTakeFirst(), () => tx.deleteFrom('thread').where('uri', '=', uri).execute() ) )}
// On an rkey collision the first thread indexed wins.export async function get_thread_by_rkey( rkey: string, viewer?: DidString): Promise<ThreadWithReplies | undefined> { const row = await get_db() .selectFrom('thread') .select('uri') .where('rkey', '=', rkey) .orderBy(sql`rowid`) .executeTakeFirst() return row && get_thread(row.uri, viewer)}
// A hidden post is gone for everyone, author and moderators included: it is// filtered out here so it never reaches any view. Moderators review hidden// content in Ozone, not here. `viewer` is the authed did (if any), used only for// the separate optimistic-write axisexport async function get_thread( id: UriString, viewer?: DidString): Promise<ThreadWithReplies | undefined> { const db = get_db()
const [thread_row, replies, ref_rows] = await Promise.all([ db .selectFrom('thread') .leftJoin('account', 'account.did', 'thread.authorDid') // the board it's actually on, which is the one it was moved to if it was .leftJoin('board', 'board.uri', 'thread.effectiveBoard') .selectAll('thread') .select(['account.handle', 'board.labels as board_labels']) .where('thread.uri', '=', id) .executeTakeFirst(), db .selectFrom('reply') .leftJoin('account', 'account.did', 'reply.authorDid') .selectAll('reply') .select('account.handle') .where('thread', '=', id) // a deleted reply just drops out of the thread — unlike the OP, losing // one doesn't orphan anything, so there's no tombstone to render .where('deletedAt', 'is', null) .orderBy('createdAt', 'asc') .execute(), db .selectFrom('refs') .select(['src_rkey', 'target_rkey']) .where('thread', '=', id) .orderBy('src_rkey', 'asc') .execute() ])
if (!thread_row) return undefined
// board_labels is joined only to decide forced spoilering; strip it off so it // doesn't leak into the hydrated thread sent to the client. const { board_labels, ...thread } = thread_row const board_permissive = is_permissive( parse_board_labels(board_labels ?? '[]') )
// an unconfirmed thread 404s for everyone but its author if (!confirmed_or_own(thread, viewer)) return undefined
// a hidden thread (or one by a hidden/inactive author) 404s for everyone; // hidden replies drop out below. No privileged in-app view — moderators // review hidden content in Ozone. const { effects, dropped } = await load_visibility([thread, ...replies])
if (dropped(thread.uri, thread.authorDid)) return undefined const thread_mod = subject_effects(effects, thread.uri)
// a locked thread stops accepting replies at the moment lock was applied. // any reply that still lands after that (e.g. a racing/lagging PDS write) // is dropped for everyone, moderators included — it was never meant to exist. const lock_at = thread_mod.locked ? (await flag_times([thread.uri], 'lock')).get(thread.uri) : undefined const after_lock = (r: { createdAt: string }) => lock_at !== undefined && r.createdAt > lock_at
const visible_replies = replies.filter( (r) => !after_lock(r) && // unconfirmed replies from other authors aren't visible here confirmed_or_own(r, viewer) && !dropped(r.uri, r.authorDid) )
// on the full thread page we have every local post, so a >>ref whose target // isn't here is either a cross-thread ref or dead. Deleted replies are // already excluded above, and a deleted OP is left out here too — its // posts.effectiveBoard exclusion in resolve_foreign_posts (via // exclude_thread) means it can't resolve as foreign either, so a >>ref to // it falls through to dead, same as any other gone post (see DeletedPost). const op_rkey = new AtUri(thread.uri).rkey const known = new Set<string>([ ...(thread.deletedAt ? [] : [op_rkey]), ...visible_replies.map((reply) => new AtUri(reply.uri).rkey) ])
// refs authored by a hidden reply are dropped (its src rkey isn't `known`), // so hidden posts don't leave backlinks or resolve forward refs const visible_ref_rows = ref_rows.filter((r) => known.has(r.src_rkey))
// forward: rkeys quoted by this thread's posts that live elsewhere const forward_targets = new Set<string>() for (const { target_rkey } of visible_ref_rows) if (!known.has(target_rkey)) forward_targets.add(target_rkey)
// incoming: posts in *other* threads that quote a post in this one const incoming = await db .selectFrom('refs') .select(['refs.src_rkey', 'refs.thread', 'refs.target_rkey']) .where('target_rkey', 'in', [...known]) .where('thread', '!=', id) .orderBy('src_rkey', 'asc') .execute()
// resolve both directions in one pass (foreign targets + incoming sources) const resolve_set = new Set<string>([ ...forward_targets, ...incoming.map((r) => r.src_rkey) ]) // cross-thread refs stay within a board, and after a move that's the board the // thread now sits on — a moved thread's >>refs resolve against its new // neighbours, not the ones it left behind const resolved = await resolve_foreign_posts( db, resolve_set, thread.effectiveBoard, id ) await drop_hidden_foreign(resolved)
const backlinks = backlinks_from_refs(visible_ref_rows) for (const row of incoming) { // skip cross-board sources: resolve only returns same-board posts, so an // unresolved incoming source is on another board and shouldn't backlink if (!resolved.has(row.src_rkey)) continue const list = backlinks.get(row.target_rkey) ?? [] if (!list.some((bl) => bl.rkey === row.src_rkey)) list.push({ rkey: row.src_rkey, thread_uri: row.thread }) backlinks.set(row.target_rkey, list) }
const foreign = foreign_refs(resolved) const foreign_posts = [...resolved.values()].map(hydrate_foreign_ref)
// yeah counts + the viewer's own yeah for the OP and every visible reply, so // each post's actions can show the toggle in the right state const yeahs = await get_yeah_summaries( [thread.uri, ...visible_replies.map((r) => r.uri)] as UriString[], viewer )
return { ...hydrate_thread(thread, { known, backlinks: backlinks.get(op_rkey), foreign, moderation: thread_mod, viewer }), yeah: yeahs.get(thread.uri), // where a moderator moved it from, so the thread can say so moved: await get_move_origin(thread.uri), spoiler: effective_spoiler( effects.get(thread.uri), board_permissive, thread.spoiler ), replies: visible_replies.map((reply) => ({ ...hydrate_reply(reply, { known, backlinks: backlinks.get(new AtUri(reply.uri).rkey), foreign, moderation: subject_effects(effects, reply.uri), viewer }), yeah: yeahs.get(reply.uri), spoiler: effective_spoiler( effects.get(reply.uri), board_permissive, reply.spoiler ) })), reply_count: visible_replies.length, file_count: visible_replies.filter((r) => r.embed).length, foreign: foreign_posts }}