refactor: migrate to nuxt compatibilityVersion: 4 (#3298)
This commit is contained in:
parent
46e4433e1c
commit
a3fbc056a9
342 changed files with 1200 additions and 2932 deletions
57
app/composables/masto/account.ts
Normal file
57
app/composables/masto/account.ts
Normal file
|
@ -0,0 +1,57 @@
|
|||
import type { mastodon } from 'masto'
|
||||
|
||||
export function getDisplayName(account: mastodon.v1.Account, options?: { rich?: boolean }) {
|
||||
const displayName = account.displayName || account.username || account.acct || ''
|
||||
if (options?.rich)
|
||||
return displayName
|
||||
return displayName.replace(/:([\w-]+):/g, '')
|
||||
}
|
||||
|
||||
export function accountToShortHandle(acct: string) {
|
||||
return `@${acct.includes('@') ? acct.split('@')[0] : acct}`
|
||||
}
|
||||
|
||||
export function getShortHandle({ acct }: mastodon.v1.Account) {
|
||||
if (!acct)
|
||||
return ''
|
||||
return accountToShortHandle(acct)
|
||||
}
|
||||
|
||||
export function getServerName(account: mastodon.v1.Account) {
|
||||
if (account.acct?.includes('@'))
|
||||
return account.acct.split('@')[1]
|
||||
// We should only lack the server name if we're on the same server as the account
|
||||
return currentInstance.value ? getInstanceDomain(currentInstance.value) : ''
|
||||
}
|
||||
|
||||
export function getFullHandle(account: mastodon.v1.Account) {
|
||||
const handle = `@${account.acct}`
|
||||
if (!currentUser.value || account.acct.includes('@'))
|
||||
return handle
|
||||
return `${handle}@${getServerName(account)}`
|
||||
}
|
||||
|
||||
export function toShortHandle(fullHandle: string) {
|
||||
if (!currentUser.value)
|
||||
return fullHandle
|
||||
const server = currentUser.value.server
|
||||
if (fullHandle.endsWith(`@${server}`))
|
||||
return fullHandle.slice(0, -server.length - 1)
|
||||
return fullHandle
|
||||
}
|
||||
|
||||
export function extractAccountHandle(account: mastodon.v1.Account) {
|
||||
let handle = getFullHandle(account).slice(1)
|
||||
const uri = currentInstance.value ? getInstanceDomain(currentInstance.value) : currentServer.value
|
||||
if (currentInstance.value && handle.endsWith(`@${uri}`))
|
||||
handle = handle.slice(0, -uri.length - 1)
|
||||
|
||||
return handle
|
||||
}
|
||||
|
||||
export function useAccountHandle(account: mastodon.v1.Account, fullServer = true) {
|
||||
return computed(() => fullServer
|
||||
? getFullHandle(account)
|
||||
: getShortHandle(account),
|
||||
)
|
||||
}
|
85
app/composables/masto/icons.ts
Normal file
85
app/composables/masto/icons.ts
Normal file
|
@ -0,0 +1,85 @@
|
|||
// @unocss-include
|
||||
export const accountFieldIcons: Record<string, string> = Object.fromEntries(Object.entries({
|
||||
Alipay: 'i-ri:alipay-line',
|
||||
Bilibili: 'i-ri:bilibili-line',
|
||||
Birth: 'i-ri:calendar-line',
|
||||
Blog: 'i-ri:newspaper-line',
|
||||
Bluesky: 'i-ri:bluesky-line',
|
||||
City: 'i-ri:map-pin-2-line',
|
||||
Dingding: 'i-ri:dingding-line',
|
||||
Discord: 'i-ri:discord-line',
|
||||
Douban: 'i-ri:douban-line',
|
||||
Facebook: 'i-ri:facebook-line',
|
||||
Friendica: 'i-ri:friendica-line',
|
||||
GitHub: 'i-ri:github-line',
|
||||
GitLab: 'i-ri:gitlab-line',
|
||||
GPG: 'i-ri:key-2-line',
|
||||
Home: 'i-ri:home-2-line',
|
||||
Instagram: 'i-ri:instagram-line',
|
||||
Joined: 'i-ri:user-add-line',
|
||||
Keyoxide: 'i-ri:key-2-line',
|
||||
Language: 'i-ri:translate-2',
|
||||
Languages: 'i-ri:translate-2',
|
||||
LinkedIn: 'i-ri:linkedin-box-line',
|
||||
Location: 'i-ri:map-pin-2-line',
|
||||
Mastodon: 'i-ri:mastodon-line',
|
||||
Matrix: 'i-tabler:brand-matrix',
|
||||
Medium: 'i-ri:medium-line',
|
||||
OpenPGP: 'i-ri:key-2-line',
|
||||
Patreon: 'i-ri:patreon-line',
|
||||
PayPal: 'i-ri:paypal-line',
|
||||
PGP: 'i-ri:key-2-line',
|
||||
Photos: 'i-ri:camera-2-line',
|
||||
Pinterest: 'i-ri:pinterest-line',
|
||||
PlayStation: 'i-ri:playstation-line',
|
||||
Portfolio: 'i-ri:link',
|
||||
Pronouns: 'i-ri:contacts-line',
|
||||
QQ: 'i-ri:qq-line',
|
||||
Site: 'i-ri:link',
|
||||
Sponsors: 'i-ri:heart-3-line',
|
||||
Spotify: 'i-ri:spotify-line',
|
||||
Steam: 'i-ri:steam-line',
|
||||
Switch: 'i-ri:switch-line',
|
||||
Telegram: 'i-ri:telegram-line',
|
||||
Threads: 'i-ri:threads-line',
|
||||
TikTok: 'i-ri:tiktok-line',
|
||||
Tumblr: 'i-ri:tumblr-line',
|
||||
Twitch: 'i-ri:twitch-line',
|
||||
Twitter: 'i-ri:twitter-line',
|
||||
Website: 'i-ri:link',
|
||||
WeChat: 'i-ri:wechat-line',
|
||||
Weibo: 'i-ri:weibo-line',
|
||||
Xbox: 'i-ri:xbox-line',
|
||||
YouTube: 'i-ri:youtube-line',
|
||||
Zhihu: 'i-ri:zhihu-line',
|
||||
}).sort(([a], [b]) => a.localeCompare(b)))
|
||||
|
||||
const accountFieldIconsLowercase = Object.fromEntries(
|
||||
Object.entries(accountFieldIcons).map(([k, v]) =>
|
||||
[k.toLowerCase(), v],
|
||||
),
|
||||
)
|
||||
|
||||
export function getAccountFieldIcon(value: string) {
|
||||
const name = value.trim().toLowerCase()
|
||||
return accountFieldIconsLowercase[name] || undefined
|
||||
}
|
||||
|
||||
export const statusVisibilities = [
|
||||
{
|
||||
value: 'public',
|
||||
icon: 'i-ri:global-line',
|
||||
},
|
||||
{
|
||||
value: 'unlisted',
|
||||
icon: 'i-ri:lock-unlock-line',
|
||||
},
|
||||
{
|
||||
value: 'private',
|
||||
icon: 'i-ri:lock-line',
|
||||
},
|
||||
{
|
||||
value: 'direct',
|
||||
icon: 'i-ri:at-line',
|
||||
},
|
||||
] as const
|
143
app/composables/masto/masto.ts
Normal file
143
app/composables/masto/masto.ts
Normal file
|
@ -0,0 +1,143 @@
|
|||
import type { UserLogin } from '#shared/types'
|
||||
import type { Pausable } from '@vueuse/core'
|
||||
import type { mastodon } from 'masto'
|
||||
import type { Ref } from 'vue'
|
||||
import type { ElkInstance } from '../users'
|
||||
import { createRestAPIClient, createStreamingAPIClient, MastoHttpError } from 'masto'
|
||||
|
||||
export function createMasto() {
|
||||
return {
|
||||
client: shallowRef<mastodon.rest.Client>(undefined as never),
|
||||
streamingClient: shallowRef<mastodon.streaming.Client | undefined>(),
|
||||
}
|
||||
}
|
||||
export type ElkMasto = ReturnType<typeof createMasto>
|
||||
|
||||
export function useMasto() {
|
||||
return useNuxtApp().$masto as ElkMasto
|
||||
}
|
||||
export function useMastoClient() {
|
||||
return useMasto().client.value
|
||||
}
|
||||
|
||||
export function mastoLogin(masto: ElkMasto, user: Pick<UserLogin, 'server' | 'token'>) {
|
||||
const server = user.server
|
||||
const url = `https://${server}`
|
||||
const instance: ElkInstance = reactive(getInstanceCache(server) || { uri: server, accountDomain: server })
|
||||
const accessToken = user.token
|
||||
|
||||
const createStreamingClient = (streamingApiUrl: string | undefined) => {
|
||||
return streamingApiUrl ? createStreamingAPIClient({ streamingApiUrl, accessToken, implementation: globalThis.WebSocket }) : undefined
|
||||
}
|
||||
|
||||
const streamingApiUrl = instance?.configuration?.urls?.streaming
|
||||
masto.client.value = createRestAPIClient({ url, accessToken })
|
||||
masto.streamingClient.value = createStreamingClient(streamingApiUrl)
|
||||
|
||||
// Refetch instance info in the background on login
|
||||
masto.client.value.v2.instance.fetch().catch(error => new Promise<mastodon.v2.Instance>((resolve, reject) => {
|
||||
if (error instanceof MastoHttpError && error.statusCode === 404) {
|
||||
return masto.client.value.v1.instance.fetch().then((newInstance) => {
|
||||
console.warn(`Instance ${server} on version ${newInstance.version} does not support "GET /api/v2/instance" API, try converting to v2 instance... expect some errors`)
|
||||
const v2Instance = {
|
||||
...newInstance,
|
||||
domain: newInstance.uri,
|
||||
sourceUrl: '',
|
||||
usage: {
|
||||
users: {
|
||||
activeMonth: 0,
|
||||
},
|
||||
},
|
||||
icon: [],
|
||||
apiVersions: {
|
||||
mastodon: newInstance.version,
|
||||
},
|
||||
contact: {
|
||||
email: newInstance.email,
|
||||
},
|
||||
configuration: {
|
||||
...(newInstance.configuration ?? {}),
|
||||
urls: {
|
||||
streaming: newInstance.urls.streamingApi,
|
||||
},
|
||||
},
|
||||
} as unknown as mastodon.v2.Instance
|
||||
return resolve(v2Instance)
|
||||
}).catch(reject)
|
||||
}
|
||||
|
||||
return reject(error)
|
||||
})).then((newInstance) => {
|
||||
Object.assign(instance, newInstance)
|
||||
if (newInstance.configuration.urls.streaming !== streamingApiUrl)
|
||||
masto.streamingClient.value = createStreamingClient(newInstance.configuration.urls.streaming)
|
||||
|
||||
instanceStorage.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.streaming.Client) => mastodon.streaming.Subscription,
|
||||
options: UseStreamingOptions<true>,
|
||||
): { stream: Ref<mastodon.streaming.Subscription | undefined> } & Pausable
|
||||
export function useStreaming(
|
||||
cb: (client: mastodon.streaming.Client) => mastodon.streaming.Subscription,
|
||||
options?: UseStreamingOptions<false>,
|
||||
): Ref<mastodon.streaming.Subscription | undefined>
|
||||
export function useStreaming(
|
||||
cb: (client: mastodon.streaming.Client) => mastodon.streaming.Subscription,
|
||||
{ immediate = true, controls }: UseStreamingOptions<boolean> = {},
|
||||
): ({ stream: Ref<mastodon.streaming.Subscription | undefined> } & Pausable) | Ref<mastodon.streaming.Subscription | undefined> {
|
||||
const { streamingClient } = useMasto()
|
||||
|
||||
const isActive = ref(immediate)
|
||||
const stream = ref<mastodon.streaming.Subscription>()
|
||||
|
||||
function pause() {
|
||||
isActive.value = false
|
||||
}
|
||||
|
||||
function resume() {
|
||||
isActive.value = true
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
if (stream.value) {
|
||||
stream.value.unsubscribe()
|
||||
stream.value = undefined
|
||||
}
|
||||
}
|
||||
|
||||
watchEffect(() => {
|
||||
cleanup()
|
||||
if (streamingClient.value && isActive.value)
|
||||
stream.value = cb(streamingClient.value)
|
||||
})
|
||||
|
||||
if (import.meta.client && !process.test)
|
||||
useNuxtApp().$pageLifecycle.addFrozenListener(cleanup)
|
||||
|
||||
tryOnBeforeUnmount(() => isActive.value = false)
|
||||
|
||||
if (controls)
|
||||
return { stream, isActive, pause, resume }
|
||||
else
|
||||
return stream
|
||||
}
|
81
app/composables/masto/notification.ts
Normal file
81
app/composables/masto/notification.ts
Normal file
|
@ -0,0 +1,81 @@
|
|||
import type { mastodon } from 'masto'
|
||||
|
||||
const notifications = reactive<Record<string, undefined | [Promise<mastodon.streaming.Subscription>, string[]]>>({})
|
||||
|
||||
export function useNotifications() {
|
||||
const id = currentUser.value?.account.id
|
||||
|
||||
const { client, streamingClient } = useMasto()
|
||||
|
||||
async function clearNotifications() {
|
||||
if (!id || !notifications[id])
|
||||
return
|
||||
|
||||
const lastReadId = notifications[id]![1][0]
|
||||
notifications[id]![1] = []
|
||||
|
||||
if (lastReadId) {
|
||||
await client.value.v1.markers.create({
|
||||
notifications: { lastReadId },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function processNotifications(stream: mastodon.streaming.Subscription, id: string) {
|
||||
for await (const entry of stream) {
|
||||
if (entry.event === 'notification' && notifications[id])
|
||||
notifications[id]![1].unshift(entry.payload.id)
|
||||
}
|
||||
}
|
||||
|
||||
async function connect(): Promise<void> {
|
||||
if (!isHydrated.value || !id || notifications[id] !== undefined || !currentUser.value?.token)
|
||||
return
|
||||
|
||||
let resolveStream: ((value: mastodon.streaming.Subscription | PromiseLike<mastodon.streaming.Subscription>) => void) | undefined
|
||||
const streamPromise = new Promise<mastodon.streaming.Subscription>(resolve => resolveStream = resolve)
|
||||
notifications[id] = [streamPromise, []]
|
||||
|
||||
await until(streamingClient).toBeTruthy()
|
||||
|
||||
const stream = streamingClient.value!.user.subscribe()
|
||||
resolveStream!(stream)
|
||||
|
||||
processNotifications(stream, id)
|
||||
|
||||
const position = await client.value.v1.markers.fetch({ timeline: ['notifications'] })
|
||||
const paginator = client.value.v1.notifications.list({ limit: 30 })
|
||||
|
||||
do {
|
||||
const result = await paginator.next()
|
||||
if (!result.done && result.value.length) {
|
||||
for (const notification of result.value) {
|
||||
if (notification.id === position.notifications.lastReadId)
|
||||
return
|
||||
notifications[id]![1].push(notification.id)
|
||||
}
|
||||
}
|
||||
else {
|
||||
break
|
||||
}
|
||||
} while (true)
|
||||
}
|
||||
|
||||
function disconnect(): void {
|
||||
if (!id || !notifications[id])
|
||||
return
|
||||
notifications[id]![0].then(stream => stream.unsubscribe())
|
||||
notifications[id] = undefined
|
||||
}
|
||||
|
||||
watch(currentUser, disconnect)
|
||||
|
||||
onHydrated(() => {
|
||||
connect()
|
||||
})
|
||||
|
||||
return {
|
||||
notifications: computed(() => id ? notifications[id]?.[1].length ?? 0 : 0),
|
||||
clearNotifications,
|
||||
}
|
||||
}
|
321
app/composables/masto/publish.ts
Normal file
321
app/composables/masto/publish.ts
Normal file
|
@ -0,0 +1,321 @@
|
|||
import type { DraftItem } from '#shared/types'
|
||||
import type { mastodon } from 'masto'
|
||||
import type { Ref } from 'vue'
|
||||
import { fileOpen } from 'browser-fs-access'
|
||||
|
||||
export function usePublish(options: {
|
||||
draftItem: Ref<DraftItem>
|
||||
expanded: Ref<boolean>
|
||||
isUploading: Ref<boolean>
|
||||
isPartOfThread: boolean
|
||||
initialDraft: () => DraftItem
|
||||
}) {
|
||||
const { draftItem } = options
|
||||
|
||||
const isEmpty = computed(() => isEmptyDraft([draftItem.value]))
|
||||
|
||||
const { client } = useMasto()
|
||||
const settings = useUserSettings()
|
||||
|
||||
const preferredLanguage = computed(() => (currentUser.value?.account.source.language || settings.value?.language || 'en').split('-')[0])
|
||||
|
||||
const isSending = ref(false)
|
||||
const isExpanded = ref(false)
|
||||
const failedMessages = ref<string[]>([])
|
||||
|
||||
const publishSpoilerText = computed({
|
||||
get() {
|
||||
return draftItem.value.params.sensitive ? draftItem.value.params.spoilerText : ''
|
||||
},
|
||||
set(val) {
|
||||
if (!draftItem.value.params.sensitive)
|
||||
return
|
||||
draftItem.value.params.spoilerText = val
|
||||
},
|
||||
})
|
||||
|
||||
const shouldExpanded = computed(() => options.expanded.value || isExpanded.value || !isEmpty.value)
|
||||
const isPublishDisabled = computed(() => {
|
||||
const { params, attachments } = draftItem.value
|
||||
const firstEmptyInputIndex = params.poll?.options.findIndex(option => option.trim().length === 0)
|
||||
return isEmpty.value
|
||||
|| options.isUploading.value
|
||||
|| isSending.value
|
||||
|| (attachments.length === 0 && !params.status)
|
||||
|| failedMessages.value.length > 0
|
||||
|| (attachments.length > 0 && params.poll !== null && params.poll !== undefined)
|
||||
|| ((params.poll !== null && params.poll !== undefined)
|
||||
&& (
|
||||
(firstEmptyInputIndex !== -1
|
||||
&& firstEmptyInputIndex !== params.poll.options.length - 1
|
||||
)
|
||||
|| params.poll.options.findLastIndex(option => option.trim().length > 0) + 1 < 2
|
||||
|| (new Set(params.poll.options).size !== params.poll.options.length)
|
||||
|| (currentInstance.value?.configuration?.polls.maxCharactersPerOption !== undefined
|
||||
&& params.poll.options.find(option => option.length > currentInstance.value!.configuration!.polls.maxCharactersPerOption) !== undefined
|
||||
)
|
||||
))
|
||||
})
|
||||
|
||||
watch(draftItem, () => {
|
||||
if (failedMessages.value.length > 0)
|
||||
failedMessages.value.length = 0
|
||||
}, { deep: true })
|
||||
|
||||
async function publishDraft() {
|
||||
if (isPublishDisabled.value)
|
||||
return
|
||||
|
||||
let content = htmlToText(draftItem.value.params.status || '')
|
||||
if (draftItem.value.mentions?.length)
|
||||
content = `${draftItem.value.mentions.map(i => `@${i}`).join(' ')} ${content}`
|
||||
|
||||
let poll
|
||||
|
||||
if (draftItem.value.params.poll) {
|
||||
let options = draftItem.value.params.poll.options
|
||||
|
||||
if (currentInstance.value?.configuration !== undefined
|
||||
&& (
|
||||
options.length < currentInstance.value.configuration.polls.maxOptions
|
||||
|| options[options.length - 1].trim().length === 0
|
||||
)
|
||||
) {
|
||||
options = options.slice(0, options.length - 1)
|
||||
}
|
||||
|
||||
poll = { ...draftItem.value.params.poll, options }
|
||||
}
|
||||
|
||||
const payload = {
|
||||
...draftItem.value.params,
|
||||
spoilerText: publishSpoilerText.value,
|
||||
status: content,
|
||||
mediaIds: draftItem.value.attachments.map(a => a.id),
|
||||
language: draftItem.value.params.language || preferredLanguage.value,
|
||||
poll,
|
||||
...(isGlitchEdition.value ? { 'content-type': 'text/markdown' } : {}),
|
||||
} as mastodon.rest.v1.CreateStatusParams
|
||||
|
||||
if (import.meta.dev) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.info({
|
||||
raw: draftItem.value.params.status,
|
||||
...payload,
|
||||
})
|
||||
// eslint-disable-next-line no-alert
|
||||
const result = confirm('[DEV] Payload logged to console, do you want to publish it?')
|
||||
if (!result)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
isSending.value = true
|
||||
|
||||
let status: mastodon.v1.Status
|
||||
if (!draftItem.value.editingStatus) {
|
||||
status = await client.value.v1.statuses.create(payload)
|
||||
}
|
||||
|
||||
else {
|
||||
status = await client.value.v1.statuses.$select(draftItem.value.editingStatus.id).update({
|
||||
...payload,
|
||||
mediaAttributes: draftItem.value.attachments.map(media => ({
|
||||
id: media.id,
|
||||
description: media.description,
|
||||
})),
|
||||
})
|
||||
}
|
||||
if (draftItem.value.params.inReplyToId && !options.isPartOfThread)
|
||||
navigateToStatus({ status })
|
||||
|
||||
draftItem.value = options.initialDraft()
|
||||
|
||||
return status
|
||||
}
|
||||
catch (err) {
|
||||
console.error(err)
|
||||
failedMessages.value.push((err as Error).message)
|
||||
}
|
||||
finally {
|
||||
isSending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isSending,
|
||||
isExpanded,
|
||||
shouldExpanded,
|
||||
isPublishDisabled,
|
||||
failedMessages,
|
||||
preferredLanguage,
|
||||
publishSpoilerText,
|
||||
publishDraft,
|
||||
}
|
||||
}
|
||||
|
||||
export type MediaAttachmentUploadError = [filename: string, message: string]
|
||||
|
||||
export function useUploadMediaAttachment(draft: Ref<DraftItem>) {
|
||||
const { client } = useMasto()
|
||||
const { t } = useI18n()
|
||||
const { formatFileSize } = useFileSizeFormatter()
|
||||
|
||||
const isUploading = ref<boolean>(false)
|
||||
const isExceedingAttachmentLimit = ref<boolean>(false)
|
||||
const failedAttachments = ref<MediaAttachmentUploadError[]>([])
|
||||
const dropZoneRef = ref<HTMLDivElement>()
|
||||
|
||||
const maxPixels = computed(() => {
|
||||
return currentInstance.value?.configuration?.mediaAttachments?.imageMatrixLimit
|
||||
?? 4096 ** 2
|
||||
})
|
||||
|
||||
const loadImage = (inputFile: Blob) => new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const url = URL.createObjectURL(inputFile)
|
||||
const img = new Image()
|
||||
|
||||
img.onerror = err => reject(err)
|
||||
img.onload = () => resolve(img)
|
||||
|
||||
img.src = url
|
||||
})
|
||||
|
||||
function resizeImage(img: HTMLImageElement, type = 'image/png'): Promise<Blob | null> {
|
||||
const { width, height } = img
|
||||
|
||||
const aspectRatio = (width as number) / (height as number)
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
|
||||
const resizedWidth = canvas.width = Math.round(Math.sqrt(maxPixels.value * aspectRatio))
|
||||
const resizedHeight = canvas.height = Math.round(Math.sqrt(maxPixels.value / aspectRatio))
|
||||
|
||||
const context = canvas.getContext('2d')
|
||||
|
||||
context?.drawImage(img, 0, 0, resizedWidth, resizedHeight)
|
||||
|
||||
return new Promise((resolve) => {
|
||||
canvas.toBlob(resolve, type)
|
||||
})
|
||||
}
|
||||
|
||||
async function processImageFile(file: File) {
|
||||
try {
|
||||
const image = await loadImage(file) as HTMLImageElement
|
||||
|
||||
if (image.width * image.height > maxPixels.value)
|
||||
file = await resizeImage(image, file.type) as File
|
||||
|
||||
return file
|
||||
}
|
||||
catch (e) {
|
||||
// Resize failed, just use the original file
|
||||
console.error(e)
|
||||
return file
|
||||
}
|
||||
}
|
||||
|
||||
async function processFile(file: File) {
|
||||
if (file.type.startsWith('image/'))
|
||||
return await processImageFile(file)
|
||||
|
||||
return file
|
||||
}
|
||||
|
||||
async function uploadAttachments(files: File[]) {
|
||||
isUploading.value = true
|
||||
failedAttachments.value = []
|
||||
// TODO: display some kind of message if too many media are selected
|
||||
// DONE
|
||||
const limit = currentInstance.value!.configuration?.statuses.maxMediaAttachments || 4
|
||||
const maxVideoSize = currentInstance.value!.configuration?.mediaAttachments.videoSizeLimit || 0
|
||||
const maxImageSize = currentInstance.value!.configuration?.mediaAttachments.imageSizeLimit || 0
|
||||
for (const file of files.slice(0, limit)) {
|
||||
if (draft.value.attachments.length < limit) {
|
||||
if (file.type.startsWith('image/')) {
|
||||
if (maxImageSize > 0 && file.size > maxImageSize) {
|
||||
failedAttachments.value = [...failedAttachments.value, [file.name, t('state.attachments_limit_image_error', [formatFileSize(maxImageSize)])]]
|
||||
continue
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (maxVideoSize > 0 && file.size > maxVideoSize) {
|
||||
const key
|
||||
= file.type.startsWith('audio/')
|
||||
? 'state.attachments_limit_audio_error'
|
||||
: file.type.startsWith('video/')
|
||||
? 'state.attachments_limit_video_error'
|
||||
: 'state.attachments_limit_unknown_error'
|
||||
const errorMessage = t(key, [formatFileSize(maxVideoSize)])
|
||||
failedAttachments.value = [
|
||||
...failedAttachments.value,
|
||||
[file.name, errorMessage],
|
||||
]
|
||||
continue
|
||||
}
|
||||
}
|
||||
isExceedingAttachmentLimit.value = false
|
||||
try {
|
||||
const attachment = await client.value.v1.media.create({
|
||||
file: await processFile(file),
|
||||
})
|
||||
draft.value.attachments.push(attachment)
|
||||
}
|
||||
catch (e) {
|
||||
// TODO: add some human-readable error message, problem is that masto api will not return response code
|
||||
console.error(e)
|
||||
failedAttachments.value = [...failedAttachments.value, [file.name, (e as Error).message]]
|
||||
}
|
||||
}
|
||||
else {
|
||||
isExceedingAttachmentLimit.value = true
|
||||
failedAttachments.value = [...failedAttachments.value, [file.name, t('state.attachments_limit_error')]]
|
||||
}
|
||||
}
|
||||
isUploading.value = false
|
||||
}
|
||||
|
||||
async function pickAttachments() {
|
||||
if (import.meta.server)
|
||||
return
|
||||
const mimeTypes = currentInstance.value!.configuration?.mediaAttachments.supportedMimeTypes
|
||||
const files = await fileOpen({
|
||||
description: 'Attachments',
|
||||
multiple: true,
|
||||
mimeTypes,
|
||||
})
|
||||
await uploadAttachments(files)
|
||||
}
|
||||
|
||||
async function setDescription(att: mastodon.v1.MediaAttachment, description: string) {
|
||||
att.description = description
|
||||
if (!draft.value.editingStatus)
|
||||
await client.value.v1.media.$select(att.id).update({ description: att.description })
|
||||
}
|
||||
|
||||
function removeAttachment(index: number) {
|
||||
draft.value.attachments.splice(index, 1)
|
||||
}
|
||||
|
||||
async function onDrop(files: File[] | null) {
|
||||
if (files)
|
||||
await uploadAttachments(files)
|
||||
}
|
||||
|
||||
const { isOverDropZone } = useDropZone(dropZoneRef, onDrop)
|
||||
|
||||
return {
|
||||
isUploading,
|
||||
isExceedingAttachmentLimit,
|
||||
isOverDropZone,
|
||||
|
||||
failedAttachments,
|
||||
dropZoneRef,
|
||||
|
||||
uploadAttachments,
|
||||
pickAttachments,
|
||||
setDescription,
|
||||
removeAttachment,
|
||||
}
|
||||
}
|
140
app/composables/masto/relationship.ts
Normal file
140
app/composables/masto/relationship.ts
Normal file
|
@ -0,0 +1,140 @@
|
|||
import type { mastodon } from 'masto'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
// Batch requests for relationships when used in the UI
|
||||
// We don't want to hold to old values, so every time a Relationship is needed it
|
||||
// is requested again from the server to show the latest state
|
||||
|
||||
const requestedRelationships = new Map<string, Ref<mastodon.v1.Relationship | undefined>>()
|
||||
let timeoutHandle: NodeJS.Timeout | undefined
|
||||
|
||||
export function useRelationship(account: mastodon.v1.Account): Ref<mastodon.v1.Relationship | undefined> {
|
||||
if (!currentUser.value)
|
||||
return ref()
|
||||
|
||||
let relationship = requestedRelationships.get(account.id)
|
||||
if (relationship)
|
||||
return relationship
|
||||
|
||||
// allow batch relationship requests
|
||||
relationship = ref<mastodon.v1.Relationship | undefined>()
|
||||
requestedRelationships.set(account.id, relationship)
|
||||
if (timeoutHandle)
|
||||
clearTimeout(timeoutHandle)
|
||||
timeoutHandle = setTimeout(() => {
|
||||
timeoutHandle = undefined
|
||||
fetchRelationships()
|
||||
}, 100)
|
||||
|
||||
return relationship
|
||||
}
|
||||
|
||||
async function fetchRelationships() {
|
||||
const requested = Array.from(requestedRelationships.entries()).filter(([, r]) => !r.value)
|
||||
const relationships = await useMastoClient().v1.accounts.relationships.fetch({ id: requested.map(([id]) => id) })
|
||||
for (const relationship of relationships) {
|
||||
const requestedToUpdate = requested.find(([id]) => id === relationship.id)
|
||||
if (!requestedToUpdate)
|
||||
continue
|
||||
requestedToUpdate[1].value = relationship
|
||||
}
|
||||
}
|
||||
|
||||
export async function toggleFollowAccount(relationship: mastodon.v1.Relationship, account: mastodon.v1.Account) {
|
||||
const { client } = useMasto()
|
||||
const i18n = useNuxtApp().$i18n
|
||||
|
||||
const unfollow = relationship!.following || relationship!.requested
|
||||
|
||||
if (unfollow) {
|
||||
const confirmUnfollow = await openConfirmDialog({
|
||||
title: i18n.t('confirm.unfollow.title'),
|
||||
description: i18n.t('confirm.unfollow.description', [`@${account.acct}`]),
|
||||
confirm: i18n.t('confirm.unfollow.confirm'),
|
||||
cancel: i18n.t('confirm.unfollow.cancel'),
|
||||
})
|
||||
if (confirmUnfollow.choice !== 'confirm')
|
||||
return
|
||||
}
|
||||
|
||||
if (unfollow) {
|
||||
relationship!.following = false
|
||||
relationship!.requested = false
|
||||
}
|
||||
else if (account.locked) {
|
||||
relationship!.requested = true
|
||||
}
|
||||
else {
|
||||
relationship!.following = true
|
||||
}
|
||||
|
||||
relationship = await client.value.v1.accounts.$select(account.id)[unfollow ? 'unfollow' : 'follow']()
|
||||
}
|
||||
|
||||
export async function toggleMuteAccount(relationship: mastodon.v1.Relationship, account: mastodon.v1.Account) {
|
||||
const { client } = useMasto()
|
||||
const i18n = useNuxtApp().$i18n
|
||||
|
||||
let duration = 0 // default 0 == indefinite
|
||||
let notifications = true // default true = mute notifications
|
||||
if (!relationship!.muting) {
|
||||
const confirmMute = await openConfirmDialog({
|
||||
title: i18n.t('confirm.mute_account.title'),
|
||||
description: i18n.t('confirm.mute_account.description', [account.acct]),
|
||||
confirm: i18n.t('confirm.mute_account.confirm'),
|
||||
cancel: i18n.t('confirm.mute_account.cancel'),
|
||||
extraOptionType: 'mute',
|
||||
})
|
||||
if (confirmMute.choice !== 'confirm')
|
||||
return
|
||||
|
||||
duration = confirmMute.extraOptions!.mute.duration
|
||||
notifications = confirmMute.extraOptions!.mute.notifications
|
||||
}
|
||||
|
||||
relationship!.muting = !relationship!.muting
|
||||
relationship = relationship!.muting
|
||||
? await client.value.v1.accounts.$select(account.id).mute({
|
||||
duration,
|
||||
notifications,
|
||||
})
|
||||
: await client.value.v1.accounts.$select(account.id).unmute()
|
||||
}
|
||||
|
||||
export async function toggleBlockAccount(relationship: mastodon.v1.Relationship, account: mastodon.v1.Account) {
|
||||
const { client } = useMasto()
|
||||
const i18n = useNuxtApp().$i18n
|
||||
|
||||
if (!relationship!.blocking) {
|
||||
const confirmBlock = await openConfirmDialog({
|
||||
title: i18n.t('confirm.block_account.title'),
|
||||
description: i18n.t('confirm.block_account.description', [account.acct]),
|
||||
confirm: i18n.t('confirm.block_account.confirm'),
|
||||
cancel: i18n.t('confirm.block_account.cancel'),
|
||||
})
|
||||
if (confirmBlock.choice !== 'confirm')
|
||||
return
|
||||
}
|
||||
|
||||
relationship!.blocking = !relationship!.blocking
|
||||
relationship = await client.value.v1.accounts.$select(account.id)[relationship!.blocking ? 'block' : 'unblock']()
|
||||
}
|
||||
|
||||
export async function toggleBlockDomain(relationship: mastodon.v1.Relationship, account: mastodon.v1.Account) {
|
||||
const { client } = useMasto()
|
||||
const i18n = useNuxtApp().$i18n
|
||||
|
||||
if (!relationship!.domainBlocking) {
|
||||
const confirmDomainBlock = await openConfirmDialog({
|
||||
title: i18n.t('confirm.block_domain.title'),
|
||||
description: i18n.t('confirm.block_domain.description', [getServerName(account)]),
|
||||
confirm: i18n.t('confirm.block_domain.confirm'),
|
||||
cancel: i18n.t('confirm.block_domain.cancel'),
|
||||
})
|
||||
if (confirmDomainBlock.choice !== 'confirm')
|
||||
return
|
||||
}
|
||||
|
||||
relationship!.domainBlocking = !relationship!.domainBlocking
|
||||
await client.value.v1.domainBlocks[relationship!.domainBlocking ? 'create' : 'remove']({ domain: getServerName(account) })
|
||||
}
|
79
app/composables/masto/routes.ts
Normal file
79
app/composables/masto/routes.ts
Normal file
|
@ -0,0 +1,79 @@
|
|||
import type { mastodon } from 'masto'
|
||||
import { withoutProtocol } from 'ufo'
|
||||
|
||||
export function getAccountRoute(account: mastodon.v1.Account) {
|
||||
return useRouter().resolve({
|
||||
name: 'account-index',
|
||||
params: {
|
||||
server: currentServer.value,
|
||||
account: extractAccountHandle(account),
|
||||
},
|
||||
})
|
||||
}
|
||||
export function getAccountFollowingRoute(account: mastodon.v1.Account) {
|
||||
return useRouter().resolve({
|
||||
name: 'account-following',
|
||||
params: {
|
||||
server: currentServer.value,
|
||||
account: extractAccountHandle(account),
|
||||
},
|
||||
})
|
||||
}
|
||||
export function getAccountFollowersRoute(account: mastodon.v1.Account) {
|
||||
return useRouter().resolve({
|
||||
name: 'account-followers',
|
||||
params: {
|
||||
server: currentServer.value,
|
||||
account: extractAccountHandle(account),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function getReportRoute(id: string | number) {
|
||||
return `https://${currentUser.value?.server}/admin/reports/${encodeURIComponent(id)}`
|
||||
}
|
||||
|
||||
export function getStatusRoute(status: mastodon.v1.Status) {
|
||||
return useRouter().resolve({
|
||||
name: 'status',
|
||||
params: {
|
||||
server: currentServer.value,
|
||||
account: extractAccountHandle(status.account),
|
||||
status: status.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function getTagRoute(tag: string) {
|
||||
return useRouter().resolve({
|
||||
name: 'tag',
|
||||
params: {
|
||||
server: currentServer.value,
|
||||
tag,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function getStatusPermalinkRoute(status: mastodon.v1.Status) {
|
||||
return status.url ? withoutProtocol(status.url) : null
|
||||
}
|
||||
|
||||
export function getStatusInReplyToRoute(status: mastodon.v1.Status) {
|
||||
return useRouter().resolve({
|
||||
name: 'status-by-id',
|
||||
params: {
|
||||
server: currentServer.value,
|
||||
status: status.inReplyToId,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function navigateToStatus({ status, focusReply = false }: {
|
||||
status: mastodon.v1.Status
|
||||
focusReply?: boolean
|
||||
}) {
|
||||
return navigateTo({
|
||||
path: getStatusRoute(status).href,
|
||||
state: { focusReply },
|
||||
})
|
||||
}
|
109
app/composables/masto/search.ts
Normal file
109
app/composables/masto/search.ts
Normal file
|
@ -0,0 +1,109 @@
|
|||
import type { MaybeRefOrGetter } from '@vueuse/core'
|
||||
import type { mastodon } from 'masto'
|
||||
import type { RouteLocation } from 'vue-router'
|
||||
|
||||
export type UseSearchOptions = MaybeRefOrGetter<
|
||||
Partial<Omit<mastodon.rest.v2.SearchParams, keyof mastodon.DefaultPaginationParams | 'q'>>
|
||||
>
|
||||
|
||||
export interface BuildSearchResult<K extends keyof any, T> {
|
||||
id: string
|
||||
type: K
|
||||
data: T
|
||||
to: RouteLocation & {
|
||||
href: string
|
||||
}
|
||||
}
|
||||
export type AccountSearchResult = BuildSearchResult<'account', mastodon.v1.Account>
|
||||
export type HashTagSearchResult = BuildSearchResult<'hashtag', mastodon.v1.Tag>
|
||||
export type StatusSearchResult = BuildSearchResult<'status', mastodon.v1.Status>
|
||||
|
||||
export type SearchResult = HashTagSearchResult | AccountSearchResult | StatusSearchResult
|
||||
|
||||
export function useSearch(query: MaybeRefOrGetter<string>, options: UseSearchOptions = {}) {
|
||||
const done = ref(false)
|
||||
const { client } = useMasto()
|
||||
const loading = ref(false)
|
||||
const accounts = ref<AccountSearchResult[]>([])
|
||||
const hashtags = ref<HashTagSearchResult[]>([])
|
||||
const statuses = ref<StatusSearchResult[]>([])
|
||||
|
||||
const q = computed(() => resolveUnref(query).trim())
|
||||
|
||||
let paginator: mastodon.Paginator<mastodon.v2.Search, mastodon.rest.v2.SearchParams> | undefined
|
||||
|
||||
const appendResults = (results: mastodon.v2.Search, empty = false) => {
|
||||
if (empty) {
|
||||
accounts.value = []
|
||||
hashtags.value = []
|
||||
statuses.value = []
|
||||
}
|
||||
accounts.value = [...accounts.value, ...results.accounts.map<AccountSearchResult>(account => ({
|
||||
type: 'account',
|
||||
id: account.id,
|
||||
data: account,
|
||||
to: getAccountRoute(account),
|
||||
}))]
|
||||
hashtags.value = [...hashtags.value, ...results.hashtags.map<HashTagSearchResult>(hashtag => ({
|
||||
type: 'hashtag',
|
||||
id: `hashtag-${hashtag.name}`,
|
||||
data: hashtag,
|
||||
to: getTagRoute(hashtag.name),
|
||||
}))]
|
||||
statuses.value = [...statuses.value, ...results.statuses.map<StatusSearchResult>(status => ({
|
||||
type: 'status',
|
||||
id: status.id,
|
||||
data: status,
|
||||
to: getStatusRoute(status),
|
||||
}))]
|
||||
}
|
||||
|
||||
watch(() => resolveUnref(query), () => {
|
||||
loading.value = !!(q.value && isHydrated.value)
|
||||
})
|
||||
|
||||
debouncedWatch(() => resolveUnref(query), async () => {
|
||||
if (!q.value || !isHydrated.value)
|
||||
return
|
||||
|
||||
loading.value = true
|
||||
|
||||
/**
|
||||
* 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 = client.value.v2.search.list({
|
||||
q: q.value,
|
||||
...resolveUnref(options),
|
||||
resolve: !!currentUser.value,
|
||||
})
|
||||
const nextResults = await paginator.next()
|
||||
|
||||
done.value = !!nextResults.done
|
||||
if (!nextResults.done)
|
||||
appendResults(nextResults.value, true)
|
||||
|
||||
loading.value = false
|
||||
}, { debounce: 300 })
|
||||
|
||||
const next = async () => {
|
||||
if (!q.value || !isHydrated.value || !paginator)
|
||||
return
|
||||
|
||||
loading.value = true
|
||||
const nextResults = await paginator.next()
|
||||
loading.value = false
|
||||
|
||||
done.value = !!nextResults.done
|
||||
if (!nextResults.done)
|
||||
appendResults(nextResults.value)
|
||||
}
|
||||
|
||||
return {
|
||||
accounts,
|
||||
hashtags,
|
||||
statuses,
|
||||
loading: readonly(loading),
|
||||
next,
|
||||
}
|
||||
}
|
104
app/composables/masto/status.ts
Normal file
104
app/composables/masto/status.ts
Normal file
|
@ -0,0 +1,104 @@
|
|||
import type { mastodon } from 'masto'
|
||||
|
||||
type Action = 'reblogged' | 'favourited' | 'bookmarked' | 'pinned' | 'muted'
|
||||
type CountField = 'reblogsCount' | 'favouritesCount'
|
||||
|
||||
export interface StatusActionsProps {
|
||||
status: mastodon.v1.Status
|
||||
}
|
||||
|
||||
export function useStatusActions(props: StatusActionsProps) {
|
||||
const status = ref<mastodon.v1.Status>({ ...props.status })
|
||||
const { client } = useMasto()
|
||||
|
||||
watch(
|
||||
() => props.status,
|
||||
val => status.value = { ...val },
|
||||
{ deep: true, immediate: true },
|
||||
)
|
||||
|
||||
// Use different states to let the user press different actions right after the other
|
||||
const isLoading = ref({
|
||||
reblogged: false,
|
||||
favourited: false,
|
||||
bookmarked: false,
|
||||
pinned: false,
|
||||
translation: false,
|
||||
muted: false,
|
||||
})
|
||||
|
||||
async function toggleStatusAction(action: Action, fetchNewStatus: () => Promise<mastodon.v1.Status>, countField?: CountField) {
|
||||
// check login
|
||||
if (!checkLogin())
|
||||
return
|
||||
|
||||
const prevCount = countField ? status.value[countField] : undefined
|
||||
|
||||
isLoading.value[action] = true
|
||||
const isCancel = status.value[action]
|
||||
fetchNewStatus().then((newStatus) => {
|
||||
// when the action is cancelled, the count is not updated highly likely (if they're the same)
|
||||
// issue of Mastodon API
|
||||
if (isCancel && countField && prevCount === newStatus[countField])
|
||||
newStatus[countField] -= 1
|
||||
|
||||
Object.assign(status.value, newStatus)
|
||||
cacheStatus(newStatus, undefined, true)
|
||||
}).finally(() => {
|
||||
isLoading.value[action] = false
|
||||
})
|
||||
// Optimistic update
|
||||
status.value[action] = !status.value[action]
|
||||
cacheStatus(status.value, undefined, true)
|
||||
if (countField)
|
||||
status.value[countField] += status.value[action] ? 1 : -1
|
||||
}
|
||||
|
||||
const canReblog = computed(() =>
|
||||
status.value.visibility !== 'direct'
|
||||
&& (status.value.visibility !== 'private' || status.value.account.id === currentUser.value?.account.id),
|
||||
)
|
||||
|
||||
const toggleReblog = () => toggleStatusAction(
|
||||
'reblogged',
|
||||
() => client.value.v1.statuses.$select(status.value.id)[status.value.reblogged ? 'unreblog' : 'reblog']().then((res) => {
|
||||
if (status.value.reblogged)
|
||||
// returns the original status
|
||||
return res.reblog!
|
||||
return res
|
||||
}),
|
||||
'reblogsCount',
|
||||
)
|
||||
|
||||
const toggleFavourite = () => toggleStatusAction(
|
||||
'favourited',
|
||||
() => client.value.v1.statuses.$select(status.value.id)[status.value.favourited ? 'unfavourite' : 'favourite'](),
|
||||
'favouritesCount',
|
||||
)
|
||||
|
||||
const toggleBookmark = () => toggleStatusAction(
|
||||
'bookmarked',
|
||||
() => client.value.v1.statuses.$select(status.value.id)[status.value.bookmarked ? 'unbookmark' : 'bookmark'](),
|
||||
)
|
||||
|
||||
const togglePin = async () => toggleStatusAction(
|
||||
'pinned',
|
||||
() => client.value.v1.statuses.$select(status.value.id)[status.value.pinned ? 'unpin' : 'pin'](),
|
||||
)
|
||||
|
||||
const toggleMute = async () => toggleStatusAction(
|
||||
'muted',
|
||||
() => client.value.v1.statuses.$select(status.value.id)[status.value.muted ? 'unmute' : 'mute'](),
|
||||
)
|
||||
|
||||
return {
|
||||
status,
|
||||
isLoading,
|
||||
canReblog,
|
||||
toggleMute,
|
||||
toggleReblog,
|
||||
toggleFavourite,
|
||||
toggleBookmark,
|
||||
togglePin,
|
||||
}
|
||||
}
|
192
app/composables/masto/statusDrafts.ts
Normal file
192
app/composables/masto/statusDrafts.ts
Normal file
|
@ -0,0 +1,192 @@
|
|||
import type { DraftItem, DraftMap } from '#shared/types'
|
||||
import type { Mutable } from '#shared/types/utils'
|
||||
import type { mastodon } from 'masto'
|
||||
import type { ComputedRef, Ref } from 'vue'
|
||||
import { STORAGE_KEY_DRAFTS } from '~/constants'
|
||||
|
||||
export const currentUserDrafts = (import.meta.server || process.test)
|
||||
? computed<DraftMap>(() => ({}))
|
||||
: useUserLocalStorage<DraftMap>(STORAGE_KEY_DRAFTS, () => ({}))
|
||||
|
||||
export const builtinDraftKeys = [
|
||||
'dialog',
|
||||
'home',
|
||||
]
|
||||
|
||||
const ALL_VISIBILITY = ['public', 'unlisted', 'private', 'direct'] as const
|
||||
|
||||
function getDefaultVisibility(currentVisibility: mastodon.v1.StatusVisibility) {
|
||||
// The default privacy only should be taken into account if it makes
|
||||
// the post more private than the replying to post
|
||||
const preferredVisibility = currentUser.value?.account.source.privacy || 'public'
|
||||
return ALL_VISIBILITY.indexOf(currentVisibility)
|
||||
> ALL_VISIBILITY.indexOf(preferredVisibility)
|
||||
? currentVisibility
|
||||
: preferredVisibility
|
||||
}
|
||||
|
||||
export function getDefaultDraftItem(options: Partial<Mutable<mastodon.rest.v1.CreateStatusParams> & Omit<DraftItem, 'params'>> = {}): DraftItem {
|
||||
const {
|
||||
attachments = [],
|
||||
initialText = '',
|
||||
status,
|
||||
inReplyToId,
|
||||
visibility,
|
||||
sensitive,
|
||||
spoilerText,
|
||||
language,
|
||||
mentions,
|
||||
poll,
|
||||
} = options
|
||||
|
||||
return {
|
||||
attachments,
|
||||
initialText,
|
||||
params: {
|
||||
status: status || '',
|
||||
poll,
|
||||
inReplyToId,
|
||||
visibility: getDefaultVisibility(visibility || 'public'),
|
||||
sensitive: sensitive ?? false,
|
||||
spoilerText: spoilerText || '',
|
||||
language: language || '', // auto inferred from current language on posting
|
||||
},
|
||||
mentions,
|
||||
lastUpdated: Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
export async function getDraftFromStatus(status: mastodon.v1.Status): Promise<DraftItem> {
|
||||
const info = {
|
||||
status: await convertMastodonHTML(status.content),
|
||||
visibility: status.visibility,
|
||||
attachments: status.mediaAttachments,
|
||||
sensitive: status.sensitive,
|
||||
spoilerText: status.spoilerText,
|
||||
language: status.language,
|
||||
inReplyToId: status.inReplyToId,
|
||||
}
|
||||
|
||||
return getDefaultDraftItem((status.mediaAttachments !== undefined && status.mediaAttachments.length > 0)
|
||||
? { ...info, mediaIds: status.mediaAttachments.map(att => att.id) }
|
||||
: {
|
||||
...info,
|
||||
poll: status.poll
|
||||
? {
|
||||
expiresIn: Math.abs(new Date().getTime() - new Date(status.poll.expiresAt!).getTime()) / 1000,
|
||||
options: [...status.poll.options.map(({ title }) => title), ''],
|
||||
multiple: status.poll.multiple,
|
||||
hideTotals: status.poll.options[0].votesCount === null,
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
function getAccountsToMention(status: mastodon.v1.Status) {
|
||||
const userId = currentUser.value?.account.id
|
||||
const accountsToMention = new Set<string>()
|
||||
if (status.account.id !== userId)
|
||||
accountsToMention.add(status.account.acct)
|
||||
status.mentions
|
||||
.filter(mention => mention.id !== userId)
|
||||
.map(mention => mention.acct)
|
||||
.forEach(i => accountsToMention.add(i))
|
||||
return Array.from(accountsToMention)
|
||||
}
|
||||
|
||||
export function getReplyDraft(status: mastodon.v1.Status) {
|
||||
const accountsToMention = getAccountsToMention(status)
|
||||
return {
|
||||
key: `reply-${status.id}`,
|
||||
draft: () => {
|
||||
return getDefaultDraftItem({
|
||||
initialText: '',
|
||||
inReplyToId: status!.id,
|
||||
sensitive: status.sensitive,
|
||||
spoilerText: status.spoilerText,
|
||||
visibility: status.visibility,
|
||||
mentions: accountsToMention,
|
||||
language: status.language,
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function isEmptyDraft(drafts: Array<DraftItem> | DraftItem | null | undefined) {
|
||||
if (!drafts)
|
||||
return true
|
||||
|
||||
const draftsArray: Array<DraftItem> = Array.isArray(drafts) ? drafts : [drafts]
|
||||
|
||||
if (draftsArray.length === 0)
|
||||
return true
|
||||
|
||||
const anyDraftHasContent = draftsArray.some((draft) => {
|
||||
const { params, attachments } = draft
|
||||
const status = params.status ?? ''
|
||||
const text = htmlToText(status).trim().replace(/^(@\S+\s?)+/, '').replaceAll(/```/g, '').trim()
|
||||
|
||||
return (text.length > 0)
|
||||
|| (attachments.length > 0)
|
||||
})
|
||||
|
||||
return !anyDraftHasContent
|
||||
}
|
||||
|
||||
export interface UseDraft {
|
||||
draftItems: Ref<Array<DraftItem>>
|
||||
isEmpty: ComputedRef<boolean> | Ref<boolean>
|
||||
}
|
||||
|
||||
export function useDraft(
|
||||
draftKey: string,
|
||||
initial: () => DraftItem = () => getDefaultDraftItem({}),
|
||||
): UseDraft {
|
||||
const draftItems = computed({
|
||||
get() {
|
||||
if (!currentUserDrafts.value[draftKey])
|
||||
currentUserDrafts.value[draftKey] = [initial()]
|
||||
const drafts = currentUserDrafts.value[draftKey]
|
||||
if (Array.isArray(drafts))
|
||||
return drafts
|
||||
return [drafts]
|
||||
},
|
||||
set(val) {
|
||||
currentUserDrafts.value[draftKey] = val
|
||||
},
|
||||
})
|
||||
|
||||
const isEmpty = computed(() => isEmptyDraft(draftItems.value))
|
||||
|
||||
onUnmounted(async () => {
|
||||
// Remove draft if it's empty
|
||||
if (isEmpty.value && draftKey) {
|
||||
await nextTick()
|
||||
delete currentUserDrafts.value[draftKey]
|
||||
}
|
||||
})
|
||||
|
||||
return { draftItems, isEmpty }
|
||||
}
|
||||
|
||||
export function mentionUser(account: mastodon.v1.Account) {
|
||||
openPublishDialog('dialog', getDefaultDraftItem({
|
||||
status: `@${account.acct} `,
|
||||
}))
|
||||
}
|
||||
|
||||
export function directMessageUser(account: mastodon.v1.Account) {
|
||||
openPublishDialog('dialog', getDefaultDraftItem({
|
||||
status: `@${account.acct} `,
|
||||
visibility: 'direct',
|
||||
}))
|
||||
}
|
||||
|
||||
export function clearEmptyDrafts() {
|
||||
for (const key in currentUserDrafts.value) {
|
||||
if (builtinDraftKeys.includes(key) && !isEmptyDraft(currentUserDrafts.value[key]))
|
||||
continue
|
||||
if (isEmptyDraft(currentUserDrafts.value[key]))
|
||||
delete currentUserDrafts.value[key]
|
||||
}
|
||||
}
|
137
app/composables/masto/translate.ts
Normal file
137
app/composables/masto/translate.ts
Normal file
|
@ -0,0 +1,137 @@
|
|||
import type { mastodon } from 'masto'
|
||||
|
||||
export interface TranslationResponse {
|
||||
translatedText: string
|
||||
detectedLanguage: {
|
||||
confidence: number
|
||||
language: string
|
||||
}
|
||||
}
|
||||
|
||||
// @see https://github.com/LibreTranslate/LibreTranslate/tree/main/libretranslate/locales
|
||||
export const supportedTranslationCodes = [
|
||||
'ar',
|
||||
'az',
|
||||
'cs',
|
||||
'da',
|
||||
'de',
|
||||
'el',
|
||||
'en',
|
||||
'eo',
|
||||
'es',
|
||||
'fa',
|
||||
'fi',
|
||||
'fr',
|
||||
'ga',
|
||||
'he',
|
||||
'hi',
|
||||
'hu',
|
||||
'id',
|
||||
'it',
|
||||
'ja',
|
||||
'ko',
|
||||
'nl',
|
||||
'pl',
|
||||
'pt',
|
||||
'ru',
|
||||
'sk',
|
||||
'sv',
|
||||
'tr',
|
||||
'uk',
|
||||
'vi',
|
||||
'zh',
|
||||
] as const
|
||||
|
||||
export function getLanguageCode() {
|
||||
let code = 'en'
|
||||
const getCode = (code: string) => code.replace(/-.*$/, '')
|
||||
if (import.meta.client) {
|
||||
const { locale } = useI18n()
|
||||
code = getCode(locale.value ? locale.value : navigator.language)
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
interface TranslationErr {
|
||||
data?: {
|
||||
error?: string
|
||||
}
|
||||
}
|
||||
|
||||
export async function translateText(text: string, from: string | null | undefined, to: string) {
|
||||
const config = useRuntimeConfig()
|
||||
const status = ref({
|
||||
success: false,
|
||||
error: '',
|
||||
text: '',
|
||||
})
|
||||
const regex = /<a[^>]*>.*?<\/a>/g
|
||||
try {
|
||||
const response = await ($fetch as any)(config.public.translateApi, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
q: text,
|
||||
source: from ?? 'auto',
|
||||
target: to,
|
||||
format: 'html',
|
||||
api_key: '',
|
||||
},
|
||||
}) as TranslationResponse
|
||||
status.value.success = true
|
||||
// replace the translated links with the original
|
||||
status.value.text = response.translatedText.replace(regex, (match) => {
|
||||
const tagLink = regex.exec(text)
|
||||
return tagLink ? tagLink[0] : match
|
||||
})
|
||||
}
|
||||
catch (err) {
|
||||
// TODO: improve type
|
||||
if ((err as TranslationErr).data?.error)
|
||||
status.value.error = (err as TranslationErr).data!.error!
|
||||
else
|
||||
status.value.error = 'Unknown Error, Please check your console in browser devtool.'
|
||||
console.error('Translate Post Error: ', err)
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
const translations = new WeakMap<mastodon.v1.Status | mastodon.v1.StatusEdit, {
|
||||
visible: boolean
|
||||
text: string
|
||||
success: boolean
|
||||
error: string
|
||||
}>()
|
||||
|
||||
export function useTranslation(status: mastodon.v1.Status | mastodon.v1.StatusEdit, to: string) {
|
||||
if (!translations.has(status))
|
||||
translations.set(status, reactive({ visible: false, text: '', success: false, error: '' }))
|
||||
|
||||
const translation = translations.get(status)!
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
const shouldTranslate = 'language' in status && status.language && status.language !== to
|
||||
&& supportedTranslationCodes.includes(to as any)
|
||||
&& supportedTranslationCodes.includes(status.language as any)
|
||||
&& !userSettings.value.disabledTranslationLanguages.includes(status.language)
|
||||
const enabled = /*! !useRuntimeConfig().public.translateApi && */ shouldTranslate
|
||||
|
||||
async function toggle() {
|
||||
if (!shouldTranslate)
|
||||
return
|
||||
|
||||
if (!translation.text) {
|
||||
const translated = await translateText(status.content, status.language, to)
|
||||
translation.error = translated.value.error
|
||||
translation.text = translated.value.text
|
||||
translation.success = translated.value.success
|
||||
}
|
||||
|
||||
translation.visible = !translation.visible
|
||||
}
|
||||
|
||||
return {
|
||||
enabled,
|
||||
toggle,
|
||||
translation,
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue