about summary refs log tree commit diff
path: root/src/lib/api/index.ts
blob: 1b12f29c5b5d752e81100cc9fc3cb98b5201f280 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import {
  AppBskyEmbedImages,
  AppBskyEmbedExternal,
  AppBskyEmbedRecord,
  AppBskyEmbedRecordWithMedia,
  AppBskyRichtextFacet,
  ComAtprotoRepoUploadBlob,
  RichText,
} from '@atproto/api'
import {AtUri} from '@atproto/api'
import {RootStoreModel} from 'state/models/root-store'
import {isNetworkError} from 'lib/strings/errors'
import {Image} from 'lib/media/types'
import {LinkMeta} from '../link-meta/link-meta'
import {isWeb} from 'platform/detection'

export interface ExternalEmbedDraft {
  uri: string
  isLoading: boolean
  meta?: LinkMeta
  localThumb?: Image
}

export async function resolveName(store: RootStoreModel, didOrHandle: string) {
  if (!didOrHandle) {
    throw new Error('Invalid handle: ""')
  }
  if (didOrHandle.startsWith('did:')) {
    return didOrHandle
  }
  const res = await store.agent.resolveHandle({
    handle: didOrHandle,
  })
  return res.data.did
}

export async function uploadBlob(
  store: RootStoreModel,
  blob: string,
  encoding: string,
): Promise<ComAtprotoRepoUploadBlob.Response> {
  if (isWeb) {
    // `blob` should be a data uri
    return store.agent.uploadBlob(convertDataURIToUint8Array(blob), {
      encoding,
    })
  } else {
    // `blob` should be a path to a file in the local FS
    return store.agent.uploadBlob(
      blob, // this will be special-cased by the fetch monkeypatch in /src/state/lib/api.ts
      {encoding},
    )
  }
}

interface PostOpts {
  rawText: string
  replyTo?: string
  quote?: {
    uri: string
    cid: string
  }
  extLink?: ExternalEmbedDraft
  images?: string[]
  knownHandles?: Set<string>
  onStateChange?: (state: string) => void
}

export async function post(store: RootStoreModel, opts: PostOpts) {
  let embed:
    | AppBskyEmbedImages.Main
    | AppBskyEmbedExternal.Main
    | AppBskyEmbedRecord.Main
    | AppBskyEmbedRecordWithMedia.Main
    | undefined
  let reply
  const rt = new RichText(
    {text: opts.rawText.trim()},
    {
      cleanNewlines: true,
    },
  )

  opts.onStateChange?.('Processing...')
  await rt.detectFacets(store.agent)

  // filter out any mention facets that didn't map to a user
  rt.facets = rt.facets?.filter(facet => {
    const mention = facet.features.find(feature =>
      AppBskyRichtextFacet.isMention(feature),
    )
    if (mention && !mention.did) {
      return false
    }
    return true
  })

  if (opts.quote) {
    embed = {
      $type: 'app.bsky.embed.record',
      record: {
        uri: opts.quote.uri,
        cid: opts.quote.cid,
      },
    } as AppBskyEmbedRecord.Main
  }

  if (opts.images?.length) {
    const images: AppBskyEmbedImages.Image[] = []
    for (const image of opts.images) {
      opts.onStateChange?.(`Uploading image #${images.length + 1}...`)
      const res = await uploadBlob(store, image, 'image/jpeg')
      images.push({
        image: res.data.blob,
        alt: '', // TODO supply alt text
      })
    }

    if (opts.quote) {
      embed = {
        $type: 'app.bsky.embed.recordWithMedia',
        record: embed,
        media: {
          $type: 'app.bsky.embed.images',
          images,
        },
      } as AppBskyEmbedRecordWithMedia.Main
    } else {
      embed = {
        $type: 'app.bsky.embed.images',
        images,
      } as AppBskyEmbedImages.Main
    }
  }

  if (opts.extLink && !opts.images?.length) {
    let thumb
    if (opts.extLink.localThumb) {
      opts.onStateChange?.('Uploading link thumbnail...')
      let encoding
      if (opts.extLink.localThumb.mime) {
        encoding = opts.extLink.localThumb.mime
      } else if (opts.extLink.localThumb.path.endsWith('.png')) {
        encoding = 'image/png'
      } else if (
        opts.extLink.localThumb.path.endsWith('.jpeg') ||
        opts.extLink.localThumb.path.endsWith('.jpg')
      ) {
        encoding = 'image/jpeg'
      } else {
        store.log.warn(
          'Unexpected image format for thumbnail, skipping',
          opts.extLink.localThumb.path,
        )
      }
      if (encoding) {
        const thumbUploadRes = await uploadBlob(
          store,
          opts.extLink.localThumb.path,
          encoding,
        )
        thumb = thumbUploadRes.data.blob
      }
    }

    if (opts.quote) {
      embed = {
        $type: 'app.bsky.embed.recordWithMedia',
        record: embed,
        media: {
          $type: 'app.bsky.embed.external',
          external: {
            uri: opts.extLink.uri,
            title: opts.extLink.meta?.title || '',
            description: opts.extLink.meta?.description || '',
            thumb,
          },
        } as AppBskyEmbedExternal.Main,
      } as AppBskyEmbedRecordWithMedia.Main
    } else {
      embed = {
        $type: 'app.bsky.embed.external',
        external: {
          uri: opts.extLink.uri,
          title: opts.extLink.meta?.title || '',
          description: opts.extLink.meta?.description || '',
          thumb,
        },
      } as AppBskyEmbedExternal.Main
    }
  }

  if (opts.replyTo) {
    const replyToUrip = new AtUri(opts.replyTo)
    const parentPost = await store.agent.getPost({
      repo: replyToUrip.host,
      rkey: replyToUrip.rkey,
    })
    if (parentPost) {
      const parentRef = {
        uri: parentPost.uri,
        cid: parentPost.cid,
      }
      reply = {
        root: parentPost.value.reply?.root || parentRef,
        parent: parentRef,
      }
    }
  }

  try {
    opts.onStateChange?.('Posting...')
    return await store.agent.post({
      text: rt.text,
      facets: rt.facets,
      reply,
      embed,
    })
  } catch (e: any) {
    console.error(`Failed to create post: ${e.toString()}`)
    if (isNetworkError(e)) {
      throw new Error(
        'Post failed to upload. Please check your Internet connection and try again.',
      )
    } else {
      throw e
    }
  }
}

// helpers
// =

function convertDataURIToUint8Array(uri: string): Uint8Array {
  var raw = window.atob(uri.substring(uri.indexOf(';base64,') + 8))
  var binary = new Uint8Array(new ArrayBuffer(raw.length))
  for (let i = 0; i < raw.length; i++) {
    binary[i] = raw.charCodeAt(i)
  }
  return binary
}