2022-11-24 08:12:25 +09:00
|
|
|
// @ts-expect-error unstorage needs to provide backwards-compatible subpath types
|
|
|
|
import _fs from 'unstorage/drivers/fs'
|
|
|
|
// @ts-expect-error unstorage needs to provide backwards-compatible subpath types
|
|
|
|
import _kv from 'unstorage/drivers/cloudflare-kv-http'
|
2022-11-28 03:22:39 +09:00
|
|
|
import { parseURL } from 'ufo'
|
2022-11-24 08:12:25 +09:00
|
|
|
|
2022-11-15 23:29:46 +09:00
|
|
|
import { $fetch } from 'ohmyfetch'
|
2022-11-24 08:12:25 +09:00
|
|
|
import type { Storage } from 'unstorage'
|
|
|
|
|
|
|
|
import cached from './cache-driver'
|
|
|
|
|
2022-11-16 00:48:23 +09:00
|
|
|
import type { AppInfo } from '~/types'
|
2022-11-24 08:12:25 +09:00
|
|
|
import { APP_NAME } from '~/constants'
|
2022-11-15 23:29:46 +09:00
|
|
|
|
2022-11-28 03:39:40 +09:00
|
|
|
const config = useRuntimeConfig()
|
|
|
|
export const HOST_URL = config.deployUrl
|
2022-11-28 03:22:39 +09:00
|
|
|
export const HOST_DOMAIN = parseURL(HOST_URL).host!
|
2022-11-26 01:57:29 +09:00
|
|
|
|
2022-11-24 08:12:25 +09:00
|
|
|
const fs = _fs as typeof import('unstorage/dist/drivers/fs')['default']
|
|
|
|
const kv = _kv as typeof import('unstorage/dist/drivers/cloudflare-kv-http')['default']
|
2022-11-15 23:29:46 +09:00
|
|
|
|
2022-11-24 08:12:25 +09:00
|
|
|
const storage = useStorage() as Storage
|
|
|
|
|
2022-11-28 03:39:40 +09:00
|
|
|
if (config.env === 'local') {
|
2022-11-24 08:12:25 +09:00
|
|
|
storage.mount('servers', fs({ base: 'node_modules/.cache/servers' }))
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
storage.mount('servers', cached(kv({
|
|
|
|
accountId: config.cloudflare.accountId,
|
|
|
|
namespaceId: config.cloudflare.namespaceId,
|
|
|
|
apiToken: config.cloudflare.apiToken,
|
|
|
|
})))
|
|
|
|
}
|
|
|
|
|
2022-11-28 03:22:39 +09:00
|
|
|
async function fetchAppInfo(server: string) {
|
2022-11-24 08:12:25 +09:00
|
|
|
const redirect_uris = [
|
|
|
|
'urn:ietf:wg:oauth:2.0:oob',
|
2022-11-28 03:22:39 +09:00
|
|
|
`${HOST_URL}/api/${server}/oauth`,
|
2022-11-24 08:12:25 +09:00
|
|
|
].join('\n')
|
|
|
|
|
|
|
|
const app: AppInfo = await $fetch(`https://${server}/api/v1/apps`, {
|
|
|
|
method: 'POST',
|
|
|
|
body: {
|
|
|
|
client_name: APP_NAME,
|
|
|
|
redirect_uris,
|
|
|
|
scopes: 'read write follow push',
|
|
|
|
},
|
2022-11-16 00:48:23 +09:00
|
|
|
})
|
2022-11-24 08:12:25 +09:00
|
|
|
return app
|
|
|
|
}
|
|
|
|
|
2022-11-28 03:33:19 +09:00
|
|
|
export async function getApp(server: string) {
|
|
|
|
const key = `servers:${HOST_DOMAIN.replace(/[^\w\d]/g, '-')}:${server}.json`
|
2022-11-24 08:12:25 +09:00
|
|
|
|
|
|
|
try {
|
2022-11-28 03:22:39 +09:00
|
|
|
if (await storage.hasItem(key))
|
|
|
|
return await storage.getItem(key) as Promise<AppInfo>
|
|
|
|
const appInfo = await fetchAppInfo(server)
|
2022-11-24 08:12:25 +09:00
|
|
|
await storage.setItem(key, appInfo)
|
|
|
|
return appInfo
|
|
|
|
}
|
|
|
|
catch {
|
|
|
|
return null
|
|
|
|
}
|
2022-11-15 23:29:46 +09:00
|
|
|
}
|