refactor: sync masto (#1121)
This commit is contained in:
parent
eb1f769e32
commit
4422a57f49
81 changed files with 397 additions and 367 deletions
|
@ -24,7 +24,7 @@ export function fetchStatus(id: string, force = false): Promise<mastodon.v1.Stat
|
|||
const cached = cache.get(key)
|
||||
if (cached && !force)
|
||||
return cached
|
||||
const promise = useMasto().v1.statuses.fetch(id)
|
||||
const promise = useMastoClient().v1.statuses.fetch(id)
|
||||
.then((status) => {
|
||||
cacheStatus(status)
|
||||
return status
|
||||
|
@ -44,7 +44,7 @@ export function fetchAccountById(id?: string | null): Promise<mastodon.v1.Accoun
|
|||
if (cached)
|
||||
return cached
|
||||
const domain = currentInstance.value?.uri
|
||||
const promise = useMasto().v1.accounts.fetch(id)
|
||||
const promise = useMastoClient().v1.accounts.fetch(id)
|
||||
.then((r) => {
|
||||
if (r.acct && !r.acct.includes('@') && domain)
|
||||
r.acct = `${r.acct}@${domain}`
|
||||
|
@ -64,7 +64,7 @@ export async function fetchAccountByHandle(acct: string): Promise<mastodon.v1.Ac
|
|||
if (cached)
|
||||
return cached
|
||||
const domain = currentInstance.value?.uri
|
||||
const account = useMasto().v1.accounts.lookup({ acct })
|
||||
const account = useMastoClient().v1.accounts.lookup({ acct })
|
||||
.then((r) => {
|
||||
if (r.acct && !r.acct.includes('@') && domain)
|
||||
r.acct = `${r.acct}@${domain}`
|
||||
|
|
|
@ -337,7 +337,7 @@ export const provideGlobalCommands = () => {
|
|||
icon: 'i-ri:user-shared-line',
|
||||
|
||||
onActivate() {
|
||||
masto.loginTo(user)
|
||||
loginTo(masto, user)
|
||||
},
|
||||
})))
|
||||
useCommand({
|
||||
|
|
|
@ -19,8 +19,8 @@ export async function updateCustomEmojis() {
|
|||
if (Date.now() - currentCustomEmojis.value.lastUpdate < TTL)
|
||||
return
|
||||
|
||||
const masto = useMasto()
|
||||
const emojis = await masto.v1.customEmojis.list()
|
||||
const { client } = $(useMasto())
|
||||
const emojis = await client.v1.customEmojis.list()
|
||||
Object.assign(currentCustomEmojis.value, {
|
||||
lastUpdate: Date.now(),
|
||||
emojis,
|
||||
|
|
|
@ -1,11 +1,115 @@
|
|||
import type { ElkMasto } from '~/types'
|
||||
import type { Pausable } from '@vueuse/core'
|
||||
import type { CreateClientParams, WsEvents, mastodon } from 'masto'
|
||||
import { createClient, fetchV1Instance } from 'masto'
|
||||
import type { Ref } from 'vue'
|
||||
import type { ElkInstance } from '../users'
|
||||
import type { Mutable } from '~/types/utils'
|
||||
import type { UserLogin } from '~/types'
|
||||
|
||||
export const createMasto = () => {
|
||||
let client = $shallowRef<mastodon.Client>(undefined as never)
|
||||
let params = $ref<Mutable<CreateClientParams>>()
|
||||
const canStreaming = $computed(() => !!params?.streamingApiUrl)
|
||||
|
||||
const setParams = (newParams: Partial<CreateClientParams>) => {
|
||||
const p = { ...params, ...newParams } as CreateClientParams
|
||||
client = createClient(p)
|
||||
params = p
|
||||
}
|
||||
|
||||
return {
|
||||
client: $$(client),
|
||||
params: readonly($$(params)),
|
||||
canStreaming: $$(canStreaming),
|
||||
setParams,
|
||||
}
|
||||
}
|
||||
export type ElkMasto = ReturnType<typeof createMasto>
|
||||
|
||||
export const useMasto = () => useNuxtApp().$masto as ElkMasto
|
||||
export const useMastoClient = () => useMasto().client.value
|
||||
|
||||
export const isMastoInitialised = computed(() => process.client && useMasto().loggedIn.value)
|
||||
export function mastoLogin(masto: ElkMasto, user: Pick<UserLogin, 'server' | 'token'>) {
|
||||
const { setParams } = $(masto)
|
||||
|
||||
export const onMastoInit = (cb: () => unknown) => {
|
||||
watchOnce(isMastoInitialised, () => {
|
||||
cb()
|
||||
}, { immediate: isMastoInitialised.value })
|
||||
const server = user.server
|
||||
const url = `https://${server}`
|
||||
const instance: ElkInstance = reactive(getInstanceCache(server) || { uri: server })
|
||||
setParams({
|
||||
url,
|
||||
accessToken: user?.token,
|
||||
disableVersionCheck: true,
|
||||
streamingApiUrl: instance?.urls?.streamingApi,
|
||||
})
|
||||
|
||||
fetchV1Instance({ url }).then((newInstance) => {
|
||||
Object.assign(instance, newInstance)
|
||||
setParams({
|
||||
streamingApiUrl: newInstance.urls.streamingApi,
|
||||
})
|
||||
instances.value[server] = newInstance
|
||||
})
|
||||
|
||||
return instance
|
||||
}
|
||||
|
||||
interface UseStreamingOptions<Controls extends boolean> {
|
||||
/**
|
||||
* Expose more controls
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
controls?: Controls
|
||||
/**
|
||||
* Connect on calling
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
immediate?: boolean
|
||||
}
|
||||
|
||||
export function useStreaming(
|
||||
cb: (client: mastodon.Client) => Promise<WsEvents>,
|
||||
options: UseStreamingOptions<true>,
|
||||
): { stream: Ref<Promise<WsEvents> | undefined> } & Pausable
|
||||
export function useStreaming(
|
||||
cb: (client: mastodon.Client) => Promise<WsEvents>,
|
||||
options?: UseStreamingOptions<false>,
|
||||
): Ref<Promise<WsEvents> | undefined>
|
||||
export function useStreaming(
|
||||
cb: (client: mastodon.Client) => Promise<WsEvents>,
|
||||
{ immediate = true, controls }: UseStreamingOptions<boolean> = {},
|
||||
): ({ stream: Ref<Promise<WsEvents> | undefined> } & Pausable) | Ref<Promise<WsEvents> | undefined> {
|
||||
const { canStreaming, client } = useMasto()
|
||||
|
||||
const isActive = ref(immediate)
|
||||
const stream = ref<Promise<WsEvents>>()
|
||||
|
||||
function pause() {
|
||||
isActive.value = false
|
||||
}
|
||||
|
||||
function resume() {
|
||||
isActive.value = true
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
if (stream.value) {
|
||||
stream.value.then(s => s.disconnect()).catch(() => Promise.resolve())
|
||||
stream.value = undefined
|
||||
}
|
||||
}
|
||||
|
||||
watchEffect(() => {
|
||||
cleanup()
|
||||
if (canStreaming.value && isActive.value)
|
||||
stream.value = cb(client.value)
|
||||
})
|
||||
|
||||
tryOnBeforeUnmount(() => isActive.value = false)
|
||||
|
||||
if (controls)
|
||||
return { stream, isActive, pause, resume }
|
||||
else
|
||||
return stream
|
||||
}
|
||||
|
|
|
@ -4,7 +4,8 @@ const notifications = reactive<Record<string, undefined | [Promise<WsEvents>, st
|
|||
|
||||
export const useNotifications = () => {
|
||||
const id = currentUser.value?.account.id
|
||||
const masto = useMasto()
|
||||
|
||||
const { client, canStreaming } = $(useMasto())
|
||||
|
||||
async function clearNotifications() {
|
||||
if (!id || !notifications[id])
|
||||
|
@ -12,24 +13,26 @@ export const useNotifications = () => {
|
|||
const lastReadId = notifications[id]![1][0]
|
||||
notifications[id]![1] = []
|
||||
|
||||
await masto.v1.markers.create({
|
||||
await client.v1.markers.create({
|
||||
notifications: { lastReadId },
|
||||
})
|
||||
}
|
||||
|
||||
async function connect(): Promise<void> {
|
||||
if (!isMastoInitialised.value || !id || notifications[id] || !currentUser.value?.token)
|
||||
if (!isHydrated.value || !id || notifications[id] || !currentUser.value?.token)
|
||||
return
|
||||
|
||||
const stream = masto.v1.stream.streamUser()
|
||||
await until($$(canStreaming)).toBe(true)
|
||||
|
||||
const stream = client.v1.stream.streamUser()
|
||||
notifications[id] = [stream, []]
|
||||
stream.then(s => s.on('notification', (n) => {
|
||||
if (notifications[id])
|
||||
notifications[id]![1].unshift(n.id)
|
||||
}))
|
||||
|
||||
const position = await masto.v1.markers.fetch({ timeline: ['notifications'] })
|
||||
const paginator = masto.v1.notifications.list({ limit: 30 })
|
||||
const position = await client.v1.markers.fetch({ timeline: ['notifications'] })
|
||||
const paginator = client.v1.notifications.list({ limit: 30 })
|
||||
do {
|
||||
const result = await paginator.next()
|
||||
if (!result.done && result.value.length) {
|
||||
|
@ -53,10 +56,10 @@ export const useNotifications = () => {
|
|||
}
|
||||
|
||||
watch(currentUser, disconnect)
|
||||
if (isMastoInitialised.value)
|
||||
|
||||
onHydrated(() => {
|
||||
connect()
|
||||
else
|
||||
watchOnce(isMastoInitialised, connect)
|
||||
})
|
||||
|
||||
return {
|
||||
notifications: computed(() => id ? notifications[id]?.[1].length ?? 0 : 0),
|
||||
|
|
|
@ -12,7 +12,7 @@ export const usePublish = (options: {
|
|||
}) => {
|
||||
const { expanded, isUploading, initialDraft } = $(options)
|
||||
let { draft, isEmpty } = $(options.draftState)
|
||||
const masto = useMasto()
|
||||
const { client } = $(useMasto())
|
||||
|
||||
let isSending = $ref(false)
|
||||
const isExpanded = $ref(false)
|
||||
|
@ -51,9 +51,9 @@ export const usePublish = (options: {
|
|||
|
||||
let status: mastodon.v1.Status
|
||||
if (!draft.editingStatus)
|
||||
status = await masto.v1.statuses.create(payload)
|
||||
status = await client.v1.statuses.create(payload)
|
||||
else
|
||||
status = await masto.v1.statuses.update(draft.editingStatus.id, payload)
|
||||
status = await client.v1.statuses.update(draft.editingStatus.id, payload)
|
||||
if (draft.params.inReplyToId)
|
||||
navigateToStatus({ status })
|
||||
|
||||
|
@ -83,7 +83,7 @@ export type MediaAttachmentUploadError = [filename: string, message: string]
|
|||
|
||||
export const useUploadMediaAttachment = (draftRef: Ref<Draft>) => {
|
||||
const draft = $(draftRef)
|
||||
const masto = useMasto()
|
||||
const { client } = $(useMasto())
|
||||
const { t } = useI18n()
|
||||
|
||||
let isUploading = $ref<boolean>(false)
|
||||
|
@ -96,12 +96,12 @@ export const useUploadMediaAttachment = (draftRef: Ref<Draft>) => {
|
|||
failedAttachments = []
|
||||
// TODO: display some kind of message if too many media are selected
|
||||
// DONE
|
||||
const limit = currentInstance.value!.configuration.statuses.maxMediaAttachments || 4
|
||||
const limit = currentInstance.value!.configuration?.statuses.maxMediaAttachments || 4
|
||||
for (const file of files.slice(0, limit)) {
|
||||
if (draft.attachments.length < limit) {
|
||||
isExceedingAttachmentLimit = false
|
||||
try {
|
||||
const attachment = await masto.v1.mediaAttachments.create({
|
||||
const attachment = await client.v1.mediaAttachments.create({
|
||||
file,
|
||||
})
|
||||
draft.attachments.push(attachment)
|
||||
|
@ -121,7 +121,7 @@ export const useUploadMediaAttachment = (draftRef: Ref<Draft>) => {
|
|||
}
|
||||
|
||||
async function pickAttachments() {
|
||||
const mimeTypes = currentInstance.value!.configuration.mediaAttachments.supportedMimeTypes
|
||||
const mimeTypes = currentInstance.value!.configuration?.mediaAttachments.supportedMimeTypes
|
||||
const files = await fileOpen({
|
||||
description: 'Attachments',
|
||||
multiple: true,
|
||||
|
@ -132,7 +132,7 @@ export const useUploadMediaAttachment = (draftRef: Ref<Draft>) => {
|
|||
|
||||
async function setDescription(att: mastodon.v1.MediaAttachment, description: string) {
|
||||
att.description = description
|
||||
await masto.v1.mediaAttachments.update(att.id, { description: att.description })
|
||||
await client.v1.mediaAttachments.update(att.id, { description: att.description })
|
||||
}
|
||||
|
||||
function removeAttachment(index: number) {
|
||||
|
|
|
@ -27,7 +27,7 @@ export function useRelationship(account: mastodon.v1.Account): Ref<mastodon.v1.R
|
|||
|
||||
async function fetchRelationships() {
|
||||
const requested = Array.from(requestedRelationships.entries()).filter(([, r]) => !r.value)
|
||||
const relationships = await useMasto().v1.accounts.fetchRelationships(requested.map(([id]) => id))
|
||||
const relationships = await useMastoClient().v1.accounts.fetchRelationships(requested.map(([id]) => id))
|
||||
for (let i = 0; i < requested.length; i++)
|
||||
requested[i][1].value = relationships[i]
|
||||
}
|
||||
|
|
|
@ -22,7 +22,7 @@ export type SearchResult = HashTagSearchResult | AccountSearchResult | StatusSea
|
|||
|
||||
export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOptions = {}) {
|
||||
const done = ref(false)
|
||||
const masto = useMasto()
|
||||
const { client } = $(useMasto())
|
||||
const loading = ref(false)
|
||||
const accounts = ref<AccountSearchResult[]>([])
|
||||
const hashtags = ref<HashTagSearchResult[]>([])
|
||||
|
@ -59,11 +59,11 @@ export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOpt
|
|||
}
|
||||
|
||||
watch(() => resolveUnref(query), () => {
|
||||
loading.value = !!(q && isMastoInitialised.value)
|
||||
loading.value = !!(q && isHydrated.value)
|
||||
})
|
||||
|
||||
debouncedWatch(() => resolveUnref(query), async () => {
|
||||
if (!q || !isMastoInitialised.value)
|
||||
if (!q || !isHydrated.value)
|
||||
return
|
||||
|
||||
loading.value = true
|
||||
|
@ -72,7 +72,7 @@ export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOpt
|
|||
* Based on the source it seems like modifying the params when calling next would result in a new search,
|
||||
* but that doesn't seem to be the case. So instead we just create a new paginator with the new params.
|
||||
*/
|
||||
paginator = masto.v2.search({
|
||||
paginator = client.v2.search({
|
||||
q,
|
||||
...resolveUnref(options),
|
||||
resolve: !!currentUser.value,
|
||||
|
@ -87,7 +87,7 @@ export function useSearch(query: MaybeComputedRef<string>, options: UseSearchOpt
|
|||
}, { debounce: 300 })
|
||||
|
||||
const next = async () => {
|
||||
if (!q || !isMastoInitialised.value || !paginator)
|
||||
if (!q || !isHydrated.value || !paginator)
|
||||
return
|
||||
|
||||
loading.value = true
|
||||
|
|
|
@ -9,7 +9,7 @@ export interface StatusActionsProps {
|
|||
|
||||
export function useStatusActions(props: StatusActionsProps) {
|
||||
let status = $ref<mastodon.v1.Status>({ ...props.status })
|
||||
const masto = useMasto()
|
||||
const { client } = $(useMasto())
|
||||
|
||||
watch(
|
||||
() => props.status,
|
||||
|
@ -61,7 +61,7 @@ export function useStatusActions(props: StatusActionsProps) {
|
|||
|
||||
const toggleReblog = () => toggleStatusAction(
|
||||
'reblogged',
|
||||
() => masto.v1.statuses[status.reblogged ? 'unreblog' : 'reblog'](status.id).then((res) => {
|
||||
() => client.v1.statuses[status.reblogged ? 'unreblog' : 'reblog'](status.id).then((res) => {
|
||||
if (status.reblogged)
|
||||
// returns the original status
|
||||
return res.reblog!
|
||||
|
@ -72,23 +72,23 @@ export function useStatusActions(props: StatusActionsProps) {
|
|||
|
||||
const toggleFavourite = () => toggleStatusAction(
|
||||
'favourited',
|
||||
() => masto.v1.statuses[status.favourited ? 'unfavourite' : 'favourite'](status.id),
|
||||
() => client.v1.statuses[status.favourited ? 'unfavourite' : 'favourite'](status.id),
|
||||
'favouritesCount',
|
||||
)
|
||||
|
||||
const toggleBookmark = () => toggleStatusAction(
|
||||
'bookmarked',
|
||||
() => masto.v1.statuses[status.bookmarked ? 'unbookmark' : 'bookmark'](status.id),
|
||||
() => client.v1.statuses[status.bookmarked ? 'unbookmark' : 'bookmark'](status.id),
|
||||
)
|
||||
|
||||
const togglePin = async () => toggleStatusAction(
|
||||
'pinned',
|
||||
() => masto.v1.statuses[status.pinned ? 'unpin' : 'pin'](status.id),
|
||||
() => client.v1.statuses[status.pinned ? 'unpin' : 'pin'](status.id),
|
||||
)
|
||||
|
||||
const toggleMute = async () => toggleStatusAction(
|
||||
'muted',
|
||||
() => masto.v1.statuses[status.muted ? 'unmute' : 'mute'](status.id),
|
||||
() => client.v1.statuses[status.muted ? 'unmute' : 'mute'](status.id),
|
||||
)
|
||||
|
||||
return {
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
import type { Paginator, WsEvents, mastodon } from 'masto'
|
||||
import type { Ref } from 'vue'
|
||||
import type { PaginatorState } from '~/types'
|
||||
|
||||
export function usePaginator<T, P, U = T>(
|
||||
_paginator: Paginator<T[], P>,
|
||||
stream?: Promise<WsEvents>,
|
||||
stream: Ref<Promise<WsEvents> | undefined>,
|
||||
eventType: 'notification' | 'update' = 'update',
|
||||
preprocess: (items: (T | U)[]) => U[] = items => items as unknown as U[],
|
||||
buffer = 10,
|
||||
|
@ -13,7 +14,7 @@ export function usePaginator<T, P, U = T>(
|
|||
// so clone it
|
||||
const paginator = _paginator.clone()
|
||||
|
||||
const state = ref<PaginatorState>(isMastoInitialised.value ? 'idle' : 'loading')
|
||||
const state = ref<PaginatorState>(isHydrated.value ? 'idle' : 'loading')
|
||||
const items = ref<U[]>([])
|
||||
const nextItems = ref<U[]>([])
|
||||
const prevItems = ref<T[]>([])
|
||||
|
@ -29,37 +30,39 @@ export function usePaginator<T, P, U = T>(
|
|||
prevItems.value = []
|
||||
}
|
||||
|
||||
stream?.then((s) => {
|
||||
s.on(eventType, (status) => {
|
||||
if ('uri' in status)
|
||||
watch(stream, (stream) => {
|
||||
stream?.then((s) => {
|
||||
s.on(eventType, (status) => {
|
||||
if ('uri' in status)
|
||||
cacheStatus(status, undefined, true)
|
||||
|
||||
const index = prevItems.value.findIndex((i: any) => i.id === status.id)
|
||||
if (index >= 0)
|
||||
prevItems.value.splice(index, 1)
|
||||
|
||||
prevItems.value.unshift(status as any)
|
||||
})
|
||||
|
||||
// TODO: update statuses
|
||||
s.on('status.update', (status) => {
|
||||
cacheStatus(status, undefined, true)
|
||||
|
||||
const index = prevItems.value.findIndex((i: any) => i.id === status.id)
|
||||
if (index >= 0)
|
||||
prevItems.value.splice(index, 1)
|
||||
const data = items.value as mastodon.v1.Status[]
|
||||
const index = data.findIndex(s => s.id === status.id)
|
||||
if (index >= 0)
|
||||
data[index] = status
|
||||
})
|
||||
|
||||
prevItems.value.unshift(status as any)
|
||||
s.on('delete', (id) => {
|
||||
removeCachedStatus(id)
|
||||
|
||||
const data = items.value as mastodon.v1.Status[]
|
||||
const index = data.findIndex(s => s.id === id)
|
||||
if (index >= 0)
|
||||
data.splice(index, 1)
|
||||
})
|
||||
})
|
||||
|
||||
// TODO: update statuses
|
||||
s.on('status.update', (status) => {
|
||||
cacheStatus(status, undefined, true)
|
||||
|
||||
const data = items.value as mastodon.v1.Status[]
|
||||
const index = data.findIndex(s => s.id === status.id)
|
||||
if (index >= 0)
|
||||
data[index] = status
|
||||
})
|
||||
|
||||
s.on('delete', (id) => {
|
||||
removeCachedStatus(id)
|
||||
|
||||
const data = items.value as mastodon.v1.Status[]
|
||||
const index = data.findIndex(s => s.id === id)
|
||||
if (index >= 0)
|
||||
data.splice(index, 1)
|
||||
})
|
||||
})
|
||||
}, { immediate: true })
|
||||
|
||||
async function loadNext() {
|
||||
if (state.value !== 'idle')
|
||||
|
@ -101,8 +104,8 @@ export function usePaginator<T, P, U = T>(
|
|||
bound.update()
|
||||
}, 1000)
|
||||
|
||||
if (!isMastoInitialised.value) {
|
||||
onMastoInit(() => {
|
||||
if (!isHydrated.value) {
|
||||
onHydrated(() => {
|
||||
state.value = 'idle'
|
||||
loadNext()
|
||||
})
|
||||
|
|
|
@ -132,5 +132,5 @@ async function sendSubscriptionToBackend(
|
|||
data,
|
||||
}
|
||||
|
||||
return await useMasto().v1.webPushSubscriptions.create(params)
|
||||
return await useMastoClient().v1.webPushSubscriptions.create(params)
|
||||
}
|
||||
|
|
|
@ -13,7 +13,7 @@ const supportsPushNotifications = typeof window !== 'undefined'
|
|||
&& 'getKey' in PushSubscription.prototype
|
||||
|
||||
export const usePushManager = () => {
|
||||
const masto = useMasto()
|
||||
const { client } = $(useMasto())
|
||||
const isSubscribed = ref(false)
|
||||
const notificationPermission = ref<PermissionState | undefined>(
|
||||
Notification.permission === 'denied'
|
||||
|
@ -168,7 +168,7 @@ export const usePushManager = () => {
|
|||
if (policyChanged)
|
||||
await subscribe(data, policy, true)
|
||||
else
|
||||
currentUser.value.pushSubscription = await masto.v1.webPushSubscriptions.update({ data })
|
||||
currentUser.value.pushSubscription = await client.v1.webPushSubscriptions.update({ data })
|
||||
|
||||
policyChanged && await nextTick()
|
||||
|
||||
|
|
|
@ -14,7 +14,7 @@ export const MentionSuggestion: Partial<SuggestionOptions> = {
|
|||
if (query.length === 0)
|
||||
return []
|
||||
|
||||
const results = await useMasto().v2.search({ q: query, type: 'accounts', limit: 25, resolve: true })
|
||||
const results = await useMastoClient().v2.search({ q: query, type: 'accounts', limit: 25, resolve: true })
|
||||
return results.accounts
|
||||
},
|
||||
render: createSuggestionRenderer(TiptapMentionList),
|
||||
|
@ -27,7 +27,7 @@ export const HashtagSuggestion: Partial<SuggestionOptions> = {
|
|||
if (query.length === 0)
|
||||
return []
|
||||
|
||||
const results = await useMasto().v2.search({
|
||||
const results = await useMastoClient().v2.search({
|
||||
q: query,
|
||||
type: 'hashtags',
|
||||
limit: 25,
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -6,6 +6,10 @@ import { useHead } from '#head'
|
|||
|
||||
export const isHydrated = ref(false)
|
||||
|
||||
export const onHydrated = (cb: () => unknown) => {
|
||||
watchOnce(isHydrated, () => cb(), { immediate: isHydrated.value })
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Whether the current component is running in the background
|
||||
*
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue