Merge branch 'api-refactor' into shigusegubu-themes3
This commit is contained in:
commit
e2ee976a88
21 changed files with 259 additions and 257 deletions
|
|
@ -98,41 +98,31 @@ export const promisedRequest = async ({
|
|||
}
|
||||
}
|
||||
|
||||
let response = null
|
||||
try {
|
||||
response = await fetch(url, options)
|
||||
const data = await (async () => {
|
||||
const [contentType] = response.headers
|
||||
.get('content-type')
|
||||
.split(';')
|
||||
.map((x) => x.toLowerCase().trim())
|
||||
const contentLength = parseInt(response.headers.get('content-length'))
|
||||
if (contentLength === 0) return null
|
||||
const response = await fetch(url, options)
|
||||
const data = await (async () => {
|
||||
const [contentType] = response.headers
|
||||
.get('content-type')
|
||||
.split(';')
|
||||
.map((x) => x.toLowerCase().trim())
|
||||
const contentLength = parseInt(response.headers.get('content-length'))
|
||||
if (contentLength === 0) return null
|
||||
|
||||
switch (contentType) {
|
||||
case 'text/plain':
|
||||
return await response.text()
|
||||
case 'application/json':
|
||||
return await response.json()
|
||||
default:
|
||||
return await response.bytes()
|
||||
}
|
||||
})()
|
||||
|
||||
const { ok, status } = response
|
||||
|
||||
if (ok) {
|
||||
return { response, status, data }
|
||||
} else {
|
||||
throw new StatusCodeError(
|
||||
response.status,
|
||||
data,
|
||||
{ url, options },
|
||||
response,
|
||||
)
|
||||
switch (contentType) {
|
||||
case 'text/plain':
|
||||
return await response.text()
|
||||
case 'application/json':
|
||||
return await response.json()
|
||||
default:
|
||||
return await response.bytes()
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(error, { url, options }, response)
|
||||
})()
|
||||
|
||||
const { ok, status } = response
|
||||
|
||||
if (ok) {
|
||||
return { response, status, data }
|
||||
} else {
|
||||
throw new StatusCodeError(response.status, data, { url, options }, response)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,8 +2,6 @@ import { reduce } from 'lodash'
|
|||
|
||||
import { paramsString, promisedRequest } from './helpers.js'
|
||||
|
||||
import { StatusCodeError } from 'src/services/errors/errors.js'
|
||||
|
||||
const REDIRECT_URI = `${window.location.origin}/oauth-callback`
|
||||
|
||||
export const MASTODON_APP_VERIFY_URL = '/api/v1/apps/verify_credentials'
|
||||
|
|
|
|||
|
|
@ -1,10 +1,6 @@
|
|||
import { concat, each, last, map } from 'lodash'
|
||||
|
||||
import { paramsString, promisedRequest } from './helpers.js'
|
||||
|
||||
import {
|
||||
parseAttachment,
|
||||
parseChat,
|
||||
parseLinkHeaderPagination,
|
||||
parseNotification,
|
||||
parseSource,
|
||||
|
|
@ -143,8 +139,6 @@ const MASTODON_SEARCH_2 = ({
|
|||
`/api/v2/search${paramsString({ q, resolve, limit, offset, following, type, withRelationships, accountId, excludeUnreviewed })}`
|
||||
const MASTODON_USER_SEARCH_URL = ({ q, resolve }) =>
|
||||
`/api/v1/accounts/search${paramsString({ q, resolve })}`
|
||||
const MASTODON_STREAMING = ({ accessToken, stream }) =>
|
||||
`/api/v1/streaming${paramsString({ accessToken, stream })}`
|
||||
const MASTODON_KNOWN_DOMAIN_LIST_URL = '/api/v1/instance/peers'
|
||||
const PLEROMA_EMOJI_REACTIONS_URL = (id) =>
|
||||
`/api/v1/pleroma/statuses/${id}/reactions`
|
||||
|
|
@ -487,168 +481,6 @@ export const search2 = ({
|
|||
export const fetchKnownDomains = ({ credentials }) =>
|
||||
promisedRequest({ url: MASTODON_KNOWN_DOMAIN_LIST_URL, credentials })
|
||||
|
||||
export const getMastodonSocketURI = ({ credentials, stream }, base) => {
|
||||
return base + MASTODON_STREAMING({ accessToken: credentials, stream })
|
||||
}
|
||||
|
||||
const MASTODON_STREAMING_EVENTS = new Set([
|
||||
'update',
|
||||
'notification',
|
||||
'delete',
|
||||
'filters_changed',
|
||||
'status.update',
|
||||
])
|
||||
|
||||
const PLEROMA_STREAMING_EVENTS = new Set([
|
||||
'pleroma:chat_update',
|
||||
'pleroma:respond',
|
||||
])
|
||||
|
||||
// A thin wrapper around WebSocket API that allows adding a pre-processor to it
|
||||
// Uses EventTarget and a CustomEvent to proxy events
|
||||
export const ProcessedWS = ({
|
||||
url,
|
||||
preprocessor = handleMastoWS,
|
||||
id = 'Unknown',
|
||||
credentials,
|
||||
}) => {
|
||||
const eventTarget = new EventTarget()
|
||||
const socket = new WebSocket(url)
|
||||
if (!socket) throw new Error(`Failed to create socket ${id}`)
|
||||
const proxy = (original, eventName, processor = (a) => a) => {
|
||||
original.addEventListener(eventName, (eventData) => {
|
||||
eventTarget.dispatchEvent(
|
||||
new CustomEvent(eventName, { detail: processor(eventData) }),
|
||||
)
|
||||
})
|
||||
}
|
||||
socket.addEventListener('open', (wsEvent) => {
|
||||
console.debug(`[WS][${id}] Socket connected`, wsEvent)
|
||||
if (credentials) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'pleroma:authenticate',
|
||||
token: credentials,
|
||||
}),
|
||||
)
|
||||
}
|
||||
})
|
||||
socket.addEventListener('error', (wsEvent) => {
|
||||
console.debug(`[WS][${id}] Socket errored`, wsEvent)
|
||||
})
|
||||
socket.addEventListener('close', (wsEvent) => {
|
||||
console.debug(
|
||||
`[WS][${id}] Socket disconnected with code ${wsEvent.code}`,
|
||||
wsEvent,
|
||||
)
|
||||
})
|
||||
// Commented code reason: very spammy, uncomment to enable message debug logging
|
||||
/*
|
||||
socket.addEventListener('message', (wsEvent) => {
|
||||
console.debug(
|
||||
`[WS][${id}] Message received`,
|
||||
wsEvent
|
||||
)
|
||||
})
|
||||
/**/
|
||||
|
||||
const onAuthenticated = () => {
|
||||
eventTarget.dispatchEvent(new CustomEvent('pleroma:authenticated'))
|
||||
}
|
||||
|
||||
proxy(socket, 'open')
|
||||
proxy(socket, 'close')
|
||||
proxy(socket, 'message', (event) => preprocessor(event, { onAuthenticated }))
|
||||
proxy(socket, 'error')
|
||||
|
||||
// 1000 = Normal Closure
|
||||
eventTarget.close = () => {
|
||||
socket.close(1000, 'Shutting down socket')
|
||||
}
|
||||
eventTarget.getState = () => socket.readyState
|
||||
eventTarget.subscribe = (stream, args = {}) => {
|
||||
console.debug(`[WS][${id}] Subscribing to stream ${stream} with args`, args)
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'subscribe',
|
||||
stream,
|
||||
...args,
|
||||
}),
|
||||
)
|
||||
}
|
||||
eventTarget.unsubscribe = (stream, args = {}) => {
|
||||
console.debug(
|
||||
`[WS][${id}] Unsubscribing from stream ${stream} with args`,
|
||||
args,
|
||||
)
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'unsubscribe',
|
||||
stream,
|
||||
...args,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return eventTarget
|
||||
}
|
||||
|
||||
export const handleMastoWS = (
|
||||
wsEvent,
|
||||
{
|
||||
onAuthenticated = () => {
|
||||
/* no-op */
|
||||
},
|
||||
} = {},
|
||||
) => {
|
||||
const { data } = wsEvent
|
||||
if (!data) return
|
||||
const parsedEvent = JSON.parse(data)
|
||||
const { event, payload } = parsedEvent
|
||||
if (
|
||||
MASTODON_STREAMING_EVENTS.has(event) ||
|
||||
PLEROMA_STREAMING_EVENTS.has(event)
|
||||
) {
|
||||
// MastoBE and PleromaBE both send payload for delete as a PLAIN string
|
||||
if (event === 'delete') {
|
||||
return { event, id: payload }
|
||||
}
|
||||
const data = payload ? JSON.parse(payload) : null
|
||||
if (event === 'pleroma:respond') {
|
||||
if (data.type === 'pleroma:authenticate') {
|
||||
if (data.result === 'success') {
|
||||
console.debug('[WS] Successfully authenticated')
|
||||
onAuthenticated()
|
||||
} else {
|
||||
console.error('[WS] Unable to authenticate:', data.error)
|
||||
wsEvent.target.close()
|
||||
}
|
||||
}
|
||||
return null
|
||||
} else if (event === 'update') {
|
||||
return { event, status: parseStatus(data) }
|
||||
} else if (event === 'status.update') {
|
||||
return { event, status: parseStatus(data) }
|
||||
} else if (event === 'notification') {
|
||||
return { event, notification: parseNotification(data) }
|
||||
} else if (event === 'pleroma:chat_update') {
|
||||
return { event, chatUpdate: parseChat(data) }
|
||||
}
|
||||
} else {
|
||||
console.warn('Unknown event', wsEvent)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const WSConnectionStatus = Object.freeze({
|
||||
JOINED: 1,
|
||||
CLOSED: 2,
|
||||
ERROR: 3,
|
||||
DISABLED: 4,
|
||||
STARTING: 5,
|
||||
STARTING_INITIAL: 6,
|
||||
})
|
||||
|
||||
export const fetchScrobbles = ({ accountId, limit = 1 }) =>
|
||||
promisedRequest({
|
||||
url: PLEROMA_SCROBBLES_URL(accountId, { limit }),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { concat, each, last, map } from 'lodash'
|
||||
import { concat, last } from 'lodash'
|
||||
|
||||
import { paramsString, promisedRequest } from './helpers.js'
|
||||
import { fetchFriends, MASTODON_STATUS_URL } from './public.js'
|
||||
|
|
|
|||
176
src/api/websocket.js
Normal file
176
src/api/websocket.js
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
import { paramsString, promisedRequest } from './helpers.js'
|
||||
|
||||
import {
|
||||
parseChat,
|
||||
parseNotification,
|
||||
parseStatus,
|
||||
} from 'src/services/entity_normalizer/entity_normalizer.service.js'
|
||||
|
||||
const MASTODON_STREAMING = ({ accessToken, stream }) =>
|
||||
`/api/v1/streaming${paramsString({ accessToken, stream })}`
|
||||
|
||||
export const getMastodonSocketURI = ({ credentials, stream }) => {
|
||||
return MASTODON_STREAMING({ accessToken: credentials, stream })
|
||||
}
|
||||
|
||||
const MASTODON_STREAMING_EVENTS = new Set([
|
||||
'update',
|
||||
'notification',
|
||||
'delete',
|
||||
'filters_changed',
|
||||
'status.update',
|
||||
])
|
||||
|
||||
const PLEROMA_STREAMING_EVENTS = new Set([
|
||||
'pleroma:chat_update',
|
||||
'pleroma:respond',
|
||||
])
|
||||
|
||||
// A thin wrapper around WebSocket API that allows adding a pre-processor to it
|
||||
// Uses EventTarget and a CustomEvent to proxy events
|
||||
export const ProcessedWS = ({
|
||||
url,
|
||||
preprocessor = handleMastoWS,
|
||||
id = 'Unknown',
|
||||
credentials,
|
||||
}) => {
|
||||
const eventTarget = new EventTarget()
|
||||
const socket = new WebSocket(url)
|
||||
if (!socket) throw new Error(`Failed to create socket ${id}`)
|
||||
const proxy = (original, eventName, processor = (a) => a) => {
|
||||
original.addEventListener(eventName, (eventData) => {
|
||||
eventTarget.dispatchEvent(
|
||||
new CustomEvent(eventName, { detail: processor(eventData) }),
|
||||
)
|
||||
})
|
||||
}
|
||||
socket.addEventListener('open', (wsEvent) => {
|
||||
console.debug(`[WS][${id}] Socket connected`, wsEvent)
|
||||
if (credentials) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'pleroma:authenticate',
|
||||
token: credentials,
|
||||
}),
|
||||
)
|
||||
}
|
||||
})
|
||||
socket.addEventListener('error', (wsEvent) => {
|
||||
console.debug(`[WS][${id}] Socket errored`, wsEvent)
|
||||
})
|
||||
socket.addEventListener('close', (wsEvent) => {
|
||||
console.debug(
|
||||
`[WS][${id}] Socket disconnected with code ${wsEvent.code}`,
|
||||
wsEvent,
|
||||
)
|
||||
})
|
||||
// Commented code reason: very spammy, uncomment to enable message debug logging
|
||||
/*
|
||||
socket.addEventListener('message', (wsEvent) => {
|
||||
console.debug(
|
||||
`[WS][${id}] Message received`,
|
||||
wsEvent
|
||||
)
|
||||
})
|
||||
/**/
|
||||
|
||||
const onAuthenticated = () => {
|
||||
eventTarget.dispatchEvent(new CustomEvent('pleroma:authenticated'))
|
||||
}
|
||||
|
||||
proxy(socket, 'open')
|
||||
proxy(socket, 'close')
|
||||
proxy(socket, 'message', (event) => preprocessor(event, { onAuthenticated }))
|
||||
proxy(socket, 'error')
|
||||
|
||||
// 1000 = Normal Closure
|
||||
eventTarget.close = () => {
|
||||
socket.close(1000, 'Shutting down socket')
|
||||
}
|
||||
eventTarget.getState = () => socket.readyState
|
||||
eventTarget.subscribe = (stream, args = {}) => {
|
||||
console.debug(`[WS][${id}] Subscribing to stream ${stream} with args`, args)
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'subscribe',
|
||||
stream,
|
||||
...args,
|
||||
}),
|
||||
)
|
||||
}
|
||||
eventTarget.unsubscribe = (stream, args = {}) => {
|
||||
console.debug(
|
||||
`[WS][${id}] Unsubscribing from stream ${stream} with args`,
|
||||
args,
|
||||
)
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'unsubscribe',
|
||||
stream,
|
||||
...args,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return eventTarget
|
||||
}
|
||||
|
||||
export const handleMastoWS = (
|
||||
wsEvent,
|
||||
{
|
||||
onAuthenticated = () => {
|
||||
/* no-op */
|
||||
},
|
||||
} = {},
|
||||
) => {
|
||||
const { data } = wsEvent
|
||||
if (!data) return
|
||||
const parsedEvent = JSON.parse(data)
|
||||
const { event, payload } = parsedEvent
|
||||
if (
|
||||
MASTODON_STREAMING_EVENTS.has(event) ||
|
||||
PLEROMA_STREAMING_EVENTS.has(event)
|
||||
) {
|
||||
// MastoBE and PleromaBE both send payload for delete as a PLAIN string
|
||||
if (event === 'delete') {
|
||||
return { event, id: payload }
|
||||
}
|
||||
const data = payload ? JSON.parse(payload) : null
|
||||
if (event === 'pleroma:respond') {
|
||||
if (data.type === 'pleroma:authenticate') {
|
||||
if (data.result === 'success') {
|
||||
console.debug('[WS] Successfully authenticated')
|
||||
onAuthenticated()
|
||||
} else {
|
||||
if (data.error === 'already_authenticated') {
|
||||
onAuthenticated()
|
||||
} else {
|
||||
console.error('[WS] Unable to authenticate:', data.error)
|
||||
wsEvent.target.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
} else if (event === 'update') {
|
||||
return { event, status: parseStatus(data) }
|
||||
} else if (event === 'status.update') {
|
||||
return { event, status: parseStatus(data) }
|
||||
} else if (event === 'notification') {
|
||||
return { event, notification: parseNotification(data) }
|
||||
} else if (event === 'pleroma:chat_update') {
|
||||
return { event, chatUpdate: parseChat(data) }
|
||||
}
|
||||
} else {
|
||||
console.warn('Unknown event', wsEvent)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const WSConnectionStatus = Object.freeze({
|
||||
JOINED: 1,
|
||||
CLOSED: 2,
|
||||
ERROR: 3,
|
||||
DISABLED: 4,
|
||||
STARTING: 5,
|
||||
STARTING_INITIAL: 6,
|
||||
})
|
||||
|
|
@ -23,7 +23,7 @@ import {
|
|||
getOrCreateChat,
|
||||
sendChatMessage,
|
||||
} from 'src/api/chats.js'
|
||||
import { WSConnectionStatus } from 'src/api/public.js'
|
||||
import { WSConnectionStatus } from 'src/api/websocket.js'
|
||||
|
||||
import { library } from '@fortawesome/fontawesome-svg-core'
|
||||
import { faChevronDown, faChevronLeft } from '@fortawesome/free-solid-svg-icons'
|
||||
|
|
|
|||
|
|
@ -10,11 +10,8 @@ import { useInterfaceStore } from 'src/stores/interface'
|
|||
import { useMergedConfigStore } from 'src/stores/merged_config.js'
|
||||
import { useOAuthStore } from 'src/stores/oauth.js'
|
||||
|
||||
import {
|
||||
fetchConversation,
|
||||
fetchStatus,
|
||||
WSConnectionStatus,
|
||||
} from 'src/api/public.js'
|
||||
import { fetchConversation, fetchStatus } from 'src/api/public.js'
|
||||
import { WSConnectionStatus } from 'src/api/websocket.js'
|
||||
|
||||
import { library } from '@fortawesome/fontawesome-svg-core'
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -8,12 +8,12 @@ import { useInterfaceStore } from 'src/stores/interface.js'
|
|||
import { useOAuthStore } from 'src/stores/oauth.js'
|
||||
import { useShoutStore } from 'src/stores/shout.js'
|
||||
|
||||
import { fetchTimeline } from 'src/api/public.js'
|
||||
import {
|
||||
fetchTimeline,
|
||||
getMastodonSocketURI,
|
||||
ProcessedWS,
|
||||
WSConnectionStatus,
|
||||
} from 'src/api/public.js'
|
||||
} from 'src/api/websocket.js'
|
||||
import followRequestFetcher from 'src/services/follow_request_fetcher/follow_request_fetcher.service'
|
||||
import notificationsFetcher from 'src/services/notifications_fetcher/notifications_fetcher.service.js'
|
||||
import timelineFetcher from 'src/services/timeline_fetcher/timeline_fetcher.service.js'
|
||||
|
|
@ -97,9 +97,8 @@ const api = {
|
|||
const { state, commit, dispatch, rootState } = store
|
||||
const timelineData = rootState.statuses.timelines.friends
|
||||
|
||||
const serv = useInstanceStore().server.replace('http', 'ws')
|
||||
const credentials = useOAuthStore().token
|
||||
const url = getMastodonSocketURI({ credentials }, serv)
|
||||
const url = getMastodonSocketURI({ credentials })
|
||||
|
||||
state.mastoUserSocket = ProcessedWS({
|
||||
url,
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ function humanizeErrors(errors) {
|
|||
export function StatusCodeError(statusCode, body, options, response) {
|
||||
this.name = 'StatusCodeError'
|
||||
this.statusCode = statusCode
|
||||
this.statusText = body.error.error || body.error
|
||||
this.statusText = body.error || body
|
||||
this.details = JSON && JSON.stringify ? JSON.stringify(body) : body
|
||||
this.errorData = body.error
|
||||
this.message = this.statusCode + ' - ' + this.statusText
|
||||
|
|
|
|||
|
|
@ -87,22 +87,20 @@ export const useAdminSettingsStore = defineStore('adminSettings', {
|
|||
loadAdminStuff() {
|
||||
getInstanceDBConfig({
|
||||
credentials: useOAuthStore().token,
|
||||
}).then(({ data: backendDbConfig }) => {
|
||||
if (backendDbConfig.error) {
|
||||
if (backendDbConfig.error.status === 400) {
|
||||
backendDbConfig.error.json().then((errorJson) => {
|
||||
if (/configurable_from_database/.test(errorJson.error)) {
|
||||
this.setInstanceAdminNoDbConfig()
|
||||
}
|
||||
})
|
||||
}
|
||||
} else {
|
||||
})
|
||||
.then(({ data: backendDbConfig }) =>
|
||||
this.setInstanceAdminSettings({
|
||||
credentials: useOAuthStore().token,
|
||||
backendDbConfig,
|
||||
})
|
||||
}
|
||||
})
|
||||
}),
|
||||
)
|
||||
.catch(({ statusCode, statusText }) => {
|
||||
if (statusCode === 400) {
|
||||
if (/configurable_from_database/.test(statusText)) {
|
||||
this.setInstanceAdminNoDbConfig()
|
||||
}
|
||||
}
|
||||
})
|
||||
if (this.descriptions === null) {
|
||||
getInstanceConfigDescriptions({
|
||||
credentials: useOAuthStore().token,
|
||||
|
|
|
|||
|
|
@ -27,8 +27,8 @@ export const useBookmarkFoldersStore = defineStore('bookmarkFolders', {
|
|||
},
|
||||
actions: {
|
||||
startFetching() {
|
||||
promiseInterval(() => {
|
||||
this.fetcher = fetchBookmarkFolders({
|
||||
this.fetcher = promiseInterval(() => {
|
||||
fetchBookmarkFolders({
|
||||
credentials: useOAuthStore().token,
|
||||
})
|
||||
.then(({ data: folders }) => this.setBookmarkFolders(folders))
|
||||
|
|
|
|||
|
|
@ -34,8 +34,8 @@ export const useListsStore = defineStore('lists', {
|
|||
},
|
||||
actions: {
|
||||
startFetching() {
|
||||
promiseInterval(() => {
|
||||
this.fetcher = fetchLists({
|
||||
this.fetcher = promiseInterval(() => {
|
||||
fetchLists({
|
||||
credentials: useOAuthStore().token,
|
||||
})
|
||||
.then(({ data: lists }) => this.setLists(lists))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue