2022-11-27 18:13:04 +03:00
|
|
|
import type { MastoClient } from 'masto'
|
2022-12-17 19:55:29 +03:00
|
|
|
import type { ElkMasto } from '~/types'
|
2022-11-26 18:42:58 +03:00
|
|
|
|
2022-12-17 19:55:29 +03:00
|
|
|
export default defineNuxtPlugin(async (nuxtApp) => {
|
|
|
|
const api = shallowRef<MastoClient | null>(null)
|
|
|
|
const apiPromise = ref<Promise<MastoClient> | null>(null)
|
|
|
|
const initialised = computed(() => !!api.value)
|
|
|
|
|
|
|
|
const masto = new Proxy({} as ElkMasto, {
|
|
|
|
get(_, key: keyof ElkMasto) {
|
|
|
|
if (key === 'loggedIn')
|
|
|
|
return initialised
|
|
|
|
|
|
|
|
if (key === 'loginTo') {
|
2022-12-20 03:16:15 +03:00
|
|
|
return (...args: any[]): Promise<MastoClient> => {
|
|
|
|
return apiPromise.value = loginTo(...args).then((r) => {
|
2022-12-17 19:55:29 +03:00
|
|
|
api.value = r
|
|
|
|
return masto
|
|
|
|
}).catch(() => {
|
|
|
|
// Show error page when Mastodon server is down
|
|
|
|
throw createError({
|
|
|
|
fatal: true,
|
|
|
|
statusMessage: 'Could not log into account.',
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (api.value && key in api.value)
|
|
|
|
return api.value[key as keyof MastoClient]
|
|
|
|
|
2022-12-20 03:16:15 +03:00
|
|
|
if (!api.value) {
|
2022-12-17 19:55:29 +03:00
|
|
|
return new Proxy({}, {
|
|
|
|
get(_, subkey) {
|
|
|
|
return (...args: any[]) => apiPromise.value?.then((r: any) => r[key][subkey](...args))
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
2022-12-20 03:16:15 +03:00
|
|
|
|
|
|
|
return undefined
|
2022-12-17 19:55:29 +03:00
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
if (process.client) {
|
2022-11-27 18:13:04 +03:00
|
|
|
const { query } = useRoute()
|
|
|
|
const user = typeof query.server === 'string' && typeof query.token === 'string'
|
2022-12-18 02:29:16 +03:00
|
|
|
? {
|
|
|
|
server: query.server,
|
|
|
|
token: query.token,
|
|
|
|
vapidKey: typeof query.vapid_key === 'string' ? query.vapid_key : undefined,
|
|
|
|
}
|
2022-11-27 18:13:04 +03:00
|
|
|
: currentUser.value
|
2022-11-26 22:33:36 +03:00
|
|
|
|
2022-12-17 19:55:29 +03:00
|
|
|
nuxtApp.hook('app:suspense:resolve', () => {
|
|
|
|
// TODO: improve upstream to make this synchronous (delayed auth)
|
2022-12-20 11:20:40 +03:00
|
|
|
if (!masto.loggedIn.value)
|
|
|
|
masto.loginTo(user)
|
2022-11-26 18:42:58 +03:00
|
|
|
})
|
|
|
|
}
|
2022-11-28 12:01:14 +03:00
|
|
|
|
|
|
|
return {
|
|
|
|
provide: {
|
2022-12-17 19:55:29 +03:00
|
|
|
masto,
|
2022-11-28 12:01:14 +03:00
|
|
|
},
|
|
|
|
}
|
2022-11-26 18:42:58 +03:00
|
|
|
})
|