import type { AppBskyFeedDefs, AppBskyFeedPost, AppBskyRichtextFacet } from "@atcute/bluesky"; import { ok } from "@atcute/client"; import { createSignal } from "solid-js"; import { createStore } from "solid-js/store"; import { agent } from "../auth/session"; import { yourAccounts } from "./accounts"; import { type Acting, actingAs, didOf } from "./api"; import type { DraftImage, DraftVideo } from "./draft-images"; import type { Draft } from "./drafts"; import { markNew, markStale } from "./feed"; import { interacted } from "./feed-interactions"; import { type DraftGif, gifDescription } from "./gifs"; import { gateRecords, type Interaction, newRecordKey } from "./interaction"; import { cardThumb, type LinkCard } from "./link-cards"; import { isDeleted } from "./posts"; import { parseRichText } from "./rich-text"; export { clipTo, firstLink, highlightSpans, lengthOf, MAX_LENGTH, postedText, splitIntoPosts, } from "./rich-text"; /** A description's longest, as Bluesky's app has it (the protocol sets none), in graphemes. */ export const MAX_ALT = 2000; const encoder = new TextEncoder(); /** Facets point into the post's text by UTF-8 byte, not by character. */ const byteAt = (text: string, index: number) => encoder.encode(text.slice(0, index)).length; /** * Some text as it's sent, and its mentions, links and tags as Bluesky stores them, in order and * not overlapping: markdown links as their words, linked; whatever's found in those words is * theirs. */ export const richTextOf = async ( written: string, ): Promise<{ text: string; facets: AppBskyRichtextFacet.Main[] }> => { const { text, features } = parseRichText(written); const resolved = await Promise.all( features.map(async (item): Promise => { const index = { byteStart: byteAt(text, item.outStart), byteEnd: byteAt(text, item.outEnd) }; if (item.kind === "link") { return { index, features: [{ $type: "app.bsky.richtext.facet#link", uri: item.uri as any }], }; } if (item.kind === "tag") { return { index, features: [{ $type: "app.bsky.richtext.facet#tag", tag: item.tag }] }; } try { const did = await didOf(item.handle.toLowerCase()); return { index, features: [{ $type: "app.bsky.richtext.facet#mention", did: did as any }], }; } catch { return undefined; } }), ); return { text, facets: resolved.filter((facet): facet is AppBskyRichtextFacet.Main => !!facet) }; }; /** * Posts sent from here in this session. Bluesky takes a moment to take in a new post, so its page, * opened at once, waits for it rather than calling it deleted. */ export const justPosted = new Set(); /** * Brings a post just sent into the account's own lists, once Bluesky has taken it in (a moment, * asked about a little longer apart each time, for up to about ten seconds): its Following and * its profile. Loaded again at once when you're at the top of the page; scrolled down, the "New * posts" button says so instead, so what you're reading doesn't move. */ export const showSentPost = async (as: Acting, uri: string) => { for (let attempt = 0; attempt < 8; attempt++) { await new Promise((resolve) => setTimeout(resolve, 400 + attempt * 300)); const found = await ok(as.rpc.get("app.bsky.feed.getPosts", { params: { uris: [uri as any] } })) .then((data) => data.posts.length > 0) .catch(() => false); if (!found) continue; const keys = [ `timeline:${as.did}`, `author:${as.did}:${as.did}`, `author-replies:${as.did}:${as.did}`, `author-media:${as.did}:${as.did}`, ]; if (scrollY < 200) markStale(...keys); else markNew(...keys); return; } }; /** * A reply asked for with a post's reply button: its thread opens its reply field, focused, once * it's showing. An object each time, so asking again for the same post still counts. */ const [replyWanted, setReplyWanted] = createSignal<{ uri: string }>(); export const wantReply = (uri: string) => setReplyWanted({ uri }); /** Whether a reply to this post was asked for and not yet taken up; taking it up if so. */ export const takeReplyWanted = (uri: string) => { if (replyWanted()?.uri !== uri) return false; setReplyWanted(undefined); return true; }; export { replyWanted }; /** * Replies sent from here in this session, by the post they answer: its thread shows them at once, * first among its replies, without loading everything again. */ const [sentReplies, setSentReplies] = createStore>({}); export const repliesSentTo = (uri: string) => sentReplies[uri] ?? []; /** * A reply as just sent, put together here from what was sent, to show at once: Bluesky can take * a moment to have it. Its own copy takes its place as soon as it comes. Its pictures are the * ones on this device; a video says it's processing until Bluesky's copy can play it. */ const sentViews = new Map(); export const sentView = (uri: string) => sentViews.get(uri); const localView = ( created: { uri: string; cid: string }, record: AppBskyFeedPost.Main, did: string, images: DraftImage[], ): AppBskyFeedDefs.PostView => { const you = yourAccounts().find((account) => account.did === did); const pictures = images.map((image) => { const url = URL.createObjectURL(image.blob); return { thumb: url, fullsize: url, alt: image.alt.trim(), aspectRatio: { width: image.width, height: image.height }, }; }); return { $type: "app.bsky.feed.defs#postView", uri: created.uri, cid: created.cid, author: { did, handle: you?.handle ?? did, displayName: you?.displayName, avatar: you?.avatar, }, record, ...(pictures.length && pictures.length <= 4 ? { embed: { $type: "app.bsky.embed.images#view", images: pictures } } : {}), // A video, with nothing to play yet: shown as processing until Bluesky's copy comes. ...(record.embed?.$type === "app.bsky.embed.video" ? { embed: { $type: "app.bsky.embed.video#view", cid: (record.embed as any).video?.ref?.$link ?? "", playlist: "", aspectRatio: (record.embed as any).aspectRatio, alt: (record.embed as any).alt, }, } : {}), replyCount: 0, repostCount: 0, likeCount: 0, quoteCount: 0, indexedAt: record.createdAt, viewer: {}, labels: [], } as any; }; /** * How many replies a post had as loaded when you first replied to it here, by address: your * replies are counted on top of that, until Bluesky's own count, loaded again, takes them in. */ const [replyBase, setReplyBase] = createStore>({}); export const noteRepliedTo = (post: { uri: string; replyCount?: number }) => { if (!(post.uri in replyBase)) setReplyBase(post.uri, post.replyCount ?? 0); }; /** Words without a link that opens or closes them: the link quoted, shown by its quote. */ const withoutEdgeLink = (text: string, link: string) => { const words = text.trim(); if (words.endsWith(link)) return words.slice(0, -link.length); if (words.startsWith(link)) return words.slice(link.length); return text; }; /** Quotes sent from here in this session, by the post they quote: counted on it at once. */ const [sentQuotes, setSentQuotes] = createStore>({}); export const quotesSentOf = (uri: string) => sentQuotes[uri] ?? []; /** How many quotes a post had as loaded when you first quoted it here, by address. */ const [quoteBase, setQuoteBase] = createStore>({}); export const noteQuoted = (post: { uri: string; quoteCount?: number }) => { if (!(post.uri in quoteBase)) setQuoteBase(post.uri, post.quoteCount ?? 0); }; /** How many quotes a post has, counting yours sent from here, less any since deleted. */ export const quoteCountOf = (post: { uri: string; quoteCount?: number }) => withYours(post.quoteCount ?? 0, quoteBase[post.uri], quotesSentOf(post.uri)); /** How many replies a post has, counting yours sent from here, less any since deleted. */ export const replyCountOf = (post: { uri: string; replyCount?: number }) => withYours(post.replyCount ?? 0, replyBase[post.uri], repliesSentTo(post.uri)); /** * A count with yours sent from here taken into account. Bluesky's own may not have them yet * (it's below what it was plus yours: yours are added) or may have them all (then any you've * since deleted come off it). */ const withYours = (counted: number, base: number | undefined, sent: string[]) => { if (base === undefined) return counted; const deleted = sent.filter((uri) => isDeleted(uri)).length; if (counted >= base + sent.length) return Math.max(0, counted - deleted); return Math.max(counted, base + sent.length - deleted); }; /** * Makes the post's record, with its threadgate and postgate if it has settings that need them: * all in one write, under one key, so a post never goes out without the rules asked for it. */ const create = async ( client: NonNullable>["pds"], repo: `did:${string}:${string}`, record: AppBskyFeedPost.Main, interaction: Interaction | undefined, ) => { const rkey = newRecordKey(); const gates = interaction ? gateRecords(`at://${repo}/app.bsky.feed.post/${rkey}`, interaction, record.createdAt) : []; if (!gates.length) { return ok( client.post("com.atproto.repo.createRecord", { input: { repo, collection: "app.bsky.feed.post", record }, }), ); } const { results } = await ok( client.post("com.atproto.repo.applyWrites", { input: { repo, writes: [ { collection: "app.bsky.feed.post", rkey, value: record }, ...gates.map((gate) => ({ ...gate, rkey })), ].map((write) => ({ $type: "com.atproto.repo.applyWrites#create" as const, ...write, collection: write.collection as `${string}.${string}.${string}`, value: write.value as Record, })), }, }), ); const made = results?.[0] as { uri?: string; cid?: string } | undefined; if (!made?.uri || !made.cid) throw new Error("Bluesky didn't say where the post went."); return { uri: made.uri, cid: made.cid }; }; /** * Sends a post from the account you're signed in as, with its pictures uploaded first (or its * video, uploaded already), and returns where it went: its address and version. */ export const publish = async ( text: string, images: DraftImage[] = [], as = actingAs(agent()), video?: DraftVideo, /** The post it answers, for a reply. */ reply?: Draft["reply"], /** The post it quotes, for a quote. */ quote?: Draft["quote"], /** What it's written in, as tags for Bluesky's language filters; the browser's if none. */ langs?: string[], /** * Who may reply and quote: for a new post, both; for a later post of a thread written here, * only whether it can be quoted, as replies follow the thread's first post. None for a reply. */ interaction?: Interaction, /** A GIF, in place of pictures or a video. */ gif?: DraftGif, /** What its first link adds: a card for the page, or a post to quote. */ card?: LinkCard, /** Warnings on its pictures or video, for apps to blur them for those who'd rather not see. */ labels?: string[], ) => { // A post linked, quoted as Bluesky's composer quotes it, unless another is already; its link // goes from the words when it opens or closes them, the quote saying it already. One in the // middle of a sentence stays, as part of what's said. if (!quote && card?.kind === "post") { quote = { uri: card.post.uri, cid: card.post.cid }; text = withoutEdgeLink(text, card.written); } if (!as) throw new Error("Sign in to post."); const me = as.did as `did:${string}:${string}`; const client = as.pds; // Two or more empty lines in a row fold into one, as Bluesky's own app does. const trimmed = text.trim().replace(/\r?\n(?:[ \t]*\r?\n){2,}/g, "\n\n"); const rich = await richTextOf(trimmed); const record: AppBskyFeedPost.Main = { $type: "app.bsky.feed.post", text: rich.text, facets: rich.facets, langs: langs?.length ? langs : [navigator.language.split("-")[0]], createdAt: new Date().toISOString(), }; if (!record.facets?.length) delete record.facets; if (labels?.length) { record.labels = { $type: "com.atproto.label.defs#selfLabels", values: labels.map((val) => ({ val })), }; } if (reply) record.reply = reply as AppBskyFeedPost.ReplyRef; // A video, already with Bluesky by now (it's sent as soon as it's added). if (video?.uploaded) { // Its captions, each file sent now as WebVTT, as Bluesky takes them. const captions = []; for (const each of video.captions ?? []) { const file = new Blob([each.blob], { type: "text/vtt" }); const { blob } = await ok(client.post("com.atproto.repo.uploadBlob", { input: file })); captions.push({ lang: each.lang, file: blob }); } record.embed = { $type: "app.bsky.embed.video", video: video.uploaded.blob, aspectRatio: { width: video.width, height: video.height }, ...(video.alt.trim() ? { alt: video.alt.trim() } : {}), ...(captions.length ? { captions } : {}), } as any; } else if (images.length) { const uploaded = []; for (const image of images) { const { blob } = await ok(client.post("com.atproto.repo.uploadBlob", { input: image.blob })); uploaded.push({ image: blob, alt: image.alt.trim(), aspectRatio: { width: image.width, height: image.height }, }); } // Up to four as Bluesky's long-standing picture embed, which every app shows; more than that // as a gallery, which holds up to ten. record.embed = uploaded.length <= 4 ? { $type: "app.bsky.embed.images", images: uploaded } : ({ $type: "app.bsky.embed.gallery", items: uploaded.map((item) => ({ $type: "app.bsky.embed.gallery#image", ...item })), } as any); } // A GIF, as Bluesky's app shares one: a link card to it, its still as the card's picture. // Without the still if it can't be had: the GIF plays all the same. if (gif && !record.embed) { const thumb = await fetch(gif.still) .then((res) => (res.ok ? res.blob() : undefined)) .then((still) => still && still.size <= 1_000_000 ? ok(client.post("com.atproto.repo.uploadBlob", { input: still })).then((up) => up.blob) : undefined, ) .catch(() => undefined); record.embed = { $type: "app.bsky.embed.external", external: { uri: gif.uri as `${string}:${string}`, title: gif.title, description: gifDescription(gif), ...(thumb ? { thumb } : {}), }, }; } // A page's card, in a post with nothing else to show: its picture uploaded as the card's, // without it if it can't be had. Not beside a quote, which comes first. if (card?.kind === "page" && !record.embed && !quote) { const still = card.image ? await cardThumb(card.image) : undefined; const thumb = still ? await ok(client.post("com.atproto.repo.uploadBlob", { input: still })) .then((up) => up.blob) .catch(() => undefined) : undefined; record.embed = { $type: "app.bsky.embed.external", external: { uri: card.uri as `${string}:${string}`, title: card.title, description: card.description, ...(thumb ? { thumb } : {}), }, }; } // A quote: the post quoted, under its pictures, video or GIF if it has any. if (quote) { const ref = { $type: "app.bsky.embed.record", record: quote }; record.embed = ( record.embed ? { $type: "app.bsky.embed.recordWithMedia", record: ref, media: record.embed } : ref ) as any; } const created = await create(client, me, record, interaction); justPosted.add(created.uri); if (quote) setSentQuotes(quote.uri, (sent = []) => [created.uri, ...sent]); // Told to the feed what's answered or quoted came from, if it asks. if (quote) interacted(as.did, quote.uri, "interactionQuote"); if (reply) interacted(as.did, reply.parent.uri, "interactionReply"); if (reply) { sentViews.set(created.uri, localView(created, record, as.did, images)); setSentReplies(reply.parent.uri, (sent = []) => [created.uri, ...sent]); } return { uri: created.uri, cid: created.cid }; };