elk/plugins/store.client.ts

89 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-11-15 15:48:23 +00:00
import { login as loginMasto } from 'masto'
2022-11-21 06:55:31 +00:00
import type { ServerInfo, UserLogin } from '~/types'
const ServerInfoTTL = 60 * 60 * 1000 * 12 // 12 hour
2022-11-15 15:48:23 +00:00
2022-11-17 21:32:03 +00:00
function createClientState() {
2022-11-15 15:48:23 +00:00
const { server, token } = useAppCookies()
2022-11-17 21:32:03 +00:00
2022-11-15 15:48:23 +00:00
const accounts = useLocalStorage<UserLogin[]>('nuxtodon-accounts', [], { deep: true })
2022-11-16 21:27:02 +00:00
const currentId = useLocalStorage<string>('nuxtodon-current-user', '')
2022-11-17 21:32:03 +00:00
2022-11-16 21:27:02 +00:00
const currentUser = computed<UserLogin | undefined>(() => {
let user: UserLogin | undefined
if (currentId.value) {
user = accounts.value.find(user => user.account?.id === currentId.value)
if (user)
return user
}
// Fallback to the first account
return accounts.value[0]
})
2022-11-15 15:48:23 +00:00
async function login(user: UserLogin) {
const existing = accounts.value.findIndex(u => u.server === user.server && u.token === user.token)
if (existing !== -1) {
2022-11-16 21:27:02 +00:00
if (currentId.value === accounts.value[existing].account?.id)
2022-11-15 15:48:23 +00:00
return null
2022-11-16 21:27:02 +00:00
currentId.value = user.account?.id
2022-11-15 15:48:23 +00:00
server.value = user.server
token.value = user.token
return true
}
const masto = await loginMasto({
url: `https://${user.server}`,
accessToken: user.token,
})
const me = await masto.accounts.verifyCredentials()
user.account = me
accounts.value.push(user)
2022-11-16 21:27:02 +00:00
currentId.value = me.id
2022-11-15 15:48:23 +00:00
server.value = user.server
token.value = user.token
return true
}
2022-11-21 06:55:31 +00:00
const serverInfos = useLocalStorage<Record<string, ServerInfo>>('nuxtodon-server-info', {})
async function fetchServerInfo(server: string) {
if (!serverInfos.value[server]) {
// @ts-expect-error init
serverInfos.value[server] = {
timeUpdated: 0,
server,
}
}
if (serverInfos.value[server].timeUpdated + ServerInfoTTL < Date.now()) {
const masto = await useMasto()
await Promise.allSettled([
masto.instances.fetch().then((r) => {
Object.assign(serverInfos.value[server], r)
}),
masto.customEmojis.fetchAll().then((r) => {
serverInfos.value[server].customEmojis = Object.fromEntries(r.map(i => [i.shortcode, i]))
}),
])
}
return serverInfos.value[server]
}
if (server.value)
fetchServerInfo(server.value)
2022-11-15 15:48:23 +00:00
return {
currentUser,
accounts,
login,
2022-11-21 06:55:31 +00:00
serverInfos,
fetchServerInfo,
2022-11-15 15:48:23 +00:00
}
}
2022-11-17 21:32:03 +00:00
export type ClientState = ReturnType<typeof createClientState>
2022-11-15 15:48:23 +00:00
export default defineNuxtPlugin((nuxt) => {
2022-11-17 21:32:03 +00:00
nuxt.$clientState = createClientState()
2022-11-15 15:48:23 +00:00
})