Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166import { 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 * as dcbor from '@ipld/dag-cbor'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`Polls 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 poll 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 poll.`) } 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 poll...`) 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> { // 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}