Something went wrong. Try again.
softfork of @juliet.paris parfait forked from juliet.paris/parfait
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389import type { AppBskyDraftDefs } from "@atcute/bluesky";import { ok } from "@atcute/client";
import { actingAsAccount } from "./accounts";import type { Acting } from "./api";import { onDraftEvent } from "./draft-events";import { discardDraftImages, loadDraftGif, loadDraftImages, loadDraftVideo } from "./draft-images";import { allDrafts, type Draft, draftOf, forgetDraft, postStorageId, storageIdsOf, type ThreadPost, isReply, keepRemoteDraft, newDraftId, setDraftRemote, worthKeeping,} from "./drafts";import { fromGates, toGates } from "./interaction";import { postLangsOf } from "./post-langs";import { readStored, writeStored } from "./storage";
/** * Drafts kept on Bluesky as well as here, so they follow you to the Bluesky app and back: each * new post or quote being written is sent there shortly after it changes, and an account's * drafts there are brought here when its Drafts is looked at. Replies stay here alone: Bluesky's * drafts have no place for what a post answers. * * Pictures and videos stay on the device they were added on, as Bluesky's drafts only hold where * to find them there: elsewhere, a draft brings its words, and says its pictures are elsewhere. */
/** How long a draft rests after a change before it's sent: not every key typed. */const PAUSE = 1500;/** How much later than its last sending here a draft on Bluesky must be to count as changed there. */const SKEW = 5000;
/** This browser, as Bluesky's drafts name where each was written. */const deviceId = (() => { const key = "parfait:device-id"; try { let id = localStorage.getItem(key); if (!id) localStorage.setItem(key, (id = crypto.randomUUID())); return id; } catch { return crypto.randomUUID(); }})();
/** Where a draft's picture or video is, on this device: in parfait's own storage, by draft. */const refOf = (id: string, item: string) => ({ path: `parfait/${id}/${item}` });
/** One post of a draft as Bluesky keeps it: its words, and where its pictures or video are. */const toRemotePost = async ( storageId: string, text: string,): Promise<AppBskyDraftDefs.DraftPost> => { const [images, video, gif] = await Promise.all([ loadDraftImages(storageId), loadDraftVideo(storageId), loadDraftGif(storageId), ]); const post: AppBskyDraftDefs.DraftPost = { text }; const pictures = images.map((image) => ({ localRef: refOf(storageId, image.id), ...(image.alt ? { alt: image.alt } : {}), })); // Up to four as pictures; more, as Bluesky's gallery. if (pictures.length > 4) { post.embedGallery = { items: pictures.map((picture) => ({ $type: "app.bsky.draft.defs#draftEmbedImage" as const, ...picture, })), }; } else if (pictures.length) { post.embedImages = pictures; } if (video) { post.embedVideos = [ { localRef: refOf(storageId, "video"), ...(video.alt ? { alt: video.alt } : {}) }, ]; } // A GIF is only a link: Bluesky keeps it whole, for any device to post. if (gif) post.embedExternals = [{ uri: gif.uri as `${string}:${string}` }]; return post;};
/** * A draft as Bluesky keeps it: its posts, a thread's all of them, the first with what it * quotes; who may reply and quote; and where each post's media is. */const toRemote = async (id: string, draft: Draft): Promise<AppBskyDraftDefs.Draft> => { const [first, ...rest] = await Promise.all([ toRemotePost(id, draft.text), ...(draft.more ?? []).map((post) => toRemotePost(postStorageId(id, post.id), post.text)), ]); if (draft.quote) first.embedRecords = [{ record: draft.quote as any }]; // Pictures or a video on the device it was written on: still there, as they were. if ( draft.mediaElsewhere && !first.embedImages && !first.embedGallery && !first.embedVideos && !first.embedExternals ) { Object.assign(first, draft.mediaElsewhere); } return { posts: [first, ...rest], langs: postLangsOf(draft.account) as AppBskyDraftDefs.Draft["langs"], deviceId, deviceName: "parfait", // Who may reply and quote, once chosen: otherwise, as the account's own setting says. ...(draft.interaction ? (toGates(draft.interaction) as object) : {}), };};
/** * The posts after a thread's first, as found on Bluesky: those already here keep their ids, in * order, so their pictures stay theirs; any more are new. */const moreFrom = (posts: AppBskyDraftDefs.DraftPost[], here: ThreadPost[] = []) => posts.length ? posts.map((post, index) => ({ id: here[index]?.id ?? Math.random().toString(36).slice(2, 10), text: post.text, })) : undefined;
/** * Drafts taken off Bluesky from here, by its id: until it stops listing them, they're kept out * of Drafts here. Its list can lag a deletion for a while, and a draft still in it would * otherwise come back as one written on another device. Kept in this browser, through reloads. */const GONE = "parfait:drafts-gone";const readGone = () => readStored<Record<string, number>>(GONE, {});const writeGone = (gone: Record<string, number>) => writeStored(GONE, Object.keys(gone).length ? gone : undefined);
const remove = async (as: Acting, remoteId: string) => { writeGone({ ...readGone(), [remoteId]: Date.now() }); await ok(as.rpc.post("app.bsky.draft.deleteDraft", { input: { id: remoteId as any }, as: null }));};
// Each draft's sending, one after another, so a quick second change never races the first.const timers = new Map<string, ReturnType<typeof setTimeout>>();const running = new Map<string, Promise<void>>();/** Bluesky's id for a draft as soon as it's known, even if the draft has gone meanwhile. */const created = new Map<string, string>();
const queue = (id: string, work: () => Promise<void>) => { const next = (running.get(id) ?? Promise.resolve()) .then(work) .catch((err) => console.warn("Could not keep a draft on Bluesky", err)); running.set(id, next); void next.finally(() => running.get(id) === next && running.delete(id));};
/** Sends a draft as it is now: made on Bluesky, changed there, or taken off once empty. */const push = async (id: string) => { const draft = draftOf(id); if (!draft || isReply(id, draft)) return; const as = await actingAsAccount(draft.account); if (!as) return; const startedAt = Date.now(); const remoteId = draft.remoteId ?? created.get(id); if (!worthKeeping(draft)) { if (!remoteId) return; await remove(as, remoteId); created.delete(id); setDraftRemote(id, undefined); return; } const remote = await toRemote(id, draft); if (remoteId) { await ok( as.rpc.post("app.bsky.draft.updateDraft", { input: { draft: { id: remoteId as any, draft: remote } }, as: null, }), ); setDraftRemote(id, remoteId, startedAt); } else { if (unsure.has(id)) return; let made: string | undefined; let failed: unknown; try { const answer = await ok( as.rpc.post("app.bsky.draft.createDraft", { input: { draft: remote } }), ); made = typeof answer?.id === "string" && answer.id ? answer.id : undefined; } catch (err) { failed = err; } // No id back (a PDS passing the answer on wrongly, or a connection dropped after the // asking): it may have been made all the same, so it's looked for before being made again, // which would otherwise happen at every pause in typing. if (!made) { const found = await findMade(as, remote, startedAt).catch(() => null); // A failed asking with nothing to check by (offline, say) is asked again at the next // change, as before; only an answer that came back without its id stops it. if (found === null && !failed) unsure.add(id); if (!found) { if (failed) throw failed; return; } made = found; } created.set(id, made); setDraftRemote(id, made, startedAt); }};
/** * Drafts whose making on Bluesky went unconfirmed, and couldn't be checked: kept here alone for * the rest of the visit, rather than made there again and again. Drafts brings them over later. */const unsure = new Set<string>();
/** * The draft just made on Bluesky, when its id didn't come back: this browser's, with these * words, made since it was asked for, and not already another draft's here. Undefined if there's * none (it wasn't made); null if Bluesky's list can't be read either. */const findMade = async (as: Acting, remote: AppBskyDraftDefs.Draft, since: number) => { const data = await ok(as.rpc.get("app.bsky.draft.getDrafts", { params: { limit: 50 } })); if (!Array.isArray(data?.drafts)) return null; const known = new Set([ ...created.values(), ...allDrafts().flatMap((draft) => (draft.remoteId ? [draft.remoteId] : [])), ]); return data.drafts .filter( (view) => !known.has(view.id) && view.draft.deviceId === deviceId && view.draft.posts[0]?.text === remote.posts[0].text && Date.parse(view.createdAt) >= since - SKEW, ) .sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))[0]?.id;};
/** Sends a draft once it's rested from changes. */const schedule = (id: string) => { clearTimeout(timers.get(id)); timers.set( id, setTimeout(() => { timers.delete(id); queue(id, () => push(id)); }, PAUSE), );};
onDraftEvent((event) => { if (event.type === "changed") return schedule(event.id); // Sent, thrown away, or moved to another account: gone from the first account's drafts. clearTimeout(timers.get(event.id)); timers.delete(event.id); const { draft } = event; if (isReply(event.id, draft)) return; queue(event.id, async () => { const remoteId = draft.remoteId ?? created.get(event.id); created.delete(event.id); if (!remoteId) return; const as = await actingAsAccount(draft.account); if (as) await remove(as, remoteId); });});
/** Every draft an account has on Bluesky, a page at a time. */const fetchAll = async (as: Acting) => { const found: AppBskyDraftDefs.DraftView[] = []; let cursor: string | undefined; for (let page = 0; page < 5; page++) { const data = await ok( as.rpc.get("app.bsky.draft.getDrafts", { params: { limit: 100, cursor } }), ); found.push(...data.drafts); cursor = data.cursor; if (!cursor) break; } return found;};
/** * Brings an account's drafts on Bluesky together with those here: one written elsewhere joins * its Drafts, one changed elsewhere (and not here since) takes the change, one gone from Bluesky * goes here too; and one here that Bluesky doesn't have yet, from before, or written offline, is * sent. Quietly does nothing if Bluesky can't be reached. */export const refreshDrafts = async (did: string) => { const as = await actingAsAccount(did); if (!as) return; let remote: AppBskyDraftDefs.DraftView[]; try { remote = await fetchAll(as); } catch (err) { console.warn("Could not read drafts from Bluesky", err); return; }
const local = allDrafts().filter((draft) => draft.account === did && !isReply(draft.id, draft)); const byRemote = new Map( local.flatMap((draft) => (draft.remoteId ? [[draft.remoteId, draft]] : [])), ); const seen = new Set<string>(); // Taken off from here: still listed, it's Bluesky catching up (or the deletion didn't reach // it), so asked again rather than brought back; no longer listed, it's done with. const gone = readGone(); const stillListed = new Set(remote.map((view) => view.id)); for (const remoteId of Object.keys(gone)) if (!stillListed.has(remoteId)) delete gone[remoteId]; writeGone(gone); for (const view of remote) { if (view.id in gone) { queue(`gone:${view.id}`, () => remove(as, view.id)); continue; } seen.add(view.id); // A thread's first post is the draft's own; the rest follow it, their words only (their // pictures stay on the device they were added on). const [post, ...rest] = view.draft.posts; const updatedAt = Date.parse(view.updatedAt) || Date.now(); const quote = post.embedRecords?.[0]?.record; const interaction = view.draft.threadgateAllow || view.draft.postgateEmbeddingRules ? fromGates(view.draft) : undefined; const media = post.embedImages?.length || post.embedGallery?.items.length || post.embedVideos?.length || post.embedExternals?.length ? { ...(post.embedImages ? { embedImages: post.embedImages } : {}), ...(post.embedGallery ? { embedGallery: post.embedGallery } : {}), ...(post.embedVideos ? { embedVideos: post.embedVideos } : {}), ...(post.embedExternals ? { embedExternals: post.embedExternals } : {}), } : undefined; const here = byRemote.get(view.id); if (here) { const changedThere = updatedAt > (here.syncedAt ?? 0) + SKEW; const changedHere = here.updatedAt > (here.syncedAt ?? 0); if (!changedThere || changedHere || running.has(here.id) || timers.has(here.id)) continue; const { id, ...draft } = here; keepRemoteDraft(id, { ...draft, text: post.text, more: moreFrom(rest, draft.more), quote, interaction, updatedAt, syncedAt: updatedAt, // Pictures added there, while this device has none of its own for it. ...(draft.media ? {} : { mediaElsewhere: media }), }); continue; } keepRemoteDraft(newDraftId(), { account: did, text: post.text, more: moreFrom(rest), quote, interaction, updatedAt, remoteId: view.id, syncedAt: updatedAt, // Its pictures are on the device it was written on; here, only its words. mediaElsewhere: media, }); } for (const draft of local) { // Gone from Bluesky, sent or thrown away elsewhere, and unchanged here since: gone here too. if (draft.remoteId && !seen.has(draft.remoteId)) { if (draft.updatedAt > (draft.syncedAt ?? 0) || running.has(draft.id)) continue; const ids = storageIdsOf(draft.id); forgetDraft(draft.id); ids.forEach((id) => void discardDraftImages(id)); } else if (!draft.remoteId && worthKeeping(draft)) { schedule(draft.id); } }};