Something went wrong. Try again.
softfork of @juliet.paris parfait forked from juliet.paris/parfait
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326import { ok } from "@atcute/client";
import type { Acting } from "./api";import { forgetPreferences, getPreferences } from "./preferences";
/** * Who may answer or quote a new post: Bluesky's threadgate and postgate, as the post's own * records beside it. Asked of new posts only; a reply follows the rules of its thread. */
export type ReplyRule = | { $type: "app.bsky.feed.threadgate#mentionRule" } | { $type: "app.bsky.feed.threadgate#followingRule" } | { $type: "app.bsky.feed.threadgate#followerRule" } | { $type: "app.bsky.feed.threadgate#listRule"; list: string };
export type Interaction = { /** Who can reply: anyone when missing, nobody when empty, otherwise anyone a rule lets in. */ allow?: ReplyRule[]; /** Whether others can quote it. */ quotes: boolean;};
export const ANYONE: Interaction = { quotes: true };
export const MENTION = "app.bsky.feed.threadgate#mentionRule";export const FOLLOWING = "app.bsky.feed.threadgate#followingRule";export const FOLLOWER = "app.bsky.feed.threadgate#followerRule";export const LIST = "app.bsky.feed.threadgate#listRule";const DISABLE = "app.bsky.feed.postgate#disableRule";
/** As Bluesky keeps it in a draft or a preference: who can reply, and the rules for quoting. */export const toGates = (interaction: Interaction) => ({ ...(interaction.allow ? { threadgateAllow: interaction.allow } : {}), ...(interaction.quotes ? {} : { postgateEmbeddingRules: [{ $type: DISABLE }] }),});
export const fromGates = (gates: { threadgateAllow?: unknown[]; threadgateAllowRules?: unknown[]; postgateEmbeddingRules?: unknown[];}): Interaction => { const allow = (gates.threadgateAllow ?? gates.threadgateAllowRules) as ReplyRule[] | undefined; return { ...(allow ? { allow } : {}), quotes: !gates.postgateEmbeddingRules?.some( (rule) => (rule as { $type?: string }).$type === DISABLE, ), };};
/** What an account has set on Bluesky for its new posts, or anyone, if nothing. */export const defaultInteraction = async (as: Acting | undefined): Promise<Interaction> => { if (!as) return ANYONE; try { const prefs = await getPreferences(as); const pref = prefs.find( (each) => each.$type === "app.bsky.actor.defs#postInteractionSettingsPref", ); return pref ? fromGates(pref as Parameters<typeof fromGates>[0]) : ANYONE; } catch { return ANYONE; }};
const PREF = "app.bsky.actor.defs#postInteractionSettingsPref";
/** * Makes a choice the account's default for new posts, in its Bluesky preferences, where the * Bluesky app reads it too. Preferences are one record: read fresh, this one setting replaced, * the rest written back as it was. */export const saveDefaultInteraction = async (as: Acting, interaction: Interaction) => { const { preferences } = await ok(as.pds.get("app.bsky.actor.getPreferences", { params: {} })); const pref = { $type: PREF, threadgateAllowRules: interaction.allow, postgateEmbeddingRules: interaction.quotes ? [] : [{ $type: DISABLE }], }; const rest = (preferences as { $type?: string }[]).filter((each) => each.$type !== PREF); await ok( as.pds.post("app.bsky.actor.putPreferences", { input: { preferences: [...rest, pref] as any }, as: null, }), ); forgetPreferences(as.did as `did:${string}:${string}`);};
/** Whether two choices let the same people reply and quote, in whatever order. */export const sameInteraction = (a: Interaction, b: Interaction) => { if (a.quotes !== b.quotes || !a.allow !== !b.allow) return false; if (!a.allow || !b.allow) return true; const key = (rule: ReplyRule) => rule.$type === LIST ? `${rule.$type} ${rule.list}` : rule.$type; const left = a.allow.map(key).sort(); const right = b.allow.map(key).sort(); return left.length === right.length && left.every((each, i) => each === right[i]);};
/** Who can reply, said shortly, for the chip: "Anyone", "Followers", "Nobody", "Some people". */export const repliesLabel = (interaction: Interaction) => { const allow = interaction.allow; if (!allow) return "Anyone can reply"; if (!allow.length) return "Nobody can reply"; if (allow.length > 1) return "Some can reply"; switch (allow[0].$type) { case MENTION: return "Mentioned can reply"; case FOLLOWING: return "Followed can reply"; case FOLLOWER: return "Followers can reply"; default: return "A list can reply"; }};
/** * Why you can't reply to a post, in a sentence, from the rules its thread's author set (its * threadgate, as Bluesky gives it with the post): who may, by name where there's one ("Only * people @alex follows can reply."), or that nobody may. A reply's rules are its thread's: given * the thread's first post, from there. Nothing when what's given doesn't say. */export const whyNoReply = (post: { author: { handle: string }; threadgate?: { record?: unknown; lists?: { uri: string; name: string }[] };}) => { const allow = (post.threadgate?.record as { allow?: ReplyRule[] } | undefined)?.allow; if (!allow) return; if (!allow.length) return "Replies are off."; const who = `@${post.author.handle}`; const has = (type: string) => allow.some((rule) => rule.$type === type); // Said as shortly as stays exact: both follow rules at once, one phrase. const phrases = [ ...(has(MENTION) ? ["mentioned people"] : []), ...(has(FOLLOWING) && has(FOLLOWER) ? [`${who}'s follows and followers`] : has(FOLLOWING) ? [`people ${who} follows`] : has(FOLLOWER) ? [`${who}'s followers`] : []), ...allow .filter((rule): rule is Extract<ReplyRule, { list: string }> => rule.$type === LIST) .map((rule) => { const name = post.threadgate?.lists?.find((list) => list.uri === rule.list)?.name; return name ? `people on ${name}` : "people on a list"; }), ]; if (!phrases.length) return; const joined = phrases.length < 3 ? phrases.join(" or ") : `${phrases.slice(0, -1).join(", ")}, or ${phrases.at(-1)}`; return `Only ${joined} can reply.`;};
/** * A record key in Bluesky's own form (a TID): when, to the microsecond, and a random clock id, * written in its sortable base 32. The post's, made here, so its threadgate and postgate can * share it and all three go in one write. */const ALPHABET = "234567abcdefghijklmnopqrstuvwxyz";let last = 0n;export const newRecordKey = () => { let micros = BigInt(Date.now()) * 1000n; if (micros <= last) micros = last + 1n; last = micros; let value = (micros << 10n) | BigInt(Math.floor(Math.random() * 1024)); let key = ""; for (let i = 0; i < 13; i++) { key = ALPHABET[Number(value & 31n)] + key; value >>= 5n; } return key;};
/** The records that go with a new post to hold to its settings: none when anyone can do anything. */export const gateRecords = (postUri: string, interaction: Interaction, createdAt: string) => { const records: { collection: string; value: Record<string, unknown> }[] = []; if (interaction.allow) { records.push({ collection: "app.bsky.feed.threadgate", value: { $type: "app.bsky.feed.threadgate", post: postUri, allow: interaction.allow, createdAt, }, }); } if (!interaction.quotes) { records.push({ collection: "app.bsky.feed.postgate", value: { $type: "app.bsky.feed.postgate", post: postUri, embeddingRules: [{ $type: DISABLE }], createdAt, }, }); } return records;};
type GateRecord = Record<string, unknown> & { $type: string; post: string; createdAt: string };
/** A post's own record of a kind beside it, by the post's key: its threadgate, its postgate. */const getGate = async (as: Acting, collection: string, rkey: string) => { const res = await as.pds.get("com.atproto.repo.getRecord", { params: { repo: as.did as any, collection: collection as any, rkey }, }); if (!res.ok) { if (res.data.error === "RecordNotFound") return undefined; throw new Error(res.data.message ?? res.data.error); } return res.data.value as GateRecord;};
/** A post's settings as they are: who may reply and quote, and whether it's a reply. */export type PostGates = { interaction: Interaction; /** A reply follows its thread's rules for replies: only quoting is its own. */ isReply: boolean; threadgate?: GateRecord; postgate?: GateRecord;};
/** * `known`: what's known of the post already, from where it's shown: then its own record isn't * read again, nor, for a reply, a threadgate it can't have (only a thread's first post has one). */export const readGates = async ( as: Acting, uri: string, known?: { reply: boolean },): Promise<PostGates> => { const rkey = uri.slice(uri.lastIndexOf("/") + 1); const [post, threadgate, postgate] = await Promise.all([ known ? { reply: known.reply } : getGate(as, "app.bsky.feed.post", rkey), known?.reply ? undefined : getGate(as, "app.bsky.feed.threadgate", rkey), getGate(as, "app.bsky.feed.postgate", rkey), ]); if (!post) throw new Error("This post isn't there any more."); return { interaction: { ...(threadgate?.allow ? { allow: threadgate.allow as ReplyRule[] } : {}), quotes: !(postgate?.embeddingRules as { $type?: string }[] | undefined)?.some( (rule) => rule.$type === DISABLE, ), }, isReply: !!post.reply, threadgate, postgate, };};
/** * Changes a post's settings: its threadgate and postgate written, kept, or taken away once * they say nothing. What else they hold stays as it was: replies the author hid, quotes they * detached. */export const writeGates = async ( as: Acting, uri: string, before: PostGates, interaction: Interaction,) => { const rkey = uri.slice(uri.lastIndexOf("/") + 1); const now = new Date().toISOString(); const repo = as.did as `did:${string}:${string}`; const save = async ( collection: `${string}.${string}.${string}`, existing: GateRecord | undefined, next: GateRecord | undefined, ) => { if (next) { const res = await as.pds.post("com.atproto.repo.putRecord", { input: { repo, collection, rkey, record: next }, }); if (!res.ok) throw new Error(res.data.message ?? res.data.error); } else if (existing) { const res = await as.pds.post("com.atproto.repo.deleteRecord", { input: { repo, collection, rkey }, }); if (!res.ok) throw new Error(res.data.message ?? res.data.error); } };
if (!before.isReply) { const { allow: _allow, ...rest }: GateRecord = before.threadgate ?? { $type: "app.bsky.feed.threadgate", post: uri, createdAt: now, }; const next: GateRecord = { ...rest, ...(interaction.allow ? { allow: interaction.allow } : {}), }; const hidden = (next.hiddenReplies as unknown[] | undefined)?.length; await save( "app.bsky.feed.threadgate", before.threadgate, next.allow || hidden ? next : undefined, ); }
const base: GateRecord = before.postgate ?? { $type: "app.bsky.feed.postgate", post: uri, createdAt: now, }; const others = ((base.embeddingRules as { $type?: string }[] | undefined) ?? []).filter( (rule) => rule.$type !== DISABLE, ); const rules = interaction.quotes ? others : [...others, { $type: DISABLE }]; const next: GateRecord = { ...base, embeddingRules: rules }; const detached = (next.detachedEmbeddingUris as unknown[] | undefined)?.length; await save( "app.bsky.feed.postgate", before.postgate, rules.length || detached ? next : undefined, );};