Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171import { type $Typed, type AppBskyEmbedExternal, type AppBskyEmbedGallery, type AppBskyEmbedImages, type AppBskyEmbedRecord, type AppBskyEmbedRecordWithMedia, type AppBskyEmbedVideo, AppBskyFeedPost, type AtpAgent, AtUri, BlobRef, ChatBskyGroupDefs, type ComAtprotoLabelDefs, type ComAtprotoRepoApplyWrites, type ComAtprotoRepoStrongRef, jsonToLex, RichText,} from '@atproto/api'import {TID} from '@atproto/common-web'import {t} from '@lingui/core/macro'import {type QueryClient} from '@tanstack/react-query'import {sha256} from 'js-sha256'import {CID} from 'multiformats/cid'import * as Hasher from 'multiformats/hashes/hasher'
import { assemblyThumbUrl, buildAssemblyExternal, ensureAssembly,} from '#/lib/api/assembly'import {communityXrpc} from '#/lib/api/community'import { admitFeedPost, fetchCommunityFeedTarget, isSpaceBackedFeed,} from '#/lib/api/community-feed'import {fetchCommunityPostView} from '#/lib/api/community-post'import { type AssemblyRef, type PollDraft, pollStatementsForPublish, pollTopicFromText,} from '#/lib/api/poll'import {imageToThumb} from '#/lib/api/resolve'import {spaceOfPostUrl} from '#/lib/api/space-permalink'import {postToSpace} from '#/lib/api/space-post'import {isSpaceRecordUri, spaceOfRecordUri} from '#/lib/api/space-uri'import {IMAGE_SIZE_CONFIG_POSTS} from '#/lib/constants'import {isNetworkError} from '#/lib/strings/errors'import {shortenLinks, stripInvalidMentions} from '#/lib/strings/rich-text-manip'import {logger} from '#/logger'import {compressImage} from '#/state/gallery'import { fetchResolveGifQuery, fetchResolveLinkQuery,} from '#/state/queries/resolve-link'import { createThreadgateRecord, threadgateAllowUISettingToAllowRecordValue,} from '#/state/queries/threadgate'import { type EmbedDraft, type PostDraft, type ThreadDraft,} from '#/view/com/composer/state/composer'import * as bsky from '#/types/bsky'import {createGIFDescription} from '../gif-alt-text'import {uploadBlob} from './upload-blob'
export {uploadBlob}
const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post'const ASSEMBLY_THUMB_TIMEOUT_MS = 5e3
/** * The space a quote belongs to, whichever form it is in — a pasted permalink * carries the space in `?space=` and is only expanded to its at:// form at * publish, long after routing has decided where the post goes. */export function quotedSpace(uri?: string | null): string | null { return spaceOfRecordUri(uri) ?? spaceOfPostUrl(uri)}
function embedNamesSpaceRecord(embed: unknown): boolean { if (!embed || typeof embed !== 'object') return false const record = (embed as {record?: unknown}).record if (!record || typeof record !== 'object') return false const uri = (record as {uri?: unknown}).uri ?? (record as {record?: {uri?: unknown}}).record?.uri return typeof uri === 'string' && isSpaceRecordUri(uri)}
function refusePoll(thread: ThreadDraft) { if (thread.posts.some(p => p.embed.poll)) { throw new Error(t`Discussions are only available on public posts.`) }}
function refusePollWithAttachments(draft: PostDraft) { if ( draft.embed.poll && (draft.embed.media || draft.embed.link || draft.embed.quote) ) { throw new Error( t`A discussion cannot be combined with media, a link card or a quote.`, ) }}
function findPollPost(thread: ThreadDraft): PostDraft | undefined { const [pollPost, ...others] = thread.posts.filter(p => p.embed.poll) if (others.length) { throw new Error(t`A thread can only have one discussion.`) } if (pollPost) { refusePollWithAttachments(pollPost) } return pollPost}
export interface PostOpts { thread: ThreadDraft draftId?: string replyTo?: string onStateChange?: (state: string) => void onAssembly?: (postId: string, ref: AssemblyRef) => void langs?: string[]}
export type PostResult = { uris: string[] assembly?: { conversationId: string statementCount: number isReplay: boolean }}
export async function post( agent: AtpAgent, queryClient: QueryClient, opts: PostOpts,): Promise<PostResult> { let thread = opts.thread const replySpace = spaceOfRecordUri(opts.replyTo) // Replying to or quoting a space post: the parent's space is the target, and // no feed needs resolving — a feed is only a view over the space. if (thread.communitySpaceUri || replySpace) { const space = thread.communitySpaceUri ?? replySpace! if ( thread.communitySpaceUri && replySpace && thread.communitySpaceUri !== replySpace ) { throw new Error( t`This reply targets a different private space than its parent.`, ) } refusePoll(thread) return postToSpace(agent, queryClient, space, opts) }
if (!thread.communityFeed && thread.communityFeedUri) { const target = await fetchCommunityFeedTarget( agent, thread.communityFeedUri, ) if (!target) { throw new Error( t`You no longer have permission to post to this community.`, ) } thread = {...thread, communityFeed: target} opts = {...opts, thread} } opts.onStateChange?.(t`Processing...`)
// A space-backed feed keeps its content in the author's permissioned repo, // so it takes an entirely different write path and must be checked before // the community routing below, which would otherwise claim it. const config = thread.communityFeed?.config if (isSpaceBackedFeed(config)) { refusePoll(thread) return postToSpace(agent, queryClient, config.space, opts) }
// Past this point the post is going to a public or community repo, not into // any space, so nothing it carries may name one. A quote reaches the composer // as a pasted link and is only expanded to its at:// form at publish, by // which time the routing decision is made — so both forms are refused here, // together. Without this a pasted space permalink rides `postCommunity`'s // stub embed into the author's public repo, publishing the existence of a // private post. if (thread.posts.some(p => quotedSpace(p.embed.quote?.uri))) { throw new Error( t`This is a private post. You can only quote it in a post to that space.`, ) }
// Route to community post endpoint if the user explicitly toggled // Blacksky-Only, is replying to a community post, or is quoting one. const isReplyToCommunityPost = opts.replyTo && opts.replyTo.includes(COMMUNITY_POST_COLLECTION) const isQuoteOfCommunityPost = thread.posts.some(p => p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION), ) const selectedCommunityRecordFeed = thread.communityFeed?.config.contentType === 'communityRecord'
if ( thread.blackskyOnly || selectedCommunityRecordFeed || isReplyToCommunityPost || isQuoteOfCommunityPost ) { refusePoll(thread) return postCommunity(agent, queryClient, opts) }
// A public post must never carry a community post in its embed; the // routing above sends those to postCommunity, so reaching here with one // is a bug we refuse rather than leak community content publicly. A space // record is refused for the same reason, and its URI would leak the space // even if the appview declined to hydrate it. if ( thread.posts.some( p => p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION) || isSpaceRecordUri(p.embed.quote?.uri), ) ) { throw new Error('Public posts cannot embed a community post') }
const pollPost = findPollPost(thread)
let replyPromise: | Promise<AppBskyFeedPost.Record['reply']> | AppBskyFeedPost.Record['reply'] | undefined if (opts.replyTo) { // Not awaited to avoid waterfalls. replyPromise = resolveReply(agent, opts.replyTo) }
let assembly: PostResult['assembly'] const poll = pollPost?.embed.poll if (pollPost && poll) { // An assembly is public and cannot be withdrawn, so a reply whose parent // is gone has to fail before one is started. await replyPromise opts.onStateChange?.(t`Starting discussion...`) const statements = pollStatementsForPublish(poll) const {ref, isReplay} = await ensureAssembly(agent, { topic: pollTopicFromText(pollPost.richtext.text), statements, ref: poll.assembly, onRef: next => opts.onAssembly?.(pollPost.id, next), }) assembly = { conversationId: ref.conversationId, statementCount: statements.length, isReplay, } thread = { ...thread, posts: thread.posts.map(p => p === pollPost ? {...p, embed: {...p.embed, poll: {...poll, assembly: ref}}} : p, ), } }
// add top 3 languages from user preferences if langs is provided let langs = opts.langs if (opts.langs) { langs = opts.langs.slice(0, 3) }
const did = agent.assertDid const writes: $Typed<ComAtprotoRepoApplyWrites.Create>[] = [] const uris: string[] = [] const admissions: Array<{post: string; cid: string}> = []
let now = new Date() let tid: TID | undefined
for (let i = 0; i < thread.posts.length; i++) { const draft = thread.posts[i]
// Not awaited to avoid waterfalls. const rtPromise = resolveRT(agent, draft.richtext) const embedPromise = resolveEmbed( agent, queryClient, draft, opts.onStateChange, ) let labels: $Typed<ComAtprotoLabelDefs.SelfLabels> | undefined if (draft.labels.length) { labels = { $type: 'com.atproto.label.defs#selfLabels', values: draft.labels.map(val => ({val})), } }
// The sorting behavior for multiple posts sharing the same createdAt time is // undefined, so what we'll do here is increment the time by 1 for every post now.setMilliseconds(now.getMilliseconds() + 1) tid = TID.next(tid) const rkey = tid.toString() const uri = `at://${did}/app.bsky.feed.post/${rkey}` uris.push(uri)
const rt = await rtPromise const embed = await embedPromise const reply = await replyPromise const record: AppBskyFeedPost.Record = { // IMPORTANT: $type has to exist, CID is calculated with the `$type` field // present and will produce the wrong CID if you omit it. $type: 'app.bsky.feed.post', createdAt: now.toISOString(), text: rt.text, facets: rt.facets, reply, embed, langs, labels, } writes.push({ $type: 'com.atproto.repo.applyWrites#create', collection: 'app.bsky.feed.post', rkey: rkey, value: record, })
if (i === 0 && thread.threadgate.some(tg => tg.type !== 'everybody')) { writes.push({ $type: 'com.atproto.repo.applyWrites#create', collection: 'app.bsky.feed.threadgate', rkey: rkey, value: createThreadgateRecord({ createdAt: now.toISOString(), post: uri, allow: threadgateAllowUISettingToAllowRecordValue(thread.threadgate), }), }) }
if ( thread.postgate.embeddingRules?.length || thread.postgate.detachedEmbeddingUris?.length ) { writes.push({ $type: 'com.atproto.repo.applyWrites#create', collection: 'app.bsky.feed.postgate', rkey: rkey, value: { ...thread.postgate, $type: 'app.bsky.feed.postgate', createdAt: now.toISOString(), post: uri, }, }) }
// Prepare a ref to the current post for the next post in the thread. const ref = { cid: await computeCid(record), uri, } if (thread.communityFeed?.config.contentType === 'publicRecord') { admissions.push({post: uri, cid: ref.cid}) } replyPromise = { root: reply?.root ?? ref, parent: ref, } }
try { await agent.com.atproto.repo.applyWrites({ repo: agent.assertDid, writes: writes, validate: true, }) } catch (err) { const e = err as Error logger.error(`Failed to create post`, { safeMessage: e.message, }) if (isNetworkError(e)) { throw new Error( t`Post failed to upload. Please check your Internet connection and try again.`, ) } else { throw e } }
if (thread.communityFeed?.config.contentType === 'publicRecord') { await Promise.all( admissions.map(({post, cid}) => admitFeedPost(agent, thread.communityFeed!, post, cid), ), ) }
return {uris, assembly}}
async function postCommunity( agent: AtpAgent, queryClient: QueryClient, opts: PostOpts,) { const thread = opts.thread
let replyPromise: | Promise<AppBskyFeedPost.Record['reply']> | AppBskyFeedPost.Record['reply'] | undefined if (opts.replyTo) { replyPromise = resolveReply(agent, opts.replyTo) }
let langs = opts.langs if (opts.langs) { langs = opts.langs.slice(0, 3) }
const did = agent.assertDid const writes: $Typed<ComAtprotoRepoApplyWrites.Create>[] = [] const uris: string[] = [] const admissions: Array<{post: string; cid: string}> = []
let now = new Date() let tid: TID | undefined
for (let i = 0; i < thread.posts.length; i++) { const draft = thread.posts[i]
const rtPromise = resolveRT(agent, draft.richtext) const embedPromise = resolveEmbed( agent, queryClient, draft, opts.onStateChange, ) let labels: $Typed<ComAtprotoLabelDefs.SelfLabels> | undefined if (draft.labels.length) { labels = { $type: 'com.atproto.label.defs#selfLabels', values: draft.labels.map(val => ({val})), } }
now.setMilliseconds(now.getMilliseconds() + 1) tid = TID.next(tid) const rkey = tid.toString() const uri = `at://${did}/${COMMUNITY_POST_COLLECTION}/${rkey}` uris.push(uri)
const rt = await rtPromise const resolvedEmbed = await embedPromise const reply = await replyPromise
// Community posts use the community video embed type, which allows // larger files than app.bsky.embed.video permits. const embed = resolvedEmbed?.$type === 'app.bsky.embed.video' ? {...resolvedEmbed, $type: 'community.blacksky.embed.video'} : resolvedEmbed
// Step 1: Build the canonical record for CID computation // This MUST match the structure the appview uses for CID verification const createdAt = now.toISOString() const canonicalRecord: Record<string, unknown> = { $type: COMMUNITY_POST_COLLECTION, text: rt.text, createdAt, } if (rt.facets?.length) { canonicalRecord.facets = rt.facets } if (langs?.length) { canonicalRecord.langs = langs } if (embed) { canonicalRecord.embed = embed } if (reply) { canonicalRecord.reply = reply }
// Step 2: Compute CID locally - this is the SOURCE OF TRUTH for integrity const cid = await computeCid( canonicalRecord as unknown as AppBskyFeedPost.Record, )
// Step 3: Submit to appview with expectedCid for verification opts.onStateChange?.(t`Submitting to community...`) const submitBody: Record<string, unknown> = { rkey, text: rt.text, createdAt, expectedCid: cid, // Appview will verify this matches } if (rt.facets?.length) { submitBody.facets = rt.facets } if (reply) { submitBody.reply = reply } if (embed) { submitBody.embed = embed } if (langs?.length) { submitBody.langs = langs } if (labels) { submitBody.labels = labels } // Interaction gates: root posts only for threadgates, community $types. if (!reply && thread.threadgate.some(tg => tg.type !== 'everybody')) { submitBody.threadgateAllow = ( threadgateAllowUISettingToAllowRecordValue(thread.threadgate) ?? [] ).map(rule => ({ ...rule, $type: String(rule.$type).replace( 'app.bsky.feed.threadgate', 'community.blacksky.feed.threadgate', ), })) } if (thread.postgate.embeddingRules?.length) { submitBody.embeddingRules = thread.postgate.embeddingRules.map(rule => ({ ...rule, $type: rule.$type.replace( 'app.bsky.feed.postgate', 'community.blacksky.feed.postgate', ), })) }
try { const submitRes = await communityXrpc( agent, 'community.blacksky.feed.submitPost', // No serviceDid: submitPost serves the Blacksky community feed, whose // content lives on the home appview. `contentStore` named a per-feed // appview for the retired multi-tenant path and was always undefined // here, so the proxy target is unchanged. {body: submitBody}, ) if (!submitRes.ok) { const errBody = (await submitRes.json().catch(() => ({}))) as { message?: string } throw new Error(errBody.message || `HTTP ${submitRes.status}`) } // Appview returns the verified CID - should match our local computation const submitData = (await submitRes.json()) as {cid?: string} if (submitData?.cid !== cid) { logger.warn(`CID mismatch: local=${cid}, server=${submitData?.cid}`) } } catch (e) { const serverMessage = e instanceof Error ? e.message : String(e) logger.error(`Failed to submit community post content`, { safeMessage: serverMessage, }) // Surface the server's reason (e.g. threadgate/quote restrictions) // instead of a generic failure. const isUserFacing = serverMessage && !serverMessage.startsWith('HTTP') && !/InternalServerError|fetch|network/i.test(serverMessage) throw new Error( isUserFacing ? serverMessage : t`Failed to submit community post. Please try again.`, ) }
// Step 4: Build stub record for PDS with CLIENT-COMPUTED CID const stubRecord: Record<string, unknown> = { $type: COMMUNITY_POST_COLLECTION, createdAt, cid, // Client's own CID - source of truth for integrity verification } // The PDS only protects blobs that are referenced from a record on the // repo (enumBlobRefs walks the record tree). Mirror the embed onto the // stub so external-thumb / image / video / gallery blobs stay alive for // the post's lifetime. Text / facets / langs / reply remain appview-only. if (embed) { // The stub goes to the author's public repo, so it is the last place a // space URI could leak from. The routing guard in `post` already refuses // these; this is the invariant restated where the write happens. if (embedNamesSpaceRecord(embed)) { throw new Error( t`This is a private post. You can only quote it in a post to that space.`, ) } stubRecord.embed = embed }
writes.push({ $type: 'com.atproto.repo.applyWrites#create', collection: COMMUNITY_POST_COLLECTION, rkey, value: stubRecord, })
// Prepare ref for next post in thread const ref = { cid: await computeCid(stubRecord as unknown as AppBskyFeedPost.Record), uri, } if (thread.communityFeed) { admissions.push({post: uri, cid: ref.cid}) } replyPromise = { root: reply?.root ?? ref, parent: ref, } }
// Write stubs to PDS try { await agent.com.atproto.repo.applyWrites({ repo: agent.assertDid, writes, validate: false, }) } catch (e) { logger.error(`Failed to write community post stubs`, { safeMessage: e instanceof Error ? e.message : String(e), }) if (isNetworkError(e)) { throw new Error( t`Post failed to upload. Please check your Internet connection and try again.`, ) } else { throw e } }
if (thread.communityFeed) { await Promise.all( admissions.map(({post, cid}) => admitFeedPost(agent, thread.communityFeed!, post, cid), ), ) }
void queryClient.invalidateQueries({queryKey: ['community-timeline']}) void queryClient.invalidateQueries({queryKey: ['community-feed']})
return {uris}}
export async function resolveRT(agent: AtpAgent, richtext: RichText) { const trimmedText = richtext.text // Trim leading whitespace-only lines (but don't break ASCII art). .replace(/^(\s*\n)+/, '') // Trim any trailing whitespace. .trimEnd() let rt = new RichText({text: trimmedText}, {cleanNewlines: true}) await rt.detectFacets(agent)
rt = shortenLinks(rt) rt = stripInvalidMentions(rt) return rt}
export class ReplyDeletedError extends Error { constructor() { super('Could not resolve reply') }}
/** * The reply refs a caller gets back from the non-space branches go straight * into a public `app.bsky.feed.post`, so a thread root that turns out to name a * space has to stop here: the space branch above is the only one allowed to * return one. */function refusePublicSpaceRefs< T extends {root: {uri: string}; parent: {uri: string}},>(refs: T): T { if (isSpaceRecordUri(refs.root.uri) || isSpaceRecordUri(refs.parent.uri)) { throw new Error( t`This is a private post. You can only reply to it in that space.`, ) } return refs}
export async function resolveReply(agent: AtpAgent, replyTo: string) { // Space records first: they are not at-uris, so AtUri would misparse one. // The parent is read back through the appview, which is the only read path // the client has into a space, and carries the root of its own thread. if (isSpaceRecordUri(replyTo)) { const post = await fetchCommunityPostView(agent, replyTo) const parent = {uri: post.uri, cid: post.cid} const root = ( post.record as {reply?: {root?: {uri?: string; cid?: string}}} )?.reply?.root return { root: root?.uri && root?.cid ? {uri: root.uri, cid: root.cid} : parent, parent, } }
const replyToUrip = new AtUri(replyTo)
// Community posts are fetched from the appview, not the standard feed API. if (replyToUrip.collection === COMMUNITY_POST_COLLECTION) { const res = await communityXrpc( agent, 'community.blacksky.feed.getCommunityPost', {params: {uri: replyTo}}, ) if (!res.ok) { logger.error('Failed to fetch parent community post for reply', { uri: replyTo, }) return undefined } const data = jsonToLex(await res.json()) as { post?: { uri: string cid: string record?: AppBskyFeedPost.Record } } if (data.post) { const parentRef = {uri: data.post.uri, cid: data.post.cid} // A reply inherits its parent's root; the parent is only the root // when it is itself a top-level post. const parentRootRef = data.post.record?.reply?.root const rootRef = parentRootRef?.uri && parentRootRef?.cid ? {uri: parentRootRef.uri, cid: parentRootRef.cid} : parentRef return refusePublicSpaceRefs({root: rootRef, parent: parentRef}) } return undefined }
// Standard Bluesky post const {data} = await agent.app.bsky.feed.getPosts({ uris: [replyTo], }) const parentPost = data.posts[0] if (!parentPost) { throw new ReplyDeletedError() }
const parentRef = { uri: parentPost.uri, cid: parentPost.cid, } let rootRef = parentRef
if ( bsky.dangerousIsType<AppBskyFeedPost.Record>( parentPost.record, AppBskyFeedPost.isRecord, ) ) { if (parentPost.record.reply) { rootRef = parentPost.record.reply.root } }
return refusePublicSpaceRefs({ root: rootRef, parent: parentRef, })}
export async function resolveEmbed( agent: AtpAgent, queryClient: QueryClient, draft: PostDraft, onStateChange: ((state: string) => void) | undefined,): Promise< | $Typed<AppBskyEmbedImages.Main> | $Typed<AppBskyEmbedGallery.Main> | $Typed<AppBskyEmbedVideo.Main> | $Typed<AppBskyEmbedExternal.Main> | $Typed<AppBskyEmbedRecord.Main> | $Typed<AppBskyEmbedRecordWithMedia.Main> | undefined> { if (draft.embed.poll) { return resolveAssembly(agent, draft, draft.embed.poll, onStateChange) } if (draft.embed.quote) { const [resolvedMedia, resolvedQuote] = await Promise.all([ resolveMedia(agent, queryClient, draft.embed, onStateChange), resolveRecord(agent, queryClient, draft.embed.quote.uri), ]) if (resolvedMedia) { return { $type: 'app.bsky.embed.recordWithMedia', record: { $type: 'app.bsky.embed.record', record: resolvedQuote, }, media: resolvedMedia, } } return { $type: 'app.bsky.embed.record', record: resolvedQuote, } } const resolvedMedia = await resolveMedia( agent, queryClient, draft.embed, onStateChange, ) if (resolvedMedia) { return resolvedMedia } if (draft.embed.link) { const resolvedLink = await fetchResolveLinkQuery( queryClient, agent, draft.embed.link.uri, ) if (resolvedLink.type === 'record') { return { $type: 'app.bsky.embed.record', record: resolvedLink.record, } } } return undefined}
async function resolveAssembly( agent: AtpAgent, draft: PostDraft, poll: PollDraft, onStateChange: ((state: string) => void) | undefined,): Promise<$Typed<AppBskyEmbedExternal.Main>> { refusePollWithAttachments(draft) const conversationId = poll.assembly?.conversationId if (!conversationId) { throw new Error('A poll cannot be posted before its assembly exists') } return { $type: 'app.bsky.embed.external', external: { ...buildAssemblyExternal({ conversationId, topic: pollTopicFromText(draft.richtext.text), statements: pollStatementsForPublish(poll), }), thumb: await uploadAssemblyThumb(agent, conversationId, onStateChange), }, }}
async function uploadAssemblyThumb( agent: AtpAgent, conversationId: string, onStateChange: ((state: string) => void) | undefined,): Promise<BlobRef | undefined> { let timer: ReturnType<typeof setTimeout> | undefined try { const thumb = await Promise.race([ imageToThumb(assemblyThumbUrl(conversationId)), new Promise<undefined>(resolve => { timer = setTimeout(() => resolve(undefined), ASSEMBLY_THUMB_TIMEOUT_MS) }), ]) if (!thumb) throw new Error('The image could not be read in time') onStateChange?.(t`Uploading link thumbnail...`) const {path, mime} = thumb.source const response = await uploadBlob(agent, path, mime) return response.data.blob } catch (e) { logger.warn(`Failed to attach the poll thumbnail`, { safeMessage: e instanceof Error ? e.message : String(e), }) return undefined } finally { clearTimeout(timer) }}
async function resolveMedia( agent: AtpAgent, queryClient: QueryClient, embedDraft: EmbedDraft, onStateChange: ((state: string) => void) | undefined,): Promise< | $Typed<AppBskyEmbedExternal.Main> | $Typed<AppBskyEmbedImages.Main> | $Typed<AppBskyEmbedGallery.Main> | $Typed<AppBskyEmbedVideo.Main> | undefined> { if (embedDraft.media?.type === 'images') { const imagesDraft = embedDraft.media.images logger.debug(`Uploading images`, { count: imagesDraft.length, }) onStateChange?.(t`Uploading images...`) const images: AppBskyEmbedImages.Image[] = await Promise.all( imagesDraft.map(async (image, i) => { logger.debug(`Compressing image #${i}`) const {path, width, height, mime} = await compressImage( image, IMAGE_SIZE_CONFIG_POSTS, ) logger.debug(`Uploading image #${i}`) const res = await uploadBlob(agent, path, mime) return { image: res.data.blob, alt: image.alt, aspectRatio: {width, height}, } }), ) return { $type: 'app.bsky.embed.images', images, } } if (embedDraft.media?.type === 'gallery') { const imagesDraft = embedDraft.media.images logger.debug(`Uploading images`, { count: imagesDraft.length, }) onStateChange?.(t`Uploading images...`) const items: $Typed<AppBskyEmbedGallery.Image>[] = await Promise.all( imagesDraft.map(async (image, i) => { logger.debug(`Compressing image #${i}`) const {path, width, height, mime} = await compressImage( image, IMAGE_SIZE_CONFIG_POSTS, ) logger.debug(`Uploading image #${i}`) const res = await uploadBlob(agent, path, mime) return { $type: 'app.bsky.embed.gallery#image' as const, image: res.data.blob, alt: image.alt, aspectRatio: {width, height}, } }), ) return { $type: 'app.bsky.embed.gallery', items, } } if ( embedDraft.media?.type === 'video' && embedDraft.media.video.status === 'done' ) { const videoDraft = embedDraft.media.video const captions = await Promise.all( videoDraft.captions .filter(caption => caption.lang !== '') .map(async caption => { const {data} = await agent.uploadBlob(caption.file, { encoding: 'text/vtt', }) return {lang: caption.lang, file: data.blob} }), )
// lexicon numbers must be floats const width = Math.round(videoDraft.asset.width) const height = Math.round(videoDraft.asset.height)
// aspect ratio values must be >0 - better to leave as unset otherwise // posting will fail if aspect ratio is set to 0 const aspectRatio = width > 0 && height > 0 ? {width, height} : undefined
if (!aspectRatio) { logger.error( `Invalid aspect ratio - got { width: ${videoDraft.asset.width}, height: ${videoDraft.asset.height} }`, ) }
return { $type: 'app.bsky.embed.video', video: videoDraft.pendingPublish.blobRef, alt: videoDraft.altText || undefined, captions: captions.length === 0 ? undefined : captions, aspectRatio, presentation: videoDraft.video.mimeType === 'image/gif' ? 'gif' : 'default', } } if (embedDraft.media?.type === 'gif') { const gifDraft = embedDraft.media const resolvedGif = await fetchResolveGifQuery( queryClient, agent, gifDraft.gif, ) let blob: BlobRef | undefined if (resolvedGif.thumb) { onStateChange?.(t`Uploading link thumbnail...`) const {path, mime} = resolvedGif.thumb.source const response = await uploadBlob(agent, path, mime) blob = response.data.blob } return { $type: 'app.bsky.embed.external', external: { uri: resolvedGif.uri, title: resolvedGif.title, description: createGIFDescription(resolvedGif.title, gifDraft.alt), thumb: blob, }, } } if (embedDraft.link) { const resolvedLink = await fetchResolveLinkQuery( queryClient, agent, embedDraft.link.uri, ) if (resolvedLink.type === 'external') { let blob: BlobRef | undefined if (resolvedLink.thumb) { onStateChange?.(t`Uploading link thumbnail...`) const {path, mime} = resolvedLink.thumb.source const response = await uploadBlob(agent, path, mime) blob = response.data.blob } return { $type: 'app.bsky.embed.external', external: { uri: resolvedLink.uri, title: resolvedLink.title, description: resolvedLink.description, thumb: blob, associatedRefs: resolvedLink.associatedRefs, }, } } if ( resolvedLink.type === 'chat-invite' && ChatBskyGroupDefs.isJoinLinkPreviewView(resolvedLink.view) ) { return { $type: 'app.bsky.embed.external', external: { uri: resolvedLink.uri, title: resolvedLink.view.name, description: `${resolvedLink.view.memberCount}/${resolvedLink.view.memberLimit}`, }, } } } return undefined}
async function resolveRecord( agent: AtpAgent, queryClient: QueryClient, uri: string,): Promise<ComAtprotoRepoStrongRef.Main> { const resolvedLink = await fetchResolveLinkQuery(queryClient, agent, uri) if (resolvedLink.type !== 'record') { throw Error(t`Expected uri to resolve to a record`) } return resolvedLink.record}
// The built-in hashing functions from multiformats (`multiformats/hashes/sha2`)// are meant for Node.js, this is the cross-platform equivalent.const mf_sha256 = Hasher.from({ name: 'sha2-256', code: 0x12, encode: input => { const digest = sha256.arrayBuffer(input) return new Uint8Array(digest) },})
async function computeCid(record: AppBskyFeedPost.Record): Promise<string> { /* * Lazily loaded since it's only needed when posting a thread, and its * `cborg` dependency is ~190KB that would otherwise be in the initial * web bundle. */ const dcbor = await import('@ipld/dag-cbor') // IMPORTANT: `prepareObject` prepares the record to be hashed by removing // fields with undefined value, and converting BlobRef instances to the // right IPLD representation. const prepared = prepareForHashing(record) // 1. Encode the record into DAG-CBOR format const encoded = dcbor.encode(prepared) // 2. Hash the record in SHA-256 (code 0x12) const digest = await mf_sha256.digest(encoded) // 3. Create a CIDv1, specifying DAG-CBOR as content (code 0x71) const cid = CID.createV1(0x71, digest) // 4. Get the Base32 representation of the CID (`b` prefix) return cid.toString()}
// Returns a transformed version of the object for use in DAG-CBOR.// eslint-disable-next-line @typescript-eslint/no-explicit-anyfunction prepareForHashing(v: any): any { // IMPORTANT: BlobRef#ipld() returns the correct object we need for hashing, // the API client will convert this for you but we're hashing in the client, // so we need it *now*. if (v instanceof BlobRef) { return v.ipld() }
// Walk through arrays if (Array.isArray(v)) { let pure = true const mapped = v.map(value => { if (value !== (value = prepareForHashing(value))) { pure = false } return value }) return pure ? v : mapped }
// Walk through plain objects if (isPlainObject(v)) { const obj: Record<string, unknown> = {} let pure = true for (const key in v) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access let value = v[key] // `value` is undefined if (value === undefined) { pure = false continue } // `prepareObject` returned a value that's different from what we had before if (value !== (value = prepareForHashing(value))) { pure = false } obj[key] = value } // Return as is if we haven't needed to tamper with anything return pure ? v : obj } return v}
// eslint-disable-next-line @typescript-eslint/no-explicit-anyfunction isPlainObject(v: any): boolean { if (typeof v !== 'object' || v === null) { return false } const proto = Object.getPrototypeOf(v) return proto === Object.prototype || proto === null}