refactor: sync masto (#1121)
This commit is contained in:
parent
eb1f769e32
commit
4422a57f49
81 changed files with 397 additions and 367 deletions
|
@ -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 {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue