diff --git a/src/lib/api/client.svelte.ts b/src/lib/api/client.svelte.ts index db9f26ce..aac1688b 100644 --- a/src/lib/api/client.svelte.ts +++ b/src/lib/api/client.svelte.ts @@ -1,4 +1,4 @@ -import { profile } from '$lib/app/auth.svelte' +import { profile } from '$lib/app/auth' import { DEFAULT_INSTANCE_URL } from '$lib/app/instance.svelte' import { instanceToURL } from '$lib/app/util.svelte' import { error } from '@sveltejs/kit' @@ -80,13 +80,11 @@ export function client({ // but not here, so that if jwt == '', it doesnt put a bearer const headers = jwt ? { authorization: `Bearer ${jwt}` } : {} - return new (clientType.name == 'piefed' ? PiefedClient : LemmyClient)( - instanceToURL(instanceURL), - { - fetchFunction: (input, init) => customFetch(func, input, init, jwt), - headers: headers, - }, - ) + const Client = clientType.name == 'piefed' ? PiefedClient : LemmyClient + return new Client(instanceToURL(instanceURL), { + fetchFunction: (input, init) => customFetch(func, input, init, jwt), + headers: headers, + }) as unknown as BaseClient } // here for parts where i forgor to switch diff --git a/src/lib/api/lemmy/adapter.ts b/src/lib/api/lemmy/adapter.ts index 4139f806..172b3967 100644 --- a/src/lib/api/lemmy/adapter.ts +++ b/src/lib/api/lemmy/adapter.ts @@ -2,12 +2,68 @@ import { LemmyHttp } from 'lemmy-js-client' import type { BaseClient, ClientType } from '../base' import { fromGetPosts, toListingType } from './rewrite' -export class LemmyClient implements BaseClient { - type: ClientType = { name: 'lemmy', baseUrl: '/api/v3' } +export const LemmyClientConstants = { + password: { minLength: 8, maxLength: 60 }, +} - static constants = { password: { minLength: 8, maxLength: 60 } } +export function createLemmyClient( + baseUrl: string, + args: { + fetchFunction: (input: any, init: any) => Promise + headers: any + }, +): BaseClient { + const client = new LemmyHttp(baseUrl, args) - #client: LemmyHttp + const overrides: Partial = { + type: { name: 'lemmy', baseUrl: '/api/v3' } as ClientType, + + async search(params) { + return await client.search({ + ...params, + listing_type: toListingType(params.listing_type), + } as any) + }, + + async listCommunities(params) { + return await client.listCommunities({ + ...params, + type_: toListingType(params.type_), + } as any) + }, + + async getPosts(params) { + return (await client.getPosts(fromGetPosts(params) as any)) as any + }, + + async getComments(params) { + return await client.getComments({ + ...params, + type_: toListingType(params.type_), + } as any) + }, + } + + return new Proxy(overrides as BaseClient, { + get: (target, prop, receiver) => { + const value = Reflect.get(target, prop, receiver) + if (value !== undefined) { + return value + } + + const clientValue = (client as any)[prop] + if (typeof clientValue === 'function') { + return clientValue.bind(client) + } + return clientValue + }, + }) +} + +export class LemmyClient { + static constants = LemmyClientConstants + + #proxy: BaseClient constructor( baseUrl: string, @@ -16,481 +72,13 @@ export class LemmyClient implements BaseClient { headers: any }, ) { - this.#client = new LemmyHttp(baseUrl, args) - } + this.#proxy = createLemmyClient(baseUrl, args) - async getSite( - ...params: Parameters - ): ReturnType { - return await this.#client.getSite(...params) - } - async generateTotpSecret( - ...params: Parameters - ): ReturnType { - return await this.#client.generateTotpSecret(...params) - } - async listLogins( - ...params: Parameters - ): ReturnType { - return await this.#client.listLogins(...params) - } - async listAllMedia( - ...params: Parameters - ): ReturnType { - return await this.#client.listAllMedia(...params) - } - async updateTotp( - ...params: Parameters - ): ReturnType { - return await this.#client.updateTotp(...params) - } - async getModlog( - ...params: Parameters - ): ReturnType { - return await this.#client.getModlog(...params) - } - async search( - params: Parameters[0], - ): ReturnType { - return await this.#client.search({ - ...params, - listing_type: toListingType(params.listing_type), - }) - } - async resolveObject( - ...params: Parameters - ): ReturnType { - return await this.#client.resolveObject(...params) - } - async createCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.createCommunity(...params) - } - async getCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.getCommunity(...params) - } - async editCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.editCommunity(...params) - } - async listCommunities( - params: Parameters[0], - ): ReturnType { - return await this.#client.listCommunities({ - ...params, - type_: toListingType(params.type_), - }) - } - async followCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.followCommunity(...params) - } - async blockCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.blockCommunity(...params) - } - async deleteCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.deleteCommunity(...params) - } - async hideCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.hideCommunity(...params) - } - async removeCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.removeCommunity(...params) - } - async banFromCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.banFromCommunity(...params) - } - async addModToCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.addModToCommunity(...params) - } - async createPost( - ...params: Parameters - ): ReturnType { - return await this.#client.createPost(...params) - } - async getPost( - ...params: Parameters - ): ReturnType { - return await this.#client.getPost(...params) - } - async editPost( - ...params: Parameters - ): ReturnType { - return await this.#client.editPost(...params) - } - async deletePost( - ...params: Parameters - ): ReturnType { - return await this.#client.deletePost(...params) - } - async removePost( - ...params: Parameters - ): ReturnType { - return await this.#client.removePost(...params) - } - async markPostAsRead( - ...params: Parameters - ): ReturnType { - return await this.#client.markPostAsRead(...params) - } - async hidePost( - ...params: Parameters - ): ReturnType { - return await this.#client.hidePost(...params) - } - async lockPost( - ...params: Parameters - ): ReturnType { - return await this.#client.lockPost(...params) - } - async featurePost( - ...params: Parameters - ): ReturnType { - return await this.#client.featurePost(...params) - } - async getPosts( - params: Parameters[0], - ): ReturnType { - return await this.#client.getPosts(fromGetPosts(params)) - } - async likePost( - ...params: Parameters - ): ReturnType { - return await this.#client.likePost(...params) - } - async listPostLikes( - ...params: Parameters - ): ReturnType { - return await this.#client.listPostLikes(...params) - } - async savePost( - ...params: Parameters - ): ReturnType { - return await this.#client.savePost(...params) - } - async createPostReport( - ...params: Parameters - ): ReturnType { - return await this.#client.createPostReport(...params) - } - async resolvePostReport( - ...params: Parameters - ): ReturnType { - return await this.#client.resolvePostReport(...params) - } - async listPostReports( - ...params: Parameters - ): ReturnType { - return await this.#client.listPostReports(...params) - } - async getSiteMetadata( - ...params: Parameters - ): ReturnType { - return await this.#client.getSiteMetadata(...params) - } - async createComment( - ...params: Parameters - ): ReturnType { - return await this.#client.createComment(...params) - } - async editComment( - ...params: Parameters - ): ReturnType { - return await this.#client.editComment(...params) - } - async deleteComment( - ...params: Parameters - ): ReturnType { - return await this.#client.deleteComment(...params) - } - async removeComment( - ...params: Parameters - ): ReturnType { - return await this.#client.removeComment(...params) - } - async markCommentReplyAsRead( - ...params: Parameters - ): ReturnType { - return await this.#client.markCommentReplyAsRead(...params) - } - async likeComment( - ...params: Parameters - ): ReturnType { - return await this.#client.likeComment(...params) - } - async listCommentLikes( - ...params: Parameters - ): ReturnType { - return await this.#client.listCommentLikes(...params) - } - async saveComment( - ...params: Parameters - ): ReturnType { - return await this.#client.saveComment(...params) - } - async distinguishComment( - ...params: Parameters - ): ReturnType { - return await this.#client.distinguishComment(...params) - } - async getComments( - params: Parameters[0], - ): ReturnType { - return await this.#client.getComments({ - ...params, - type_: toListingType(params.type_), - }) - } - async getComment( - ...params: Parameters - ): ReturnType { - return await this.#client.getComment(...params) - } - async createCommentReport( - ...params: Parameters - ): ReturnType { - return await this.#client.createCommentReport(...params) - } - async resolveCommentReport( - ...params: Parameters - ): ReturnType { - return await this.#client.resolveCommentReport(...params) - } - async listCommentReports( - ...params: Parameters - ): ReturnType { - return await this.#client.listCommentReports(...params) - } - async getPrivateMessages( - ...params: Parameters - ): ReturnType { - return await this.#client.getPrivateMessages(...params) - } - async createPrivateMessage( - ...params: Parameters - ): ReturnType { - return await this.#client.createPrivateMessage(...params) - } - async editPrivateMessage( - ...params: Parameters - ): ReturnType { - return await this.#client.editPrivateMessage(...params) - } - async deletePrivateMessage( - ...params: Parameters - ): ReturnType { - return await this.#client.deletePrivateMessage(...params) - } - async markPrivateMessageAsRead( - ...params: Parameters - ): ReturnType { - return await this.#client.markPrivateMessageAsRead(...params) - } - async createPrivateMessageReport( - ...params: Parameters - ): ReturnType { - return await this.#client.createPrivateMessageReport(...params) - } - async resolvePrivateMessageReport( - ...params: Parameters - ): ReturnType { - return await this.#client.resolvePrivateMessageReport(...params) - } - async listPrivateMessageReports( - ...params: Parameters - ): ReturnType { - return await this.#client.listPrivateMessageReports(...params) - } - async register( - ...params: Parameters - ): ReturnType { - return await this.#client.register(...params) - } - async login( - ...params: Parameters - ): ReturnType { - return await this.#client.login(...params) - } - async logout( - ...params: Parameters - ): ReturnType { - return await this.#client.logout(...params) - } - async getPersonDetails( - ...params: Parameters - ): ReturnType { - return await this.#client.getPersonDetails(...params) - } - async getPersonMentions( - ...params: Parameters - ): ReturnType { - return await this.#client.getPersonMentions(...params) - } - async markPersonMentionAsRead( - ...params: Parameters - ): ReturnType { - return await this.#client.markPersonMentionAsRead(...params) - } - async getReplies( - ...params: Parameters - ): ReturnType { - return await this.#client.getReplies(...params) - } - async banPerson( - ...params: Parameters - ): ReturnType { - return await this.#client.banPerson(...params) - } - async getBannedPersons( - ...params: Parameters - ): ReturnType { - return await this.#client.getBannedPersons(...params) - } - async blockPerson( - ...params: Parameters - ): ReturnType { - return await this.#client.blockPerson(...params) - } - async getCaptcha( - ...params: Parameters - ): ReturnType { - return await this.#client.getCaptcha(...params) - } - async deleteAccount( - ...params: Parameters - ): ReturnType { - return await this.#client.deleteAccount(...params) - } - async passwordReset( - ...params: Parameters - ): ReturnType { - return await this.#client.passwordReset(...params) - } - async passwordChangeAfterReset( - ...params: Parameters - ): ReturnType { - return await this.#client.passwordChangeAfterReset(...params) - } - async markAllAsRead( - ...params: Parameters - ): ReturnType { - return await this.#client.markAllAsRead(...params) - } - async saveUserSettings( - ...params: Parameters - ): ReturnType { - return await this.#client.saveUserSettings(...params) - } - async changePassword( - ...params: Parameters - ): ReturnType { - return await this.#client.changePassword(...params) - } - async getReportCount( - ...params: Parameters - ): ReturnType { - return await this.#client.getReportCount(...params) - } - async getUnreadCount( - ...params: Parameters - ): ReturnType { - return await this.#client.getUnreadCount(...params) - } - async verifyEmail( - ...params: Parameters - ): ReturnType { - return await this.#client.verifyEmail(...params) - } - async addAdmin( - ...params: Parameters - ): ReturnType { - return await this.#client.addAdmin(...params) - } - async getUnreadRegistrationApplicationCount( - ...params: Parameters - ): ReturnType { - return await this.#client.getUnreadRegistrationApplicationCount(...params) - } - async listRegistrationApplications( - ...params: Parameters - ): ReturnType { - return await this.#client.listRegistrationApplications(...params) - } - async approveRegistrationApplication( - ...params: Parameters - ): ReturnType { - return await this.#client.approveRegistrationApplication(...params) - } - async getRegistrationApplication( - ...params: Parameters - ): ReturnType { - return await this.#client.getRegistrationApplication(...params) - } - async purgePerson( - ...params: Parameters - ): ReturnType { - return await this.#client.purgePerson(...params) - } - async purgeCommunity( - ...params: Parameters - ): ReturnType { - return await this.#client.purgeCommunity(...params) - } - async purgePost( - ...params: Parameters - ): ReturnType { - return await this.#client.purgePost(...params) - } - async purgeComment( - ...params: Parameters - ): ReturnType { - return await this.#client.purgeComment(...params) - } - async getFederatedInstances( - ...params: Parameters - ): ReturnType { - return await this.#client.getFederatedInstances(...params) - } - async blockInstance( - ...params: Parameters - ): ReturnType { - return await this.#client.blockInstance(...params) - } - async uploadImage( - ...params: Parameters - ): ReturnType { - return await this.#client.uploadImage(...params) - } - async editSite( - ...params: Parameters - ): ReturnType { - return await this.#client.editSite(...params) - } - async deleteImage( - ...params: Parameters - ): ReturnType { - return await this.#client.deleteImage(...params) - } - async listMedia( - ...params: Parameters - ): ReturnType { - return await this.#client.listMedia(...params) + return new Proxy(this, { + get: (target, prop) => { + if (prop === 'constructor') return LemmyClient + return (target.#proxy as any)[prop] + }, + }) as any } } diff --git a/src/lib/api/piefed/adapter.ts b/src/lib/api/piefed/adapter.ts index dfac8e05..f47c3f99 100644 --- a/src/lib/api/piefed/adapter.ts +++ b/src/lib/api/piefed/adapter.ts @@ -1,11 +1,6 @@ import createClient from 'openapi-fetch' -import { - BaseClient, - type ClientType, - type NullableFnArg, - type NullableFnReturn, -} from '../base' -import type { SubscribedType } from '../types' +import type { BaseClient, ClientType } from '../base' +import type * as types from '../types' import { fromCreateComment, fromCreatePost, @@ -33,52 +28,93 @@ import { toSortType, toTopicView, } from './rewrite' -import type { paths } from './schema' +import type { components, paths } from './schema' -export class PiefedClient implements BaseClient { - type: ClientType = { name: 'piefed', baseUrl: '/api/alpha' } +type piefed = components['schemas'] - static constants = { password: { minLength: 6, maxLength: 128 } } +type ApiClient = ReturnType> +type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' - #client: ReturnType> +// i think this should be inside baseclient maybe +type MethodName = NonNullable< + { + [K in keyof BaseClient]: BaseClient[K] extends (...args: any[]) => any + ? K + : never + }[keyof BaseClient] +> - constructor( - baseUrl: string, - args: { - fetchFunction: (input: any, init: any) => Promise - headers: any - }, - ) { - this.#client = createClient({ - baseUrl: baseUrl, - // @ts-expect-error i dont feel like fixing this right now - fetch: args.fetchFunction, - headers: args.headers, - }) +type MethodConfig< + K extends MethodName, + P extends keyof paths = keyof paths, + M extends HttpMethod = 'GET', +> = { + method: HttpMethod + path: keyof paths + query?: (params: Parameters[0]) => unknown + body?: (params: Parameters[0]) => unknown + transform: ( + response: SuccessResponse, + params: Parameters[0], + ) => Awaited> +} + +type MethodDef = + | MethodConfig + | ((client: ApiClient, params: any) => Promise) + | 'unsupported' + +type MethodDefinitions = { + [K in MethodName]: MethodDef +} + +type SuccessResponse< + P extends keyof paths, + M extends HttpMethod, +> = paths[P] extends { + [K in M]: { responses: { 200: { content: { 'application/json': infer R } } } } +} + ? R + : paths[P] extends { + [K in M]: { + responses: { 201: { content: { 'application/json': infer R } } } + } + } + ? R + : never + +function assertData(response: { data?: T; error?: unknown }): T { + if (response.error || !response.data) { + throw new Error( + `API error: ${JSON.stringify(response.error ?? 'No data returned')}`, + ) } + return response.data +} - async getSite(): ReturnType { - const response = (await this.#client.GET('/api/alpha/site', {})).data! - - return { - admins: response.admins.map(toPersonView), +const methods: MethodDefinitions = { + getSite: { + method: 'GET', + path: '/api/alpha/site', + transform: (r: piefed['GetSiteResponse']) => ({ + admins: r.admins.map(toPersonView), site_view: { counts: { comments: -1, communities: -1, posts: -1, site_id: -1, - users: response.site.user_count ?? -1, + users: r.site.user_count ?? -1, users_active_day: -1, users_active_half_year: -1, users_active_month: -1, users_active_week: -1, }, - local_site: toLocalSite(response.site), - site: response.site, + local_site: toLocalSite(r.site), + site: r.site, }, all_languages: - (response.site.all_languages as { + (r.site.all_languages as { code: string id: number name: string @@ -87,963 +123,767 @@ export class PiefedClient implements BaseClient { custom_emojis: [], discussion_languages: [], taglines: [], - version: response.version, - my_user: response.my_user ? toMyUser(response.my_user) : undefined, - } - } + version: r.version, + my_user: r.my_user ? toMyUser(r.my_user) : undefined, + }), + }, - async createPost( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/post', { - body: fromCreatePost(params), - }) - ).data! + getSiteMetadata: { + method: 'GET', + path: '/api/alpha/post/site_metadata', + query: (p) => p, + transform: (r) => r, + }, - return { - post_view: toPostView(response.post_view), - } - } - async getPost( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/post', { - params: { query: fromGetPost(params) }, - }) - ).data! + getFederatedInstances: { + method: 'GET', + path: '/api/alpha/federated_instances', + transform: (r) => r, + }, - return { - community_view: toCommunityView(response.community_view!), - cross_posts: response.cross_posts!.map(toPostView), - moderators: response.moderators!.map((i) => ({ + blockInstance: { + method: 'POST', + path: '/api/alpha/site/block', + transform: (r) => r, + }, + + createPost: { + method: 'POST', + path: '/api/alpha/post', + body: fromCreatePost, + transform: (r: piefed['GetPostResponse']) => ({ + post_view: toPostView(r.post_view), + }), + }, + + getPost: { + method: 'GET', + path: '/api/alpha/post', + query: fromGetPost, + transform: (r: piefed['GetPostResponse']) => ({ + community_view: toCommunityView(r.community_view!), + cross_posts: r.cross_posts!.map(toPostView), + moderators: r.moderators!.map((i: any) => ({ community: toCommunity(i.community), moderator: toPerson(i.moderator), })), - post_view: toPostView(response.post_view), - } - } + post_view: toPostView(r.post_view), + }), + }, - async editPost( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.PUT('/api/alpha/post', { body: params }) - ).data! + editPost: { + method: 'PUT', + path: '/api/alpha/post', + transform: (r: piefed['GetPostResponse']) => ({ + post_view: toPostView(r.post_view), + }), + }, - return { - post_view: toPostView(response.post_view), - } - } - async deletePost( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/post/delete', { body: params }) - ).data! + deletePost: { + method: 'POST', + path: '/api/alpha/post/delete', + transform: (r: piefed['GetPostResponse']) => ({ + post_view: toPostView(r.post_view), + }), + }, - return { - post_view: toPostView(response.post_view), - } - } + removePost: { + method: 'POST', + path: '/api/alpha/post/remove', + transform: (r: piefed['GetPostResponse']) => ({ + post_view: toPostView(r.post_view), + }), + }, - async removePost( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/post/remove', { body: params }) - ).data! + getPosts: { + method: 'GET', + path: '/api/alpha/post/list', + query: fromGetPosts, + transform: (r: piefed['ListPostsResponse'], p) => ({ + ...r, + posts: r.posts.map(toPostView), + next_page: String(Number(p.page_cursor ?? 1) + 1), + }), + }, - return { - post_view: toPostView(response.post_view), - } - } + likePost: { + method: 'POST', + path: '/api/alpha/post/like', + transform: (r: piefed['GetPostResponse']) => ({ + post_view: toPostView(r.post_view), + }), + }, - async getPosts( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/post/list', { - params: { query: fromGetPosts(params) }, - }) - ).data! + markPostAsRead: { + method: 'POST', + path: '/api/alpha/post/mark_as_read', + transform: () => ({ success: true }), + }, - return { - ...response, - posts: response.posts.map(toPostView), - next_page: (Number(params.page_cursor ?? 1) + 1).toString(), - } - } - async likePost( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/post/like', { - body: { ...params }, - }) - ).data! + lockPost: { + method: 'POST', + path: '/api/alpha/post/lock', + transform: (r: piefed['GetPostResponse']) => ({ + post_view: toPostView(r.post_view), + }), + }, - return { - post_view: toPostView(response.post_view), - } - } + featurePost: { + method: 'POST', + path: '/api/alpha/post/feature', + transform: (r: piefed['GetPostResponse']) => ({ + post_view: toPostView(r.post_view), + }), + }, - async generateTotpSecret(): ReturnType { - throw new Error('unsupported') - } - async listLogins(): ReturnType { - throw new Error('unsupported') - } - async listAllMedia(): ReturnType { - throw new Error('unsupported') - } - async updateTotp(): ReturnType { - throw new Error('unsupported') - } - async getModlog(): ReturnType { - throw new Error('unsupported') - } - async search( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/search', { - params: { - query: fromSearch(params), - }, - }) - ).data! + savePost: { + method: 'PUT', + path: '/api/alpha/post/save', + transform: (r: piefed['GetPostResponse']) => ({ + post_view: toPostView(r.post_view), + }), + }, - return { - comments: [], - communities: response.communities.map(toCommunityView), - posts: response.posts.map(toPostView), - users: response.users.map(toPersonView), - type_: response.type_, - } - } - async resolveObject( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/resolve_object', { - params: { query: params }, - }) - ).data! - - return { - comment: response.comment ? toCommentView(response.comment) : undefined, - community: response.community - ? toCommunityView(response.community) - : undefined, - post: response.post ? toPostView(response.post) : undefined, - person: response.person ? toPersonView(response.person) : undefined, - } - } - async createCommunity( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/community', { body: params }) - ).data! - - return { - ...response, - community_view: toCommunityView(response.community_view), - } - } - async getCommunity( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/community', { - params: { - query: params, - }, - }) - ).data! - - return { - ...response, - community_view: toCommunityView(response.community_view), - moderators: response.moderators.map((i) => ({ - community: toCommunity(i.community), - moderator: toPerson(i.moderator), - })), - } - } - async editCommunity( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.PUT('/api/alpha/community', { - body: params, - }) - ).data! - - return { - ...response, - community_view: toCommunityView(response.community_view), - } - } - async listCommunities( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/community/list', { - params: { - query: fromListCommunities(params), - }, - }) - ).data! - - return { - communities: response.communities.map(toCommunityView), - } - } - async followCommunity( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/community/follow', { body: params }) - ).data! - - return { - ...response, - community_view: toCommunityView(response.community_view), - } - } - async blockCommunity( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/community/block', { body: params }) - ).data! - - return { - ...response, - community_view: toCommunityView(response.community_view), - } - } - async deleteCommunity( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/community/delete', { body: params }) - ).data! - - return { - ...response, - community_view: toCommunityView(response.community_view), - } - } - async hideCommunity(): ReturnType { - throw new Error('unsupported') - } - async removeCommunity(): ReturnType { - throw new Error('unsupported') - } - async banFromCommunity( - params: Parameters[0], - ): ReturnType { - const response = // piefed has separate methods for ban/unban - ( - params.ban - ? await this.#client.POST('/api/alpha/community/moderate/ban', { - body: { - ...params, - expiredAt: new Date( - params.expires ?? '6767-06-07T00:00:00.000Z', - ).toISOString(), - user_id: params.person_id, - reason: params.reason ?? 'No reason provided.', - }, - }) - : await this.#client.PUT('/api/alpha/community/moderate/unban', { - body: { - community_id: params.community_id, - user_id: params.person_id, - }, - }) - ).data! - - return { - banned: params.ban, - person_view: { - person: toPerson(response.banned_user!), - counts: { comment_count: -1, person_id: -1, post_count: -1 }, - is_admin: false, - }, - } - } - async addModToCommunity( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/community/mod', { body: params }) - ).data! - - return { - moderators: response.moderators.map((i) => ({ - community: toCommunity(i.community), - moderator: toPerson(i.moderator), - })), - } - } - async markPostAsRead( - params: Parameters[0], - ): ReturnType { - await this.#client.POST('/api/alpha/post/mark_as_read', { - body: { ...params }, - }) - - return { - success: true, - } - } - async hidePost(): ReturnType { - throw new Error('unsupported') - } - async lockPost( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/post/lock', { body: params }) - ).data! - - return { - ...response, - post_view: toPostView(response.post_view), - } - } - async featurePost( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/post/feature', { body: params }) - ).data! - - return { - ...response, - post_view: toPostView(response.post_view), - } - } - async listPostLikes( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/post/like/list', { - params: { query: params }, - }) - ).data! - - return { - post_likes: response.post_likes!.map((i) => ({ + listPostLikes: { + method: 'GET', + path: '/api/alpha/post/like/list', + query: (p) => p, + transform: (r: piefed['ListPostLikesResponse']) => ({ + post_likes: r.post_likes!.map((i: any) => ({ ...i, creator_banned_from_community: false, creator: toPerson(i.creator), })), - } - } - async savePost( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.PUT('/api/alpha/post/save', { body: params }) - ).data! + }), + }, - return { - post_view: toPostView(response.post_view), - } - } - async createPostReport( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/post/report', { body: params }) - ).data! - - return { + createPostReport: { + method: 'POST', + path: '/api/alpha/post/report', + body: (p) => ({ ...p, report_remote: false }), + transform: (r: piefed['PostReportResponse']) => ({ post_report_view: { - ...response.post_report_view, - community: toCommunity(response.post_report_view.community), - post: toPost(response.post_report_view.post), - creator: toPerson(response.post_report_view.creator), - // TODO figure out if this is a bug or not - resolver: response.post_report_view.resolver - ? toPerson(response.post_report_view.resolver!) + ...r.post_report_view, + community: toCommunity(r.post_report_view.community), + post: toPost(r.post_report_view.post), + creator: toPerson(r.post_report_view.creator), + resolver: (r.post_report_view as any).resolver + ? toPerson((r.post_report_view as any).resolver) : undefined, - post_creator: toPerson(response.post_report_view.post_creator), + post_creator: toPerson(r.post_report_view.post_creator), read: false, hidden: false, creator_banned_from_community: false, unread_comments: -1, }, - } - } - async resolvePostReport(): ReturnType { - throw new Error('unsupported') - } - async listPostReports(): ReturnType { - throw new Error('unsupported') - } - async getSiteMetadata( - params: Parameters[0], - ): ReturnType { - return ( - await this.#client.GET('/api/alpha/post/site_metadata', { - params: { query: params }, - }) - ).data! - } + }), + }, - async createComment( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/comment', { - body: fromCreateComment(params), - }) - ).data! + // @ts-expect-error for some reason this method doesn't exist on MethodDefinitions + voteOnPoll: { + method: 'POST', + path: '/api/alpha/post/poll_vote', + transform: (r: piefed['PollVoteResponse']) => ({ + post_view: toPostView(r.post_view), + }), + }, - return { - ...response, - comment_view: toCommentView(response.comment_view), + createComment: { + method: 'POST', + path: '/api/alpha/comment', + body: fromCreateComment, + transform: (r: piefed['GetCommentResponse']) => ({ + ...r, + comment_view: toCommentView(r.comment_view), recipient_ids: [], - } - } - async editComment( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.PUT('/api/alpha/comment', { - body: { ...params, body: params.content }, - }) - ).data! + }), + }, - return { - comment_view: toCommentView(response.comment_view), + editComment: { + method: 'PUT', + path: '/api/alpha/comment', + body: (p) => ({ ...p, body: p.content, distinguished: false }), + transform: (r: piefed['GetCommentResponse']) => ({ + ...r, + comment_view: toCommentView(r.comment_view), recipient_ids: [], - } - } - async deleteComment( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/comment/delete', { body: params }) - ).data! + }), + }, - return { - comment_view: toCommentView(response.comment_view), + deleteComment: { + method: 'POST', + path: '/api/alpha/comment/delete', + transform: (r: piefed['GetCommentResponse']) => ({ + ...r, + comment_view: toCommentView(r.comment_view), recipient_ids: [], - } - } - async removeComment( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/comment/remove', { body: params }) - ).data! + }), + }, - return { - comment_view: toCommentView(response.comment_view), + removeComment: { + method: 'POST', + path: '/api/alpha/comment/remove', + transform: (r: piefed['GetCommentResponse']) => ({ + ...r, + comment_view: toCommentView(r.comment_view), recipient_ids: [], - } - } - async markCommentReplyAsRead( - params: Parameters[0], - ): ReturnType { - await this.#client.POST('/api/alpha/comment/mark_as_read', { - body: params, - }) - } - async likeComment( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/comment/like', { - body: { - ...params, - // TODO add private votes - private: false, - }, - }) - ).data! + }), + }, - return { - comment_view: toCommentView(response.comment_view), + markCommentReplyAsRead: { + method: 'POST', + path: '/api/alpha/comment/mark_as_read', + transform: () => undefined, + }, + + likeComment: { + method: 'POST', + path: '/api/alpha/comment/like', + body: (p) => ({ ...p, private: false }), + transform: (r: piefed['GetCommentResponse']) => ({ + comment_view: toCommentView(r.comment_view), recipient_ids: [], - } - } + }), + }, - async listCommentLikes( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/comment/like/list', { - params: { query: params }, - }) - ).data! - - return { - comment_likes: response.comment_likes!.map((i) => ({ + listCommentLikes: { + method: 'GET', + path: '/api/alpha/comment/like/list', + query: (p) => p, + transform: (r: piefed['ListCommentLikesResponse']) => ({ + comment_likes: r.comment_likes!.map((i: any) => ({ ...i, creator: toPerson(i.creator), })), - } - } - async saveComment( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.PUT('/api/alpha/comment/save', { body: params }) - ).data! + }), + }, - return { - ...response, - comment_view: toCommentView(response.comment_view), + saveComment: { + method: 'PUT', + path: '/api/alpha/comment/save', + transform: (r: piefed['GetCommentResponse']) => ({ + ...r, + comment_view: toCommentView(r.comment_view), recipient_ids: [], - } - } - async distinguishComment(): ReturnType { - throw new Error('unsupported') - } + }), + }, - async getComments( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/comment/list', { - params: { query: fromGetComments(params) }, - }) - ).data! + getComments: { + method: 'GET', + path: '/api/alpha/comment/list', + query: fromGetComments, + transform: (r: piefed['ListCommentsResponse']) => ({ + comments: r.comments.map(toCommentView), + }), + }, - return { - comments: response.comments.map(toCommentView), - } - } - - async getComment( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/comment', { - params: { query: params }, - }) - ).data! - - return { - ...response, - comment_view: toCommentView(response.comment_view), + getComment: { + method: 'GET', + path: '/api/alpha/comment', + query: (p) => p, + transform: (r: piefed['GetCommentResponse']) => ({ + ...r, + comment_view: toCommentView(r.comment_view), recipient_ids: [], - } - } - async createCommentReport( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/comment/report', { - body: { - ...params, - // TODO add remote reports - report_remote: false, - }, - }) - ).data! + }), + }, - return { - ...response, + // createCommentReport: async (client, params) => { + // const response = assertData( + // await client.POST('/api/alpha/comment/report', { + // body: { + // ...params, + // report_remote: false, + // reason: params.reason ?? '', + // } as any, + // }), + // ) + // return { + // ...response, + // comment_report_view: { + // ...response.comment_report_view, + // comment: toComment(response.comment_report_view.comment), + // community: toCommunity(response.comment_report_view.community), + // comment_creator: toPerson(response.comment_report_view.comment_creator), + // creator: toPerson(response.comment_report_view.creator), + // post: toPost(response.comment_report_view.post), + // resolver: (response.comment_report_view as any).resolver + // ? toPerson((response.comment_report_view as any).resolver) + // : undefined, + // subscribed: response.comment_report_view.subscribed as SubscribedType, + // }, + // } + // }, + + createCommentReport: { + method: 'POST', + path: '/api/alpha/comment/report', + body: (p) => ({ ...p, report_report: false, reason: p.reason ?? '' }), + transform: (r: piefed['GetCommentReportResponse']) => ({ + ...r, comment_report_view: { - ...response.comment_report_view, - comment: toComment(response.comment_report_view.comment), - community: toCommunity(response.comment_report_view.community), - comment_creator: toPerson(response.comment_report_view.comment_creator), - creator: toPerson(response.comment_report_view.creator), - post: toPost(response.comment_report_view.post), - // TODO figure out what's wrong here - resolver: response.comment_report_view.resolver - ? toPerson(response.comment_report_view.resolver) + ...r.comment_report_view, + comment: toComment(r.comment_report_view.comment), + community: toCommunity(r.comment_report_view.community), + comment_creator: toPerson(r.comment_report_view.comment_creator), + creator: toPerson(r.comment_report_view.creator), + post: toPost(r.comment_report_view.post), + resolver: (r.comment_report_view as any).resolver + ? toPerson((r.comment_report_view as any).resolver) : undefined, - subscribed: response.comment_report_view.subscribed as SubscribedType, + subscribed: r.comment_report_view.subscribed as types.SubscribedType, + }, + }), + }, + + createCommunity: { + method: 'POST', + path: '/api/alpha/community', + transform: (r: piefed['CommunityResponse']) => ({ + ...r, + community_view: toCommunityView(r.community_view), + }), + }, + + getCommunity: { + method: 'GET', + path: '/api/alpha/community', + query: (p) => p, + transform: (r: piefed['GetCommunityResponse']) => ({ + ...r, + community_view: toCommunityView(r.community_view), + moderators: r.moderators.map((i: any) => ({ + community: toCommunity(i.community), + moderator: toPerson(i.moderator), + })), + }), + }, + + editCommunity: { + method: 'PUT', + path: '/api/alpha/community', + transform: (r: piefed['CommunityResponse']) => ({ + ...r, + community_view: toCommunityView(r.community_view), + }), + }, + + listCommunities: { + method: 'GET', + path: '/api/alpha/community/list', + query: fromListCommunities, + transform: (r: piefed['ListCommunitiesResponse']) => ({ + communities: r.communities.map(toCommunityView), + }), + }, + + followCommunity: { + method: 'POST', + path: '/api/alpha/community/follow', + transform: (r: piefed['CommunityResponse']) => ({ + ...r, + community_view: toCommunityView(r.community_view), + }), + }, + + blockCommunity: { + method: 'POST', + path: '/api/alpha/community/block', + transform: (r: piefed['CommunityResponse'], p) => ({ + ...r, + community_view: toCommunityView(r.community_view), + blocked: p.block, + }), + }, + + deleteCommunity: { + method: 'POST', + path: '/api/alpha/community/delete', + transform: (r: piefed['CommunityResponse']) => ({ + ...r, + community_view: toCommunityView(r.community_view), + }), + }, + + banFromCommunity: async ( + client, + params: Parameters[0], + ) => { + const response = params.ban + ? await client.POST('/api/alpha/community/moderate/ban', { + body: { + community_id: params.community_id, + user_id: params.person_id, + reason: params.reason ?? 'No reason provided.', + // why is this nullable bro + expiredAt: new Date( + params.expires ?? '6767-06-07T06:07:06Z', + ).toISOString(), + } as any, + }) + : await client.PUT('/api/alpha/community/moderate/unban', { + body: { + community_id: params.community_id, + user_id: params.person_id, + } as any, + }) + + return { + banned: params.ban, + person_view: { + person: toPerson(assertData(response).banned_user!), + counts: { comment_count: -1, person_id: -1, post_count: -1 }, + is_admin: false, }, } - } - async resolveCommentReport(): ReturnType { - throw new Error('unsupported') - } - async listCommentReports(): ReturnType { - throw new Error('unsupported') - } - async getPrivateMessages( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/private_message/list', { - params: { query: params }, - }) - ).data! + }, - return { - private_messages: response.private_messages.map(toPrivateMessageView), - } - } - async createPrivateMessage( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/private_message', { body: params }) - ).data! + addModToCommunity: { + method: 'POST', + path: '/api/alpha/community/mod', + transform: (r: piefed['ModCommunityResponse']) => ({ + moderators: r.moderators.map((i) => ({ + community: toCommunity(i.community), + moderator: toPerson(i.moderator), + })), + }), + }, - return { - ...response, - private_message_view: toPrivateMessageView(response.private_message_view), - } - } - async editPrivateMessage( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.PUT('/api/alpha/private_message', { body: params }) - ).data! + search: { + method: 'GET', + path: '/api/alpha/search', + query: fromSearch, + transform: (r: piefed['SearchResponse']) => ({ + comments: [], + communities: r.communities.map(toCommunityView), + posts: r.posts.map(toPostView), + users: r.users.map(toPersonView), + type_: r.type_, + }), + }, - return { - ...response, - private_message_view: toPrivateMessageView(response.private_message_view), - } - } - async deletePrivateMessage( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/private_message/delete', { - body: params, - }) - ).data! + resolveObject: { + method: 'GET', + path: '/api/alpha/resolve_object', + query: (p) => p, + transform: (r: piefed['ResolveObjectResponse']) => ({ + // just make the rewrite options accept null values bro + comment: r.comment ? toCommentView(r.comment) : undefined, + community: r.community ? toCommunityView(r.community) : undefined, + post: r.post ? toPostView(r.post) : undefined, + person: r.person ? toPersonView(r.person) : undefined, + }), + }, - return { - ...response, - private_message_view: toPrivateMessageView(response.private_message_view), - } - } - async markPrivateMessageAsRead( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/private_message/mark_as_read', { - body: params, - }) - ).data! + getPrivateMessages: { + method: 'GET', + path: '/api/alpha/private_message/list', + query: (p) => p, + transform: (r: piefed['ListPrivateMessagesResponse']) => ({ + private_messages: r.private_messages.map(toPrivateMessageView), + }), + }, - return { - ...response, - private_message_view: toPrivateMessageView(response.private_message_view), - } - } - async createPrivateMessageReport(): ReturnType< - BaseClient['createPrivateMessageReport'] - > { - throw new Error('unsupported') - } - async resolvePrivateMessageReport(): ReturnType< - BaseClient['resolvePrivateMessageReport'] - > { - throw new Error('unsupported') - } - async listPrivateMessageReports(): ReturnType< - BaseClient['listPrivateMessageReports'] - > { - throw new Error('unsupported') - } - async register(): ReturnType { - throw new Error('unsupported') - } - async login( - params: Parameters[0], - ): ReturnType { - const response = await this.#client.POST('/api/alpha/user/login', { + createPrivateMessage: { + method: 'POST', + path: '/api/alpha/private_message', + transform: (p: piefed['PrivateMessageResponse']) => ({ + ...p, + private_message_view: toPrivateMessageView(p.private_message_view), + }), + }, + + editPrivateMessage: { + method: 'PUT', + path: '/api/alpha/private_message', + transform: (p: piefed['PrivateMessageResponse']) => ({ + ...p, + private_message_view: toPrivateMessageView(p.private_message_view), + }), + }, + + deletePrivateMessage: { + method: 'POST', + path: '/api/alpha/private_message/delete', + transform: (p: piefed['PrivateMessageResponse']) => ({ + ...p, + private_message_view: toPrivateMessageView(p.private_message_view), + }), + }, + + markPrivateMessageAsRead: { + method: 'POST', + path: '/api/alpha/private_message/mark_as_read', + transform: (p: piefed['PrivateMessageResponse']) => ({ + ...p, + private_message_view: toPrivateMessageView(p.private_message_view), + }), + }, + + login: async (client, params) => { + const response = await client.POST('/api/alpha/user/login', { body: { username: params.username_or_email, password: params.password }, - })! - + }) return { verify_email_sent: false, registration_created: false, jwt: response.data?.jwt, } - } - async logout(): ReturnType { - throw new Error('unsupported') - } - async getPersonDetails( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/user', { - params: { - query: { - ...params, - include_content: true, - sort: toSortType(params.sort), - }, - }, - }) - ).data! + }, - return { - comments: response.comments.map(toCommentView), - moderates: response.moderates.map((i) => ({ + getPersonDetails: { + method: 'GET', + path: '/api/alpha/user', + query: (p) => ({ ...p, include_content: true, sort: toSortType(p.sort) }), + transform: (r: piefed['GetUserResponse']) => ({ + comments: r.comments.map(toCommentView), + moderates: r.moderates.map((i: any) => ({ community: toCommunity(i.community), moderator: toPerson(i.moderator), })), - person_view: toPersonView(response.person_view), - posts: response.posts.map(toPostView), - } - } - async getPersonMentions( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/user/mentions', { - params: { query: { ...params, sort: toCommentSortType(params.sort) } }, - }) - ).data! + person_view: toPersonView(r.person_view), + posts: r.posts.map(toPostView), + }), + }, - return { - mentions: response.replies.map(toPersonMentionView), - } - } - async markPersonMentionAsRead( - params: Parameters[0], - ): ReturnType { - // @ts-expect-error this method isnt documented - await this.#client.POST('/api/alpha/mention/mark_as_read', { + getPersonMentions: { + method: 'GET', + path: '/api/alpha/user/mentions', + query: (p) => ({ ...p, sort: toCommentSortType(p.sort) }), + transform: (r: piefed['UserMentionsResponse']) => ({ + mentions: r.replies.map(toPersonMentionView), + }), + }, + + // current xylight has no idea why past xylight did this + markPersonMentionAsRead: async (client, params) => { + await (client as any).POST('/api/alpha/mention/mark_as_read', { body: params, }) - } - async getReplies( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.GET('/api/alpha/user/replies', { - params: { query: fromGetReplies(params) }, - }) - ).data! + }, - return { - replies: response.replies.map(toCommentReplyView), - } - } - async banPerson(): ReturnType { - // this is for site view not community view - throw new Error('unsupported') - } - async getBannedPersons(): ReturnType { - // this is for site view not community view - throw new Error('unsupported') - } - async blockPerson( - params: Parameters[0], - ): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/user/block', { body: params }) - ).data! + getReplies: { + method: 'GET', + path: '/api/alpha/user/replies', + query: fromGetReplies, + transform: (r: piefed['UserRepliesResponse']) => ({ + replies: r.replies.map(toCommentReplyView), + }), + }, - return { - ...response, - person_view: toPersonView(response.person_view), - } - } - async getCaptcha(): ReturnType { - throw new Error('unsupported') - } - async deleteAccount(): ReturnType { - throw new Error('unsupported') - } - async passwordReset(): ReturnType { - throw new Error('unsupported') - } - async passwordChangeAfterReset(): ReturnType< - BaseClient['passwordChangeAfterReset'] - > { - throw new Error('unsupported') - } - async markAllAsRead(): ReturnType { - const response = ( - await this.#client.POST('/api/alpha/user/mark_all_as_read') - ).data! + blockPerson: { + method: 'POST', + path: '/api/alpha/user/block', + transform: (r: piefed['UserBlockResponse']) => ({ + ...r, + person_view: toPersonView(r.person_view), + }), + }, - return { - replies: response.replies.map(toCommentReplyView), - } - } - async saveUserSettings( - params: Parameters[0], - ): ReturnType { - await this.#client.PUT('/api/alpha/user/save_user_settings', { - body: params, - }) - return { - success: true, - } - } - async changePassword(): ReturnType { - throw new Error('unsupported') - } - async getReportCount(): ReturnType { - throw new Error('unsupported') - } - async getUnreadCount(): ReturnType { - return (await this.#client.GET('/api/alpha/user/unread_count')).data! - } - async verifyEmail(): ReturnType { - throw new Error('unsupported') - } - async addAdmin(): ReturnType { - throw new Error('unsupported') - } - async getUnreadRegistrationApplicationCount(): ReturnType< - BaseClient['getUnreadRegistrationApplicationCount'] - > { - throw new Error('unsupported') - } - async listRegistrationApplications(): ReturnType< - BaseClient['listRegistrationApplications'] - > { - throw new Error('unsupported') - } - async approveRegistrationApplication(): ReturnType< - BaseClient['approveRegistrationApplication'] - > { - throw new Error('unsupported') - } - async getRegistrationApplication(): ReturnType< - BaseClient['getRegistrationApplication'] - > { - throw new Error('unsupported') - } - async purgePerson(): ReturnType { - throw new Error('unsupported') - } - async purgeCommunity(): ReturnType { - throw new Error('unsupported') - } - async purgePost(): ReturnType { - throw new Error('unsupported') - } - async purgeComment(): ReturnType { - throw new Error('unsupported') - } - async getFederatedInstances(): ReturnType< - BaseClient['getFederatedInstances'] - > { - return (await this.#client.GET('/api/alpha/federated_instances')).data! - } - async blockInstance( - params: Parameters[0], - ): ReturnType { - return (await this.#client.POST('/api/alpha/site/block', { - body: { ...params }, - }))!.data! - } - async uploadImage( - params: Parameters[0], - ): ReturnType { + markAllAsRead: { + method: 'POST', + path: '/api/alpha/user/mark_all_as_read', + transform: (r: piefed['UserMarkAllReadResponse']) => ({ + replies: r.replies.map(toCommentReplyView), + }), + }, + + saveUserSettings: { + method: 'PUT', + path: '/api/alpha/user/save_user_settings', + body: (p) => p, + transform: () => ({ success: true }), + }, + + getUnreadCount: { + method: 'GET', + path: '/api/alpha/user/unread_count', + transform: (r: piefed['UserUnreadCountsResponse']) => r, + }, + + setFlair: { + method: 'POST', + path: '/api/alpha/user/set_flair', + transform: (r: piefed['UserSetFlairResponse']) => ({ + ...r, + person_view: toPersonView(r.person_view!), + }), + }, + + setNote: { + method: 'POST', + path: '/api/alpha/user/note', + body: (p: types.SetNote) => ({ ...p, note: p.note ?? '' }), + transform: (r: piefed['UserSetNoteResponse']) => ({ + ...r, + person_view: toPersonView(r.person_view), + }), + }, + + getFeeds: { + method: 'GET', + path: '/api/alpha/feed/list', + query: (p: types.GetFeeds) => p, + // why is it FeedList and not ListFeeds + transform: (r: piefed['FeedListResponse']) => ({ + ...r, + feeds: r.feeds.map(toFeedView), + }), + }, + + getTopics: { + method: 'GET', + path: '/api/alpha/topic/list', + query: (p: types.GetTopics) => p, + // same here + transform: (r: piefed['TopicListResponse']) => ({ + ...r, + topics: r.topics.map(toTopicView), + }), + }, + + uploadImage: async (client, params) => { const formData = new FormData() formData.append('file', params.image as File) + const response = assertData( + await client.POST('/api/alpha/upload/image', { + body: formData as any, + }), + ) + return { ...response, msg: 'Image uploaded successfully' } + }, - const response = ( - await this.#client.POST('/api/alpha/upload/image', { - // @ts-expect-error this is the only working way to do this - body: formData, + generateTotpSecret: 'unsupported', + listLogins: 'unsupported', + listAllMedia: 'unsupported', + updateTotp: 'unsupported', + getModlog: 'unsupported', + hidePost: 'unsupported', + hideCommunity: 'unsupported', + removeCommunity: 'unsupported', + resolvePostReport: 'unsupported', + listPostReports: 'unsupported', + distinguishComment: 'unsupported', + resolveCommentReport: 'unsupported', + listCommentReports: 'unsupported', + createPrivateMessageReport: 'unsupported', + resolvePrivateMessageReport: 'unsupported', + listPrivateMessageReports: 'unsupported', + register: 'unsupported', + logout: 'unsupported', + banPerson: 'unsupported', + getBannedPersons: 'unsupported', + getCaptcha: 'unsupported', + deleteAccount: 'unsupported', + passwordReset: 'unsupported', + passwordChangeAfterReset: 'unsupported', + changePassword: 'unsupported', + getReportCount: 'unsupported', + verifyEmail: 'unsupported', + addAdmin: 'unsupported', + getUnreadRegistrationApplicationCount: 'unsupported', + listRegistrationApplications: 'unsupported', + approveRegistrationApplication: 'unsupported', + getRegistrationApplication: 'unsupported', + purgePerson: 'unsupported', + purgeCommunity: 'unsupported', + purgePost: 'unsupported', + purgeComment: 'unsupported', + editSite: 'unsupported', + deleteImage: 'unsupported', + listMedia: 'unsupported', +} satisfies MethodDefinitions + +export const PiefedClientConstants = { + password: { minLength: 6, maxLength: 128 }, +} + +async function executeMethod< + K extends MethodName, + P extends keyof paths, + M extends HttpMethod, +>( + client: ApiClient, + config: MethodConfig, + // i have been up for 3 hours writing typescript types. i am not going to be bothered to figure + // this out right before i am at the end + params: any, +): Promise { + const execute = async () => { + if (config.method === 'GET') { + return await client.GET(config.path as any, { + params: { query: config.query?.(params) ?? params }, + }) + } else { + return await (client as any)[config.method](config.path, { + body: config.body?.(params) ?? params, }) - ).data! - - return { - ...response, - msg: 'yeah it worked i think', } } - async setFlair( - params: NullableFnArg[0], - ): NullableFnReturn { - const response = ( - await this.#client.POST('/api/alpha/user/set_flair', { body: params }) - ).data! + return execute().then((response) => + config.transform(assertData(response), params), + ) +} - return toPersonView(response.person_view!) +export function createPiefedClient( + baseUrl: string, + args: { + fetchFunction: (input: any, init: any) => Promise + headers: any + }, +): BaseClient { + const client = createClient({ + baseUrl, + fetch: args.fetchFunction as any, + headers: args.headers, + }) + + const instance = { + type: { name: 'piefed', baseUrl: '/api/alpha' } as ClientType, } - async editSite(): ReturnType { - throw new Error('unsupported') - } - async deleteImage(): ReturnType { - throw new Error('unsupported') - } + return new Proxy(instance as BaseClient, { + get(target, prop: string, receiver) { + if (prop in target) return Reflect.get(target, prop, receiver) - async getFeeds( - params: NullableFnArg[0], - ): NullableFnReturn { - const response = ( - await this.#client.GET('/api/alpha/feed/list', { - params: { query: params }, - }) - ).data! + const def = methods[prop as MethodName] + if (!def) return undefined - return { - ...response, - feeds: response.feeds.map(toFeedView), - } - } + if (def === 'unsupported') { + return () => { + throw new Error(`${prop} is not supported on PieFed`) + } + } - async getTopics( - params: NullableFnArg[0], - ): NullableFnReturn { - const response = ( - await this.#client.GET('/api/alpha/topic/list', { - params: { query: params }, - }) - ).data! + if (typeof def === 'function') { + return (params: unknown) => def(client, params) + } - return { - ...response, - topics: response.topics.map(toTopicView), - } - } + return (params: unknown) => executeMethod(client, def, params) + }, + }) +} - async assignFlair( - params: NullableFnArg[0], - ): NullableFnReturn { - const response = ( - await this.#client.POST('/api/alpha/post/assign_flair', { - body: params, - }) - ).data! +export class PiefedClient { + static constants = PiefedClientConstants - return toPostView(response) - } + #proxy: BaseClient - async listMedia(): ReturnType { - throw new Error('unsupported') - } + constructor( + baseUrl: string, + args: { + fetchFunction: (input: any, init: any) => Promise + headers: any + }, + ) { + this.#proxy = createPiefedClient(baseUrl, args) - async voteOnPoll( - params: NullableFnArg[0], - ): NullableFnReturn { - const response = ( - await this.#client.POST('/api/alpha/post/poll_vote', { body: params }) - ).data! - - return toPostView(response.post_view) - } - - async setNote( - params: NullableFnArg[0], - ): NullableFnReturn { - const response = ( - await this.#client.POST('/api/alpha/user/note', { body: params }) - ).data! - - return toPersonView(response.person_view) + return new Proxy(this, { + get: (target, prop) => { + if (prop === 'constructor') return PiefedClient + return (target.#proxy as any)[prop] + }, + }) as any } } diff --git a/src/lib/api/piefed/rewrite.ts b/src/lib/api/piefed/rewrite.ts index 4e807658..d1eda11e 100644 --- a/src/lib/api/piefed/rewrite.ts +++ b/src/lib/api/piefed/rewrite.ts @@ -1,36 +1,23 @@ -import { Search } from 'mono-svelte' -import type { - Comment, - CommentReplyView, - CommentSortType, - CommentView, - Community, - CommunityView, - CreateComment, - CreatePost, - FeedView, - GetComments, - GetPost, - GetPosts, - GetReplies, - ListCommunities, - LocalSite, - MyUserInfo, - Person, - PersonMentionView, - PersonView, - Post, - PostView, - PrivateMessageView, - SortType, - SubscribedType, - TopicView, -} from '../types' -import type { components } from './schema' +import * as base from '../types' +import type { components, paths } from './schema' + +type Schema = components['schemas'][T] + +type PathQuery

= paths[P] extends { + get: { parameters: { query?: infer Q } } +} + ? Q + : never + +type PathBody

= paths[P] extends { + post: { requestBody: { content: { 'application/json': infer B } } } +} + ? B + : never export function toPersonView( - personView: components['schemas']['PersonView'], -): PersonView { + personView: Schema<'PersonView'>, +): base.PersonView { return { counts: personView.counts, is_admin: personView.is_admin, @@ -38,7 +25,7 @@ export function toPersonView( } } -export function toPerson(person: components['schemas']['Person']): Person { +export function toPerson(person: Schema<'Person'>): base.Person { return { ...person, id: person.id, @@ -47,14 +34,14 @@ export function toPerson(person: components['schemas']['Person']): Person { } } -export function toLocalSite(site: components['schemas']['Site']): LocalSite { +export function toLocalSite(site: Schema<'Site'>): base.LocalSite { if (site) return {} return {} } export function toCommunityView( - communityView: components['schemas']['CommunityView'], -): CommunityView { + communityView: Schema<'CommunityView'>, +): base.CommunityView { return { ...communityView, community: toCommunity(communityView.community), @@ -74,9 +61,7 @@ export function toCommunityView( } } -export function toCommunity( - community: components['schemas']['Community'], -): Community { +export function toCommunity(community: Schema<'Community'>): base.Community { return { ...community, posting_restricted_to_mods: false, @@ -84,9 +69,7 @@ export function toCommunity( } } -export function toMyUser( - myUser: components['schemas']['MyUserInfo'], -): MyUserInfo { +export function toMyUser(myUser: Schema<'MyUserInfo'>): base.MyUserInfo { return { ...myUser, community_blocks: myUser.community_blocks.map((i) => ({ @@ -125,9 +108,7 @@ export function toMyUser( } } -export function toPostView( - postView: components['schemas']['PostView'], -): PostView { +export function toPostView(postView: Schema<'PostView'>): base.PostView { return { ...postView, creator: toPerson(postView.creator), @@ -137,7 +118,7 @@ export function toPostView( } } -export function toPost(post: components['schemas']['Post']): Post { +export function toPost(post: Schema<'Post'>): base.Post { return { ...post, creator_id: -1, @@ -148,19 +129,19 @@ export function toPost(post: components['schemas']['Post']): Post { } export function toCommentView( - commentView: components['schemas']['CommentView'], -): CommentView { + commentView: Schema<'CommentView'>, +): base.CommentView { return { ...commentView, comment: toComment(commentView.comment), creator: toPerson(commentView.creator), post: toPost(commentView.post), community: toCommunity(commentView.community), - subscribed: commentView.subscribed as SubscribedType, + subscribed: commentView.subscribed as base.SubscribedType, } } -export function toComment(comment: components['schemas']['Comment']): Comment { +export function toComment(comment: Schema<'Comment'>): base.Comment { return { ...comment, content: comment.body, @@ -170,8 +151,8 @@ export function toComment(comment: components['schemas']['Comment']): Comment { } export function toCommentReplyView( - commentReplyView: components['schemas']['CommentReplyView'], -): CommentReplyView { + commentReplyView: Schema<'CommentReplyView'>, +): base.CommentReplyView { return { ...commentReplyView, banned_from_community: false, @@ -185,8 +166,8 @@ export function toCommentReplyView( } export function toPrivateMessageView( - privateMessageView: components['schemas']['PrivateMessageView'], -): PrivateMessageView { + privateMessageView: Schema<'PrivateMessageView'>, +): base.PrivateMessageView { return { ...privateMessageView, creator: toPerson(privateMessageView.creator), @@ -195,8 +176,8 @@ export function toPrivateMessageView( } export function toPersonMentionView( - personMentionView: components['schemas']['CommentReplyView'], -): PersonMentionView { + personMentionView: Schema<'CommentReplyView'>, +): base.PersonMentionView { return { ...personMentionView, person_mention: personMentionView.comment_reply, @@ -210,9 +191,7 @@ export function toPersonMentionView( } } -export function toTopicView( - topicView: components['schemas']['TopicView'], -): TopicView { +export function toTopicView(topicView: Schema<'TopicView'>): base.TopicView { return { ...topicView, communities: topicView.communities?.map(toCommunity), @@ -220,9 +199,7 @@ export function toTopicView( } } -export function toFeedView( - feedView: components['schemas']['FeedView'], -): FeedView { +export function toFeedView(feedView: Schema<'FeedView'>): base.FeedView { return { ...feedView, communities: feedView.communities?.map(toCommunity), @@ -230,10 +207,9 @@ export function toFeedView( } } -// Query calls export function fromGetPosts( - getPosts: GetPosts, -): components['parameters']['GetPosts'] { + getPosts: base.GetPosts, +): PathQuery<'/api/alpha/post/list'> { return { ...getPosts, sort: toSortType(getPosts.sort), @@ -242,8 +218,8 @@ export function fromGetPosts( } export function fromGetComments( - getComments: GetComments, -): components['schemas']['GetComments'] { + getComments: base.GetComments, +): PathQuery<'/api/alpha/comment/list'> { return { ...getComments, sort: toCommentSortType(getComments.sort), @@ -251,23 +227,25 @@ export function fromGetComments( } export function fromGetPost( - getPost: GetPost, -): components['schemas']['GetPost'] { + getPost: base.GetPost, +): PathQuery<'/api/alpha/post'> { return getPost } export function fromGetReplies( - getReplies: GetReplies, -): components['schemas']['GetReplies'] { + getReplies: base.GetReplies, +): PathQuery<'/api/alpha/user/replies'> { return { ...getReplies, sort: toCommentSortType(getReplies.sort), } } -export function fromSearch(search: Search): components['schemas']['Search'] { +export function fromSearch( + search: base.Search, +): PathQuery<'/api/alpha/search'> { return { - ...(search as Omit & { + ...(search as Omit & { type_: 'Communities' | 'Users' | 'Url' | 'Posts' }), sort: toSortType(search.sort), @@ -275,8 +253,8 @@ export function fromSearch(search: Search): components['schemas']['Search'] { } export function fromCreatePost( - createPost: CreatePost, -): components['schemas']['CreatePost'] { + createPost: base.CreatePost, +): PathBody<'/api/alpha/post'> { return { ...createPost, title: createPost.name, @@ -284,27 +262,28 @@ export function fromCreatePost( } export function fromListCommunities( - listCommunities: ListCommunities, -): components['schemas']['CommunityRequest'] { + listCommunities: base.ListCommunities, +): PathQuery<'/api/alpha/community/list'> { return { ...listCommunities, + type_: listCommunities.type_ as 'All', sort: toCommunitiesSortType(listCommunities.sort), } } export function fromCreateComment( - createComment: CreateComment, -): components['schemas']['CreateComment'] { + createComment: base.CreateComment, +): PathBody<'/api/alpha/comment'> { return { ...createComment, body: createComment.content, } } -// Misc export function toSortType( - sortType?: SortType, -): components['schemas']['SortType'] | undefined { + sortType?: base.SortType, +): Schema<'SortType'> | undefined { + if (!sortType) return if ( sortType == 'Old' || sortType == 'MostComments' || @@ -312,18 +291,19 @@ export function toSortType( sortType == 'NewComments' ) sortType = 'New' - return sortType + if (sortType?.startsWith('Top')) sortType = 'TopAll' + return sortType as Schema<'SortType'> } export function toCommentSortType( - commentSortType?: CommentSortType, -): components['schemas']['CommentSortType'] | undefined { + commentSortType?: base.CommentSortType, +): Schema<'CommentSortType'> | undefined { if (commentSortType == 'Controversial') commentSortType = undefined return commentSortType } export function toCommunitiesSortType( - sortType?: SortType, + sortType?: base.SortType, ): 'Top' | 'Hot' | 'New' | undefined { if (sortType == 'Hot' || sortType == 'New' || sortType == undefined) return sortType diff --git a/src/lib/api/piefed/schema.d.ts b/src/lib/api/piefed/schema.d.ts index 07442101..018dd5b4 100644 --- a/src/lib/api/piefed/schema.d.ts +++ b/src/lib/api/piefed/schema.d.ts @@ -4706,7 +4706,7 @@ export interface components { * Format: datetime * @example 2025-06-07T02:29:07.980084Z */ - published?: string + published: string title?: string } PersonView: { @@ -5809,7 +5809,7 @@ export interface components { note: string } UserSetNoteResponse: { - person_view?: components['schemas']['PersonView'] + person_view: components['schemas']['PersonView'] } ListCommentsResponse: { comments: components['schemas']['CommentView'][] @@ -5873,7 +5873,7 @@ export interface components { id: number creator_id: number comment_id: number - original_comment_text?: string + original_comment_text: string reason?: string resolved: boolean /** @@ -6057,7 +6057,7 @@ export interface components { * Format: datetime * @example 2025-06-07T02:29:07.980084Z */ - published?: string + published: string } PostReportView: { post_report: components['schemas']['PostReport'] @@ -6215,6 +6215,8 @@ export interface components { private_message_id: number reason: string } + SortType: 'Active' | 'Hot' | 'TopAll' | 'New' | 'Old' + CommentSortType: 'Hot' | 'Top' | 'TopAll' | 'New' | 'Old' } responses: { /** @description Unprocessable Content */ diff --git a/src/lib/api/types/generated.ts b/src/lib/api/types/generated.ts index 5ac19930..578dd6d6 100644 --- a/src/lib/api/types/generated.ts +++ b/src/lib/api/types/generated.ts @@ -165,7 +165,7 @@ export interface GetPersonMentionsResponse { } export interface GetPost { - id?: PostId + id: PostId comment_id?: CommentId } @@ -190,8 +190,8 @@ export interface GetPosts { show_read?: boolean show_nsfw?: boolean page_cursor?: PaginationCursor - feed_id?: string - topic_id?: string + feed_id?: number + topic_id?: number } export interface GetPostsResponse { @@ -2333,7 +2333,7 @@ export interface UpdateTotpResponse { } export interface UploadImage { - image: File | Buffer + image: File } export interface UploadImageResponse { msg: string diff --git a/src/lib/app/auth/inbox.svelte.ts b/src/lib/app/auth/inbox.svelte.ts new file mode 100644 index 00000000..9eed0b3c --- /dev/null +++ b/src/lib/app/auth/inbox.svelte.ts @@ -0,0 +1,90 @@ +import type { Profile } from './profile.svelte' + +interface Notifications { + inbox: number + reports: number + applications: number +} + +export class InboxService { + private readonly POLL_INTERVAL = 4 * 60 * 1000 + #pollInterval: ReturnType | null = null + + #profile: Profile + + notifications = $state({ + applications: 0, + inbox: 0, + reports: 0, + }) + + constructor(profile: Profile) { + this.#profile = profile + } + + async init(): Promise { + this.cleanup() + + this.notifications = await this.checkInbox() + + this.#pollInterval = setInterval(async () => { + this.notifications = await this.checkInbox() + }, this.POLL_INTERVAL) + } + + cleanup(): void { + if (this.#pollInterval) clearInterval(this.#pollInterval) + + this.#pollInterval = null + } + + clear(): Notifications { + this.notifications = { + applications: 0, + inbox: 0, + reports: 0, + } + return this.notifications + } + + async checkInbox(): Promise { + if (!this.#profile.current.user || !this.#profile.current.jwt) + return this.clear() + + const unreadsPromise = this.#profile.client + .getUnreadCount() + .then((res) => res.mentions + res.private_messages + res.replies) + .catch(() => 0) + + const reportsPromise = this.#profile.isMod() + ? this.#profile.client + .getReportCount({}) + .then( + (res) => + res.comment_reports + + res.post_reports + + (res.private_message_reports ?? 0), + ) + .catch(() => 0) + : Promise.resolve(0) + + const applicationsPromise = this.#profile.isAdmin + ? this.#profile.client + .getUnreadRegistrationApplicationCount() + .then((res) => res.registration_applications) + .catch(() => 0) + : Promise.resolve(0) + + const [unreads, reports, applications] = await Promise.all([ + unreadsPromise, + reportsPromise, + applicationsPromise, + ]) + + return { + inbox: unreads, + reports: reports, + applications: applications, + } + } +} diff --git a/src/lib/app/auth/index.ts b/src/lib/app/auth/index.ts new file mode 100644 index 00000000..ae412fd9 --- /dev/null +++ b/src/lib/app/auth/index.ts @@ -0,0 +1 @@ +export { profile, type ProfileInfo } from './profile.svelte' diff --git a/src/lib/app/auth.svelte.ts b/src/lib/app/auth/profile.svelte.ts similarity index 69% rename from src/lib/app/auth.svelte.ts rename to src/lib/app/auth/profile.svelte.ts index c61d9ef3..892542cc 100644 --- a/src/lib/app/auth.svelte.ts +++ b/src/lib/app/auth/profile.svelte.ts @@ -5,10 +5,11 @@ import { client, site } from '$lib/api/client.svelte' import type { Community, GetSiteResponse, MyUserInfo } from '$lib/api/types' import { publishedToDate } from '$lib/ui/util/date' import { toast } from 'mono-svelte' -import { errorMessage } from './error' -import { t } from './i18n' -import { DEFAULT_INSTANCE_URL } from './instance.svelte' -import { instanceToURL, moveItem } from './util.svelte' +import { errorMessage } from '../error' +import { t } from '../i18n' +import { DEFAULT_INSTANCE_URL } from '../instance.svelte' +import { instanceToURL, moveItem } from '../util.svelte' +import { InboxService } from './inbox.svelte' function getFromStorage(key: string): T | undefined { if (!browser) return @@ -18,9 +19,12 @@ function getFromStorage(key: string): T | undefined { return JSON.parse(lc) } -function setFromStorage(key: string, item: any, stringify: boolean = true) { +function setFromStorage(key: string, item: T, stringify: boolean = true) { if (!browser) return - return localStorage.setItem(key, stringify ? JSON.stringify(item) : item) + return localStorage.setItem( + key, + stringify ? JSON.stringify(item) : (item as string), + ) } export interface ProfileInfo { @@ -44,12 +48,6 @@ interface ProfileData { profile: number } -interface Notifications { - inbox: number - reports: number - applications: number -} - const getCookie = (key: string): string | undefined => { if (!browser) return undefined @@ -60,7 +58,7 @@ const getCookie = (key: string): string | undefined => { ?.split('=')?.[1] } -class Profile { +export class Profile { private static readonly DONATION_CHECK_TIMEOUT = 3 * 1000 private static readonly DONATION_REMINDER_INTERVAL = 375 * 24 * 60 * 60 * 1000 @@ -142,11 +140,10 @@ class Profile { private donationPoll(delay: number) { return setTimeout(() => { if ( - profile.current.user?.local_user_view.local_user - .last_donation_notification + this.current.user?.local_user_view.local_user.last_donation_notification ) { const donationDate = publishedToDate( - profile.current.user?.local_user_view.local_user + this.current.user?.local_user_view.local_user .last_donation_notification, ) if ( @@ -161,11 +158,11 @@ class Profile { // lemmy js client donation dialog is broken fetch( - `${instanceToURL(profile.current.instance)}/api/v3/user/donation_dialog_shown`, + `${instanceToURL(this.current.instance)}/api/v3/user/donation_dialog_shown`, { method: 'POST', headers: { - authorization: `Bearer ${profile.current.jwt}`, + authorization: `Bearer ${this.current.jwt}`, }, }, ) @@ -179,7 +176,7 @@ class Profile { if (this.#current.jwt) { site.data = undefined - const res = await userFromJwt( + const res = await fetchUserContext( this.#current.jwt, this.#current.instance, this.#current.client, @@ -199,7 +196,7 @@ class Profile { site.data = res?.site this.#current.user = res?.user - if (profile.current.user) { + if (this.current.user) { this.#current.avatar = res?.user?.local_user_view.person.avatar this.#current.username = res?.user?.local_user_view.person.name } @@ -218,7 +215,7 @@ class Profile { async add(jwt: string, instance: string, type: ClientType) { try { - const user = await userFromJwt(jwt, instance, type) + const user = await fetchUserContext(jwt, instance, type) if (!user?.user) { throw new Error('No user data received') } @@ -265,15 +262,13 @@ class Profile { } isMod(community?: Community): boolean { - if (community) - return ( - (this.#current.user?.moderates.some( - (i) => i.community.id == community.id, - ) || - (community.local && this.isAdmin)) ?? - false - ) - else return (this.#current.user?.moderates.length ?? 0) > 0 + if (!community) return (this.#current.user?.moderates.length ?? 0) > 0 + if (community.local && this.isAdmin) return true + return ( + this.#current.user?.moderates.some( + (m) => m.community.id === community.id, + ) ?? false + ) } get isAdmin(): boolean { @@ -311,93 +306,9 @@ class Profile { }) } -class InboxService { - private readonly POLL_INTERVAL = 4 * 60 * 1000 - #pollInterval: NodeJS.Timeout | null = null - - #profile: Profile - - notifications = $state({ - applications: 0, - inbox: 0, - reports: 0, - }) - - constructor(profile: Profile) { - this.#profile = profile - } - - async init(): Promise { - this.cleanup() - - this.notifications = await this.checkInbox() - - this.#pollInterval = setInterval(async () => { - this.notifications = await this.checkInbox() - }, this.POLL_INTERVAL) - } - - cleanup(): void { - if (this.#pollInterval) clearInterval(this.#pollInterval) - - this.#pollInterval = null - } - - clear(): Notifications { - this.notifications = { - applications: 0, - inbox: 0, - reports: 0, - } - return this.notifications - } - - async checkInbox(): Promise { - if (!this.#profile.current.user || !this.#profile.current.jwt) - return this.clear() - - const unreadsPromise = client() - .getUnreadCount() - .then((res) => res.mentions + res.private_messages + res.replies) - .catch(() => 0) - - const reportsPromise = this.#profile.isMod() - ? client() - .getReportCount({}) - .then( - (res) => - res.comment_reports + - res.post_reports + - (res.private_message_reports ?? 0), - ) - .catch(() => 0) - : new Promise((res) => res(0)) - - const applicationsPromise = this.#profile.isAdmin - ? client() - .getUnreadRegistrationApplicationCount() - .then((res) => res.registration_applications) - .catch(() => 0) - : new Promise((res) => res(0)) - - const [unreads, reports, applications] = await Promise.all([ - unreadsPromise, - reportsPromise, - applicationsPromise, - ]) - - return { - inbox: unreads, - reports: reports, - applications: applications, - } - } -} - export const profile = new Profile() -// this is all garbage legacy code, remove later -async function userFromJwt( +async function fetchUserContext( jwt: string, instance: string, type: ClientType, @@ -429,10 +340,8 @@ async function userFromJwt( if (!site) return - const myUser = site.my_user - return { - user: myUser, + user: site.my_user, site: site, } } diff --git a/src/lib/app/instance.svelte.ts b/src/lib/app/instance.svelte.ts index 5b0141b8..745fa91e 100644 --- a/src/lib/app/instance.svelte.ts +++ b/src/lib/app/instance.svelte.ts @@ -1,6 +1,6 @@ import { browser } from '$app/environment' import { env } from '$env/dynamic/public' -import { profile } from './auth.svelte' +import { profile } from './auth' class InstanceData { #instance = $derived(profile.current.instance) diff --git a/src/lib/app/util.svelte.ts b/src/lib/app/util.svelte.ts index d0b2c90b..4c2982df 100644 --- a/src/lib/app/util.svelte.ts +++ b/src/lib/app/util.svelte.ts @@ -1,5 +1,6 @@ import { browser } from '$app/environment' import { goto } from '$app/navigation' +import { env } from '$env/dynamic/public' import { client } from '$lib/api/client.svelte' import type { Community, Person } from '$lib/api/types' import { SvelteURL } from 'svelte/reactivity' @@ -26,6 +27,7 @@ export const searchParam = ( }) } +// why is this using SvelteURL brother export const fullCommunityName = (name: string, actorId: string) => `${name}@${new SvelteURL(actorId).hostname}` @@ -33,8 +35,8 @@ export const placeholders = { get: (type: 'url' | 'post' | 'body' | 'comment') => { switch (type) { case 'post': - return Math.random() < 0.01 - ? 'A C E C* B* G D E E F G F E D C E' + return Math.random() < 0.01 && env.PUBLIC_XYLIGHT_MODE + ? 'top 10 reasons why TCP is brilliant and UDP is a spawn of satan' : t.get('placeholders.title') case 'body': return t.get('placeholders.body') @@ -46,6 +48,8 @@ export const placeholders = { }, } +// lol this function was made 3 years ago when lil xylight +// was still learning cs export function moveItem( array: T[], currentIndex: number, @@ -62,10 +66,7 @@ export function moveItem( const newArray = [...array] - // Remove the item from the current index const [item] = newArray.splice(currentIndex, 1) - - // Insert the item at the new index newArray.splice(newIndex, 0, item) return newArray @@ -139,7 +140,6 @@ export function fuzzySearch(text: string, pattern: string): number { lastIndex = index } - // Bonus for matching start of words if (textLower.startsWith(patternLower)) { score += 2 } else if (textLower.includes(' ' + patternLower)) { @@ -167,6 +167,9 @@ export function snapshot(item: T) { return $state.snapshot(item) } +// these methods should really not exist +// instead we should use lemmy's url_content_type which +// gives us a mimetype (which is more reliable) export const isImage = (url: string | undefined) => { try { if (!url) return false diff --git a/src/lib/feature/comment/Comment.svelte b/src/lib/feature/comment/Comment.svelte index 3c739a67..a6c82a73 100644 --- a/src/lib/feature/comment/Comment.svelte +++ b/src/lib/feature/comment/Comment.svelte @@ -1,7 +1,7 @@ -

+
{#if meta}
@@ -68,7 +64,6 @@
{/if} import { site } from '$lib/api/client.svelte' import type { Comment } from '$lib/api/types' - import { profile } from '$lib/app/auth.svelte' + import { profile } from '$lib/app/auth' import { errorMessage } from '$lib/app/error' import { t } from '$lib/app/i18n' import { settings } from '$lib/app/settings.svelte' diff --git a/src/lib/feature/community/CommunityCard.svelte b/src/lib/feature/community/CommunityCard.svelte index 91ad8ec9..53bbd1ae 100644 --- a/src/lib/feature/community/CommunityCard.svelte +++ b/src/lib/feature/community/CommunityCard.svelte @@ -1,7 +1,7 @@ diff --git a/src/routes/accounts/+page.svelte b/src/routes/accounts/+page.svelte index 0976ed64..b33f4042 100644 --- a/src/routes/accounts/+page.svelte +++ b/src/routes/accounts/+page.svelte @@ -1,6 +1,6 @@