Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026import { 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 {communityXrpc} from '#/lib/api/community'import { admitFeedPost, fetchCommunityFeedTarget, isSpaceBackedFeed,} from '#/lib/api/community-feed'import {fetchCommunityPostView} from '#/lib/api/community-post'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'
/** * 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)}
export interface PostOpts { thread: ThreadDraft draftId?: string replyTo?: string onStateChange?: (state: string) => void langs?: string[]}
export async function post( agent: AtpAgent, queryClient: QueryClient, opts: PostOpts,) { 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.`, ) } 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)) { 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 ) { 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') }
let replyPromise: | Promise<AppBskyFeedPost.Record['reply']> | AppBskyFeedPost.Record['reply'] | undefined if (opts.replyTo) { // Not awaited to avoid waterfalls. replyPromise = resolveReply(agent, opts.replyTo) }
// 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}}
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.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 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}