refactor: sync masto (#1121)
This commit is contained in:
parent
eb1f769e32
commit
4422a57f49
81 changed files with 397 additions and 367 deletions
|
@ -1,8 +1,9 @@
|
|||
import { createClient, fetchV1Instance } from 'masto'
|
||||
import type { mastodon } from 'masto'
|
||||
import type { EffectScope, Ref } from 'vue'
|
||||
import type { MaybeComputedRef, RemovableRef } from '@vueuse/core'
|
||||
import type { ElkMasto, UserLogin } from '~/types'
|
||||
import type { ElkMasto } from './masto/masto'
|
||||
import type { UserLogin } from '~/types'
|
||||
import type { Overwrite } from '~/types/utils'
|
||||
import {
|
||||
DEFAULT_POST_CHARS_LIMIT,
|
||||
STORAGE_KEY_CURRENT_USER,
|
||||
|
@ -41,9 +42,12 @@ const initializeUsers = async (): Promise<Ref<UserLogin[]> | RemovableRef<UserLo
|
|||
}
|
||||
|
||||
const users = await initializeUsers()
|
||||
const instances = useLocalStorage<Record<string, mastodon.v1.Instance>>(STORAGE_KEY_SERVERS, mock ? mock.server : {}, { deep: true })
|
||||
export const instances = useLocalStorage<Record<string, mastodon.v1.Instance>>(STORAGE_KEY_SERVERS, mock ? mock.server : {}, { deep: true })
|
||||
const currentUserId = useLocalStorage<string>(STORAGE_KEY_CURRENT_USER, mock ? mock.user.account.id : '')
|
||||
|
||||
export type ElkInstance = Partial<mastodon.v1.Instance> & { uri: string }
|
||||
export const getInstanceCache = (server: string): mastodon.v1.Instance | undefined => instances.value[server]
|
||||
|
||||
export const currentUser = computed<UserLogin | undefined>(() => {
|
||||
if (currentUserId.value) {
|
||||
const user = users.value.find(user => user.account?.id === currentUserId.value)
|
||||
|
@ -54,9 +58,9 @@ export const currentUser = computed<UserLogin | undefined>(() => {
|
|||
return users.value[0]
|
||||
})
|
||||
|
||||
const publicInstance = ref<mastodon.v1.Instance | null>(null)
|
||||
export const currentInstance = computed<null | mastodon.v1.Instance>(() => currentUser.value ? instances.value[currentUser.value.server] ?? null : publicInstance.value)
|
||||
export const isGlitchEdition = computed(() => currentInstance.value?.version.includes('+glitch'))
|
||||
const publicInstance = ref<ElkInstance | null>(null)
|
||||
export const currentInstance = computed<null | ElkInstance>(() => currentUser.value ? instances.value[currentUser.value.server] ?? null : publicInstance.value)
|
||||
export const isGlitchEdition = computed(() => currentInstance.value?.version?.includes('+glitch'))
|
||||
|
||||
export const publicServer = ref('')
|
||||
export const currentServer = computed<string>(() => currentUser.value?.server || publicServer.value)
|
||||
|
@ -102,91 +106,63 @@ export const useUsers = () => users
|
|||
export const useSelfAccount = (user: MaybeComputedRef<mastodon.v1.Account | undefined>) =>
|
||||
computed(() => currentUser.value && resolveUnref(user)?.id === currentUser.value.account.id)
|
||||
|
||||
export const characterLimit = computed(() => currentInstance.value?.configuration.statuses.maxCharacters ?? DEFAULT_POST_CHARS_LIMIT)
|
||||
export const characterLimit = computed(() => currentInstance.value?.configuration?.statuses.maxCharacters ?? DEFAULT_POST_CHARS_LIMIT)
|
||||
|
||||
async function loginTo(user?: Omit<UserLogin, 'account'> & { account?: mastodon.v1.AccountCredentials }) {
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const server = user?.server || route.params.server as string || publicServer.value
|
||||
const url = `https://${server}`
|
||||
const instance = await fetchV1Instance({
|
||||
url,
|
||||
})
|
||||
const masto = createClient({
|
||||
url,
|
||||
streamingApiUrl: instance.urls.streamingApi,
|
||||
accessToken: user?.token,
|
||||
disableVersionCheck: true,
|
||||
})
|
||||
export async function loginTo(masto: ElkMasto, user: Overwrite<UserLogin, { account?: mastodon.v1.AccountCredentials }>) {
|
||||
const { client } = $(masto)
|
||||
const instance = mastoLogin(masto, user)
|
||||
|
||||
if (!user?.token) {
|
||||
publicServer.value = server
|
||||
publicServer.value = user.server
|
||||
publicInstance.value = instance
|
||||
return
|
||||
}
|
||||
|
||||
function getUser() {
|
||||
return users.value.find(u => u.server === user.server && u.token === user.token)
|
||||
}
|
||||
|
||||
const account = getUser()?.account
|
||||
if (account)
|
||||
currentUserId.value = account.id
|
||||
|
||||
const [me, pushSubscription] = await Promise.all([
|
||||
fetchAccountInfo(client, user.server),
|
||||
// if PWA is not enabled, don't get push subscription
|
||||
useRuntimeConfig().public.pwaEnabled
|
||||
// we get 404 response instead empty data
|
||||
? client.v1.webPushSubscriptions.fetch().catch(() => Promise.resolve(undefined))
|
||||
: Promise.resolve(undefined),
|
||||
])
|
||||
|
||||
const existingUser = getUser()
|
||||
if (existingUser) {
|
||||
existingUser.account = me
|
||||
existingUser.pushSubscription = pushSubscription
|
||||
}
|
||||
else {
|
||||
try {
|
||||
const [me, pushSubscription] = await Promise.all([
|
||||
masto.v1.accounts.verifyCredentials(),
|
||||
// if PWA is not enabled, don't get push subscription
|
||||
useRuntimeConfig().public.pwaEnabled
|
||||
// we get 404 response instead empty data
|
||||
? masto.v1.webPushSubscriptions.fetch().catch(() => Promise.resolve(undefined))
|
||||
: Promise.resolve(undefined),
|
||||
])
|
||||
|
||||
if (!me.acct.includes('@'))
|
||||
me.acct = `${me.acct}@${instance.uri}`
|
||||
|
||||
user.account = me
|
||||
user.pushSubscription = pushSubscription
|
||||
currentUserId.value = me.id
|
||||
instances.value[server] = instance
|
||||
|
||||
if (!users.value.some(u => u.server === user.server && u.token === user.token))
|
||||
users.value.push(user as UserLogin)
|
||||
}
|
||||
catch (err) {
|
||||
console.error(err)
|
||||
await signout()
|
||||
}
|
||||
}
|
||||
|
||||
// This only cleans up the URL; page content should stay the same
|
||||
if (route.path === '/signin/callback') {
|
||||
await router.push('/home')
|
||||
}
|
||||
|
||||
else if ('server' in route.params && user?.token && !useNuxtApp()._processingMiddleware) {
|
||||
await router.push({
|
||||
...route,
|
||||
force: true,
|
||||
users.value.push({
|
||||
...user,
|
||||
account: me,
|
||||
pushSubscription,
|
||||
})
|
||||
}
|
||||
|
||||
return masto
|
||||
currentUserId.value = me.id
|
||||
}
|
||||
|
||||
export function setAccountInfo(userId: string, account: mastodon.v1.AccountCredentials) {
|
||||
const index = getUsersIndexByUserId(userId)
|
||||
if (index === -1)
|
||||
return false
|
||||
|
||||
users.value[index].account = account
|
||||
return true
|
||||
}
|
||||
|
||||
export async function pullMyAccountInfo() {
|
||||
const account = await useMasto().v1.accounts.verifyCredentials()
|
||||
export async function fetchAccountInfo(client: mastodon.Client, server: string) {
|
||||
const account = await client.v1.accounts.verifyCredentials()
|
||||
if (!account.acct.includes('@'))
|
||||
account.acct = `${account.acct}@${currentInstance.value!.uri}`
|
||||
|
||||
setAccountInfo(currentUserId.value, account)
|
||||
cacheAccount(account, currentServer.value, true)
|
||||
account.acct = `${account.acct}@${server}`
|
||||
cacheAccount(account, server, true)
|
||||
return account
|
||||
}
|
||||
|
||||
export function getUsersIndexByUserId(userId: string) {
|
||||
return users.value.findIndex(u => u.account?.id === userId)
|
||||
export async function refreshAccountInfo() {
|
||||
const account = await fetchAccountInfo(useMastoClient(), currentServer.value)
|
||||
currentUser.value!.account = account
|
||||
return account
|
||||
}
|
||||
|
||||
export async function removePushNotificationData(user: UserLogin, fromSWPushManager = true) {
|
||||
|
@ -223,7 +199,23 @@ export async function removePushNotifications(user: UserLogin) {
|
|||
return
|
||||
|
||||
// unsubscribe push notifications
|
||||
await useMasto().v1.webPushSubscriptions.remove().catch(() => Promise.resolve())
|
||||
await useMastoClient().v1.webPushSubscriptions.remove().catch(() => Promise.resolve())
|
||||
}
|
||||
|
||||
export async function switchUser(user: UserLogin) {
|
||||
const masto = useMasto()
|
||||
|
||||
await loginTo(masto, user)
|
||||
|
||||
// This only cleans up the URL; page content should stay the same
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
if ('server' in route.params && user?.token && !useNuxtApp()._processingMiddleware) {
|
||||
await router.push({
|
||||
...route,
|
||||
force: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function signout() {
|
||||
|
@ -258,7 +250,7 @@ export async function signout() {
|
|||
if (!currentUserId.value)
|
||||
await useRouter().push('/')
|
||||
|
||||
await masto.loginTo(currentUser.value)
|
||||
loginTo(masto, currentUser.value)
|
||||
}
|
||||
|
||||
export function checkLogin() {
|
||||
|
@ -320,57 +312,3 @@ export function clearUserLocalStorage(account?: mastodon.v1.Account) {
|
|||
delete value.value[id]
|
||||
})
|
||||
}
|
||||
|
||||
export const createMasto = () => {
|
||||
const api = shallowRef<mastodon.Client | null>(null)
|
||||
const apiPromise = ref<Promise<mastodon.Client> | 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') {
|
||||
return (...args: any[]): Promise<mastodon.Client> => {
|
||||
return apiPromise.value = loginTo(...args).then((r) => {
|
||||
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 mastodon.Client]
|
||||
|
||||
if (!api.value) {
|
||||
return new Proxy({}, {
|
||||
get(_, subkey) {
|
||||
if (typeof subkey === 'string' && subkey.startsWith('iterate')) {
|
||||
return (...args: any[]) => {
|
||||
let paginator: any
|
||||
function next() {
|
||||
paginator = paginator || (api.value as any)?.[key][subkey](...args)
|
||||
return paginator.next()
|
||||
}
|
||||
return { next }
|
||||
}
|
||||
}
|
||||
|
||||
return (...args: any[]) => apiPromise.value?.then((r: any) => r[key][subkey](...args))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
|
||||
return masto
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue