aboutsummaryrefslogtreecommitdiff
path: root/src/services/api/api.service.js
diff options
context:
space:
mode:
authortusooa <tusooa@kazv.moe>2023-01-22 09:34:01 -0500
committertusooa <tusooa@kazv.moe>2023-01-22 09:34:01 -0500
commitb1e75c25bd50180e715afde70c6e659e7509a3f3 (patch)
treef5d529d81b4bfa98009e39e7c37d64132d316592 /src/services/api/api.service.js
parent6649baaac94348bbf09015eeb2c8eeea714096db (diff)
parent0d6435261ef3e91c06fe34cc8bf72ff1b30078c2 (diff)
Merge remote-tracking branch 'upstream/develop' into birthdays
Diffstat (limited to 'src/services/api/api.service.js')
-rw-r--r--src/services/api/api.service.js384
1 files changed, 361 insertions, 23 deletions
diff --git a/src/services/api/api.service.js b/src/services/api/api.service.js
index 7b7fbefd..af12265e 100644
--- a/src/services/api/api.service.js
+++ b/src/services/api/api.service.js
@@ -1,5 +1,5 @@
import { each, map, concat, last, get } from 'lodash'
-import { parseStatus, parseUser, parseNotification, parseAttachment, parseChat, parseLinkHeaderPagination } from '../entity_normalizer/entity_normalizer.service.js'
+import { parseStatus, parseSource, parseUser, parseNotification, parseAttachment, parseChat, parseLinkHeaderPagination } from '../entity_normalizer/entity_normalizer.service.js'
import { RegistrationError, StatusCodeError } from '../errors/errors'
/* eslint-env browser */
@@ -49,9 +49,16 @@ const MASTODON_PUBLIC_TIMELINE = '/api/v1/timelines/public'
const MASTODON_USER_HOME_TIMELINE_URL = '/api/v1/timelines/home'
const MASTODON_STATUS_URL = id => `/api/v1/statuses/${id}`
const MASTODON_STATUS_CONTEXT_URL = id => `/api/v1/statuses/${id}/context`
+const MASTODON_STATUS_SOURCE_URL = id => `/api/v1/statuses/${id}/source`
+const MASTODON_STATUS_HISTORY_URL = id => `/api/v1/statuses/${id}/history`
const MASTODON_USER_URL = '/api/v1/accounts'
+const MASTODON_USER_LOOKUP_URL = '/api/v1/accounts/lookup'
const MASTODON_USER_RELATIONSHIPS_URL = '/api/v1/accounts/relationships'
const MASTODON_USER_TIMELINE_URL = id => `/api/v1/accounts/${id}/statuses`
+const MASTODON_USER_IN_LISTS = id => `/api/v1/accounts/${id}/lists`
+const MASTODON_LIST_URL = id => `/api/v1/lists/${id}`
+const MASTODON_LIST_TIMELINE_URL = id => `/api/v1/timelines/list/${id}`
+const MASTODON_LIST_ACCOUNTS_URL = id => `/api/v1/lists/${id}/accounts`
const MASTODON_TAG_TIMELINE_URL = tag => `/api/v1/timelines/tag/${tag}`
const MASTODON_BOOKMARK_TIMELINE_URL = '/api/v1/bookmarks'
const MASTODON_USER_BLOCKS_URL = '/api/v1/blocks/'
@@ -60,8 +67,10 @@ const MASTODON_BLOCK_USER_URL = id => `/api/v1/accounts/${id}/block`
const MASTODON_UNBLOCK_USER_URL = id => `/api/v1/accounts/${id}/unblock`
const MASTODON_MUTE_USER_URL = id => `/api/v1/accounts/${id}/mute`
const MASTODON_UNMUTE_USER_URL = id => `/api/v1/accounts/${id}/unmute`
+const MASTODON_REMOVE_USER_FROM_FOLLOWERS = id => `/api/v1/accounts/${id}/remove_from_followers`
const MASTODON_SUBSCRIBE_USER = id => `/api/v1/pleroma/accounts/${id}/subscribe`
const MASTODON_UNSUBSCRIBE_USER = id => `/api/v1/pleroma/accounts/${id}/unsubscribe`
+const MASTODON_USER_NOTE_URL = id => `/api/v1/accounts/${id}/note`
const MASTODON_BOOKMARK_STATUS_URL = id => `/api/v1/statuses/${id}/bookmark`
const MASTODON_UNBOOKMARK_STATUS_URL = id => `/api/v1/statuses/${id}/unbookmark`
const MASTODON_POST_STATUS_URL = '/api/v1/statuses'
@@ -79,8 +88,11 @@ const MASTODON_UNMUTE_CONVERSATION = id => `/api/v1/statuses/${id}/unmute`
const MASTODON_SEARCH_2 = '/api/v2/search'
const MASTODON_USER_SEARCH_URL = '/api/v1/accounts/search'
const MASTODON_DOMAIN_BLOCKS_URL = '/api/v1/domain_blocks'
+const MASTODON_LISTS_URL = '/api/v1/lists'
const MASTODON_STREAMING = '/api/v1/streaming'
const MASTODON_KNOWN_DOMAIN_LIST_URL = '/api/v1/instance/peers'
+const MASTODON_ANNOUNCEMENTS_URL = '/api/v1/announcements'
+const MASTODON_ANNOUNCEMENTS_DISMISS_URL = id => `/api/v1/announcements/${id}/dismiss`
const PLEROMA_EMOJI_REACTIONS_URL = id => `/api/v1/pleroma/statuses/${id}/reactions`
const PLEROMA_EMOJI_REACT_URL = (id, emoji) => `/api/v1/pleroma/statuses/${id}/reactions/${emoji}`
const PLEROMA_EMOJI_UNREACT_URL = (id, emoji) => `/api/v1/pleroma/statuses/${id}/reactions/${emoji}`
@@ -89,7 +101,12 @@ const PLEROMA_CHAT_URL = id => `/api/v1/pleroma/chats/by-account-id/${id}`
const PLEROMA_CHAT_MESSAGES_URL = id => `/api/v1/pleroma/chats/${id}/messages`
const PLEROMA_CHAT_READ_URL = id => `/api/v1/pleroma/chats/${id}/read`
const PLEROMA_DELETE_CHAT_MESSAGE_URL = (chatId, messageId) => `/api/v1/pleroma/chats/${chatId}/messages/${messageId}`
+const PLEROMA_ADMIN_REPORTS = '/api/pleroma/admin/reports'
const PLEROMA_BACKUP_URL = '/api/v1/pleroma/backups'
+const PLEROMA_ANNOUNCEMENTS_URL = '/api/v1/pleroma/admin/announcements'
+const PLEROMA_POST_ANNOUNCEMENT_URL = '/api/v1/pleroma/admin/announcements'
+const PLEROMA_EDIT_ANNOUNCEMENT_URL = id => `/api/v1/pleroma/admin/announcements/${id}`
+const PLEROMA_DELETE_ANNOUNCEMENT_URL = id => `/api/v1/pleroma/admin/announcements/${id}`
const oldfetch = window.fetch
@@ -147,7 +164,7 @@ const updateNotificationSettings = ({ credentials, settings }) => {
form.append(key, value)
})
- return fetch(NOTIFICATION_SETTINGS_URL, {
+ return fetch(`${NOTIFICATION_SETTINGS_URL}?${new URLSearchParams(settings)}`, {
headers: authHeaders(credentials),
method: 'PUT',
body: form
@@ -257,6 +274,13 @@ const unfollowUser = ({ id, credentials }) => {
}).then((data) => data.json())
}
+const fetchUserInLists = ({ id, credentials }) => {
+ const url = MASTODON_USER_IN_LISTS(id)
+ return fetch(url, {
+ headers: authHeaders(credentials)
+ }).then((data) => data.json())
+}
+
const pinOwnStatus = ({ id, credentials }) => {
return promisedRequest({ url: MASTODON_PIN_OWN_STATUS(id), credentials, method: 'POST' })
.then((data) => parseStatus(data))
@@ -291,6 +315,24 @@ const unblockUser = ({ id, credentials }) => {
}).then((data) => data.json())
}
+const removeUserFromFollowers = ({ id, credentials }) => {
+ return fetch(MASTODON_REMOVE_USER_FROM_FOLLOWERS(id), {
+ headers: authHeaders(credentials),
+ method: 'POST'
+ }).then((data) => data.json())
+}
+
+const editUserNote = ({ id, credentials, comment }) => {
+ return promisedRequest({
+ url: MASTODON_USER_NOTE_URL(id),
+ credentials,
+ payload: {
+ comment
+ },
+ method: 'POST'
+ })
+}
+
const approveUser = ({ id, credentials }) => {
const url = MASTODON_APPROVE_USER_URL(id)
return fetch(url, {
@@ -313,6 +355,25 @@ const fetchUser = ({ id, credentials }) => {
.then((data) => parseUser(data))
}
+const fetchUserByName = ({ name, credentials }) => {
+ return promisedRequest({
+ url: MASTODON_USER_LOOKUP_URL,
+ credentials,
+ params: { acct: name }
+ })
+ .then(data => data.id)
+ .catch(error => {
+ if (error && error.statusCode === 404) {
+ // Either the backend does not support lookup endpoint,
+ // or there is no user with such name. Fallback and treat name as id.
+ return name
+ } else {
+ throw error
+ }
+ })
+ .then(id => fetchUser({ id, credentials }))
+}
+
const fetchUserRelationship = ({ id, credentials }) => {
const url = `${MASTODON_USER_RELATIONSHIPS_URL}/?id=${id}`
return fetch(url, { headers: authHeaders(credentials) })
@@ -385,6 +446,81 @@ const fetchFollowRequests = ({ credentials }) => {
.then((data) => data.map(parseUser))
}
+const fetchLists = ({ credentials }) => {
+ const url = MASTODON_LISTS_URL
+ return fetch(url, { headers: authHeaders(credentials) })
+ .then((data) => data.json())
+}
+
+const createList = ({ title, credentials }) => {
+ const url = MASTODON_LISTS_URL
+ const headers = authHeaders(credentials)
+ headers['Content-Type'] = 'application/json'
+
+ return fetch(url, {
+ headers,
+ method: 'POST',
+ body: JSON.stringify({ title })
+ }).then((data) => data.json())
+}
+
+const getList = ({ listId, credentials }) => {
+ const url = MASTODON_LIST_URL(listId)
+ return fetch(url, { headers: authHeaders(credentials) })
+ .then((data) => data.json())
+}
+
+const updateList = ({ listId, title, credentials }) => {
+ const url = MASTODON_LIST_URL(listId)
+ const headers = authHeaders(credentials)
+ headers['Content-Type'] = 'application/json'
+
+ return fetch(url, {
+ headers,
+ method: 'PUT',
+ body: JSON.stringify({ title })
+ })
+}
+
+const getListAccounts = ({ listId, credentials }) => {
+ const url = MASTODON_LIST_ACCOUNTS_URL(listId)
+ return fetch(url, { headers: authHeaders(credentials) })
+ .then((data) => data.json())
+ .then((data) => data.map(({ id }) => id))
+}
+
+const addAccountsToList = ({ listId, accountIds, credentials }) => {
+ const url = MASTODON_LIST_ACCOUNTS_URL(listId)
+ const headers = authHeaders(credentials)
+ headers['Content-Type'] = 'application/json'
+
+ return fetch(url, {
+ headers,
+ method: 'POST',
+ body: JSON.stringify({ account_ids: accountIds })
+ })
+}
+
+const removeAccountsFromList = ({ listId, accountIds, credentials }) => {
+ const url = MASTODON_LIST_ACCOUNTS_URL(listId)
+ const headers = authHeaders(credentials)
+ headers['Content-Type'] = 'application/json'
+
+ return fetch(url, {
+ headers,
+ method: 'DELETE',
+ body: JSON.stringify({ account_ids: accountIds })
+ })
+}
+
+const deleteList = ({ listId, credentials }) => {
+ const url = MASTODON_LIST_URL(listId)
+ return fetch(url, {
+ method: 'DELETE',
+ headers: authHeaders(credentials)
+ })
+}
+
const fetchConversation = ({ id, credentials }) => {
const urlContext = MASTODON_STATUS_CONTEXT_URL(id)
return fetch(urlContext, { headers: authHeaders(credentials) })
@@ -414,6 +550,31 @@ const fetchStatus = ({ id, credentials }) => {
.then((data) => parseStatus(data))
}
+const fetchStatusSource = ({ id, credentials }) => {
+ const url = MASTODON_STATUS_SOURCE_URL(id)
+ return fetch(url, { headers: authHeaders(credentials) })
+ .then((data) => {
+ if (data.ok) {
+ return data
+ }
+ throw new Error('Error fetching source', data)
+ })
+ .then((data) => data.json())
+ .then((data) => parseSource(data))
+}
+
+const fetchStatusHistory = ({ status, credentials }) => {
+ const url = MASTODON_STATUS_HISTORY_URL(status.id)
+ return promisedRequest({ url, credentials })
+ .then((data) => {
+ data.reverse()
+ return data.map((item) => {
+ item.originalStatus = status
+ return parseStatus(item)
+ })
+ })
+}
+
const tagUser = ({ tag, credentials, user }) => {
const screenName = user.screen_name
const form = {
@@ -506,9 +667,11 @@ const fetchTimeline = ({
since = false,
until = false,
userId = false,
+ listId = false,
tag = false,
withMuted = false,
- replyVisibility = 'all'
+ replyVisibility = 'all',
+ includeTypes = []
}) => {
const timelineUrls = {
public: MASTODON_PUBLIC_TIMELINE,
@@ -518,6 +681,7 @@ const fetchTimeline = ({
publicAndExternal: MASTODON_PUBLIC_TIMELINE,
user: MASTODON_USER_TIMELINE_URL,
media: MASTODON_USER_TIMELINE_URL,
+ list: MASTODON_LIST_TIMELINE_URL,
favorites: MASTODON_USER_FAVORITES_TIMELINE_URL,
tag: MASTODON_TAG_TIMELINE_URL,
bookmarks: MASTODON_BOOKMARK_TIMELINE_URL
@@ -531,6 +695,10 @@ const fetchTimeline = ({
url = url(userId)
}
+ if (timeline === 'list') {
+ url = url(listId)
+ }
+
if (since) {
params.push(['since_id', since])
}
@@ -555,32 +723,33 @@ const fetchTimeline = ({
if (replyVisibility !== 'all') {
params.push(['reply_visibility', replyVisibility])
}
+ if (includeTypes.length > 0) {
+ includeTypes.forEach(type => {
+ params.push(['include_types[]', type])
+ })
+ }
params.push(['limit', 20])
const queryString = map(params, (param) => `${param[0]}=${param[1]}`).join('&')
url += `?${queryString}`
- let status = ''
- let statusText = ''
-
- let pagination = {}
return fetch(url, { headers: authHeaders(credentials) })
- .then((data) => {
- status = data.status
- statusText = data.statusText
- pagination = parseLinkHeaderPagination(data.headers.get('Link'), {
- flakeId: timeline !== 'bookmarks' && timeline !== 'notifications'
- })
- return data
- })
- .then((data) => data.json())
- .then((data) => {
- if (!data.errors) {
+ .then(async (response) => {
+ const success = response.ok
+
+ const data = await response.json()
+
+ if (success && !data.errors) {
+ const pagination = parseLinkHeaderPagination(response.headers.get('Link'), {
+ flakeId: timeline !== 'bookmarks' && timeline !== 'notifications'
+ })
+
return { data: data.map(isNotifications ? parseNotification : parseStatus), pagination }
} else {
- data.status = status
- data.statusText = statusText
+ data.errors ||= []
+ data.status = response.status
+ data.statusText = response.statusText
return data
}
})
@@ -705,6 +874,54 @@ const postStatus = ({
.then((data) => data.error ? data : parseStatus(data))
}
+const editStatus = ({
+ id,
+ credentials,
+ status,
+ spoilerText,
+ sensitive,
+ poll,
+ mediaIds = [],
+ contentType
+}) => {
+ const form = new FormData()
+ const pollOptions = poll.options || []
+
+ form.append('status', status)
+ if (spoilerText) form.append('spoiler_text', spoilerText)
+ if (sensitive) form.append('sensitive', sensitive)
+ if (contentType) form.append('content_type', contentType)
+ mediaIds.forEach(val => {
+ form.append('media_ids[]', val)
+ })
+
+ if (pollOptions.some(option => option !== '')) {
+ const normalizedPoll = {
+ expires_in: poll.expiresIn,
+ multiple: poll.multiple
+ }
+ Object.keys(normalizedPoll).forEach(key => {
+ form.append(`poll[${key}]`, normalizedPoll[key])
+ })
+
+ pollOptions.forEach(option => {
+ form.append('poll[options][]', option)
+ })
+ }
+
+ const putHeaders = authHeaders(credentials)
+
+ return fetch(MASTODON_STATUS_URL(id), {
+ body: form,
+ method: 'PUT',
+ headers: putHeaders
+ })
+ .then((response) => {
+ return response.json()
+ })
+ .then((data) => data.error ? data : parseStatus(data))
+}
+
const deleteStatus = ({ id, credentials }) => {
return fetch(MASTODON_DELETE_URL(id), {
headers: authHeaders(credentials),
@@ -1075,7 +1292,7 @@ const searchUsers = ({ credentials, query }) => {
.then((data) => data.map(parseUser))
}
-const search2 = ({ credentials, q, resolve, limit, offset, following }) => {
+const search2 = ({ credentials, q, resolve, limit, offset, following, type }) => {
let url = MASTODON_SEARCH_2
const params = []
@@ -1099,6 +1316,10 @@ const search2 = ({ credentials, q, resolve, limit, offset, following }) => {
params.push(['following', true])
}
+ if (type) {
+ params.push(['following', type])
+ }
+
params.push(['with_relationships', true])
const queryString = map(params, (param) => `${param[0]}=${param[1]}`).join('&')
@@ -1154,6 +1375,66 @@ const dismissNotification = ({ credentials, id }) => {
})
}
+const adminFetchAnnouncements = ({ credentials }) => {
+ return promisedRequest({ url: PLEROMA_ANNOUNCEMENTS_URL, credentials })
+}
+
+const fetchAnnouncements = ({ credentials }) => {
+ return promisedRequest({ url: MASTODON_ANNOUNCEMENTS_URL, credentials })
+}
+
+const dismissAnnouncement = ({ id, credentials }) => {
+ return promisedRequest({
+ url: MASTODON_ANNOUNCEMENTS_DISMISS_URL(id),
+ credentials,
+ method: 'POST'
+ })
+}
+
+const announcementToPayload = ({ content, startsAt, endsAt, allDay }) => {
+ const payload = { content }
+
+ if (typeof startsAt !== 'undefined') {
+ payload.starts_at = startsAt ? new Date(startsAt).toISOString() : null
+ }
+
+ if (typeof endsAt !== 'undefined') {
+ payload.ends_at = endsAt ? new Date(endsAt).toISOString() : null
+ }
+
+ if (typeof allDay !== 'undefined') {
+ payload.all_day = allDay
+ }
+
+ return payload
+}
+
+const postAnnouncement = ({ credentials, content, startsAt, endsAt, allDay }) => {
+ return promisedRequest({
+ url: PLEROMA_POST_ANNOUNCEMENT_URL,
+ credentials,
+ method: 'POST',
+ payload: announcementToPayload({ content, startsAt, endsAt, allDay })
+ })
+}
+
+const editAnnouncement = ({ id, credentials, content, startsAt, endsAt, allDay }) => {
+ return promisedRequest({
+ url: PLEROMA_EDIT_ANNOUNCEMENT_URL(id),
+ credentials,
+ method: 'PATCH',
+ payload: announcementToPayload({ content, startsAt, endsAt, allDay })
+ })
+}
+
+const deleteAnnouncement = ({ id, credentials }) => {
+ return promisedRequest({
+ url: PLEROMA_DELETE_ANNOUNCEMENT_URL(id),
+ credentials,
+ method: 'DELETE'
+ })
+}
+
export const getMastodonSocketURI = ({ credentials, stream, args = {} }) => {
return Object.entries({
...(credentials
@@ -1171,7 +1452,8 @@ const MASTODON_STREAMING_EVENTS = new Set([
'update',
'notification',
'delete',
- 'filters_changed'
+ 'filters_changed',
+ 'status.update'
])
const PLEROMA_STREAMING_EVENTS = new Set([
@@ -1243,6 +1525,8 @@ export const handleMastoWS = (wsEvent) => {
const data = payload ? JSON.parse(payload) : null
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') {
@@ -1339,12 +1623,46 @@ const deleteChatMessage = ({ chatId, messageId, credentials }) => {
})
}
+const setReportState = ({ id, state, credentials }) => {
+ // TODO: Can't use promisedRequest because on OK this does not return json
+ // See https://git.pleroma.social/pleroma/pleroma-fe/-/merge_requests/1322
+ return fetch(PLEROMA_ADMIN_REPORTS, {
+ headers: {
+ ...authHeaders(credentials),
+ Accept: 'application/json',
+ 'Content-Type': 'application/json'
+ },
+ method: 'PATCH',
+ body: JSON.stringify({
+ reports: [{
+ id,
+ state
+ }]
+ })
+ })
+ .then(data => {
+ if (data.status >= 500) {
+ throw Error(data.statusText)
+ } else if (data.status >= 400) {
+ return data.json()
+ }
+ return data
+ })
+ .then(data => {
+ if (data.errors) {
+ throw Error(data.errors[0].message)
+ }
+ })
+}
+
const apiService = {
verifyCredentials,
fetchTimeline,
fetchPinnedStatuses,
fetchConversation,
fetchStatus,
+ fetchStatusSource,
+ fetchStatusHistory,
fetchFriends,
exportFriends,
fetchFollowers,
@@ -1356,7 +1674,10 @@ const apiService = {
unmuteConversation,
blockUser,
unblockUser,
+ removeUserFromFollowers,
+ editUserNote,
fetchUser,
+ fetchUserByName,
fetchUserRelationship,
favorite,
unfavorite,
@@ -1365,6 +1686,7 @@ const apiService = {
bookmarkStatus,
unbookmarkStatus,
postStatus,
+ editStatus,
deleteStatus,
uploadMedia,
setMediaDescription,
@@ -1405,6 +1727,14 @@ const apiService = {
addBackup,
listBackups,
fetchFollowRequests,
+ fetchLists,
+ createList,
+ getList,
+ updateList,
+ getListAccounts,
+ addAccountsToList,
+ removeAccountsFromList,
+ deleteList,
approveUser,
denyUser,
suggestions,
@@ -1430,7 +1760,15 @@ const apiService = {
chatMessages,
sendChatMessage,
readChat,
- deleteChatMessage
+ deleteChatMessage,
+ setReportState,
+ fetchUserInLists,
+ fetchAnnouncements,
+ dismissAnnouncement,
+ postAnnouncement,
+ editAnnouncement,
+ deleteAnnouncement,
+ adminFetchAnnouncements
}
export default apiService