about summary refs log tree commit diff
path: root/src/lib/media/video/upload.shared.ts
blob: f74efa03a6778c6a9ada61e9f7c57ba8b8392a89 (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
import {type BskyAgent} from '@atproto/api'
import {type I18n} from '@lingui/core'
import {msg} from '@lingui/macro'

import {VIDEO_SERVICE_DID} from '#/lib/constants'
import {UploadLimitError} from '#/lib/media/video/errors'
import {getServiceAuthAudFromUrl} from '#/lib/strings/url-helpers'
import {createVideoAgent} from './util'

export async function getServiceAuthToken({
  agent,
  aud,
  lxm,
  exp,
}: {
  agent: BskyAgent
  aud?: string
  lxm: string
  exp?: number
}) {
  const pdsAud = getServiceAuthAudFromUrl(agent.dispatchUrl)
  if (!pdsAud) {
    throw new Error('Agent does not have a PDS URL')
  }
  const {data: serviceAuth} = await agent.com.atproto.server.getServiceAuth({
    aud: aud ?? pdsAud,
    lxm,
    exp,
  })
  return serviceAuth.token
}

export async function getVideoUploadLimits(agent: BskyAgent, _: I18n['_']) {
  const token = await getServiceAuthToken({
    agent,
    lxm: 'app.bsky.video.getUploadLimits',
    aud: VIDEO_SERVICE_DID,
  })
  const videoAgent = createVideoAgent()
  const {data: limits} = await videoAgent.app.bsky.video
    .getUploadLimits({}, {headers: {Authorization: `Bearer ${token}`}})
    .catch(err => {
      if (err instanceof Error) {
        throw new UploadLimitError(err.message)
      } else {
        throw err
      }
    })

  if (!limits.canUpload) {
    if (limits.message) {
      throw new UploadLimitError(limits.message)
    } else {
      throw new UploadLimitError(
        _(
          msg`You have temporarily reached the limit for video uploads. Please try again later.`,
        ),
      )
    }
  }
}