1
0

refactor mastodon API and preserve remote user agent for requests

This commit is contained in:
Hazelnoot
2025-03-20 20:43:05 -04:00
parent 92382b2ed4
commit f61d71ac8c
17 changed files with 1319 additions and 1447 deletions
@@ -3,92 +3,128 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { MiLocalUser } from '@/models/User.js';
import { Injectable } from '@nestjs/common';
import { MastodonClientService } from '@/server/api/mastodon/MastodonClientService.js';
import { getErrorData, MastodonLogger } from '@/server/api/mastodon/MastodonLogger.js';
import { MastoConverters } from '../converters.js';
import { parseTimelineArgs, TimelineArgs } from '../timelineArgs.js';
import { parseTimelineArgs, TimelineArgs } from '../argsUtils.js';
import Account = Entity.Account;
import Status = Entity.Status;
import type { MegalodonInterface } from 'megalodon';
import type { FastifyRequest } from 'fastify';
import type { FastifyInstance } from 'fastify';
export interface ApiSearchMastodonRoute {
interface ApiSearchMastodonRoute {
Querystring: TimelineArgs & {
type?: 'accounts' | 'hashtags' | 'statuses';
q?: string;
}
}
@Injectable()
export class ApiSearchMastodon {
constructor(
private readonly request: FastifyRequest<ApiSearchMastodonRoute>,
private readonly client: MegalodonInterface,
private readonly me: MiLocalUser | null,
private readonly BASE_URL: string,
private readonly mastoConverters: MastoConverters,
private readonly clientService: MastodonClientService,
private readonly logger: MastodonLogger,
) {}
public async SearchV1() {
if (!this.request.query.q) throw new Error('Missing required property "q"');
const query = parseTimelineArgs(this.request.query);
const data = await this.client.search(this.request.query.q, { type: this.request.query.type, ...query });
return data.data;
}
public register(fastify: FastifyInstance): void {
fastify.get<ApiSearchMastodonRoute>('/v1/search', async (_request, reply) => {
try {
if (!_request.query.q) return reply.code(400).send({ error: 'Missing required property "q"' });
public async SearchV2() {
if (!this.request.query.q) throw new Error('Missing required property "q"');
const query = parseTimelineArgs(this.request.query);
const type = this.request.query.type;
const acct = !type || type === 'accounts' ? await this.client.search(this.request.query.q, { type: 'accounts', ...query }) : null;
const stat = !type || type === 'statuses' ? await this.client.search(this.request.query.q, { type: 'statuses', ...query }) : null;
const tags = !type || type === 'hashtags' ? await this.client.search(this.request.query.q, { type: 'hashtags', ...query }) : null;
return {
accounts: await Promise.all(acct?.data.accounts.map(async (account: Account) => await this.mastoConverters.convertAccount(account)) ?? []),
statuses: await Promise.all(stat?.data.statuses.map(async (status: Status) => await this.mastoConverters.convertStatus(status, this.me)) ?? []),
hashtags: tags?.data.hashtags ?? [],
};
}
const query = parseTimelineArgs(_request.query);
const client = this.clientService.getClient(_request);
const data = await client.search(_request.query.q, { type: _request.query.type, ...query });
public async getStatusTrends() {
const data = await fetch(`${this.BASE_URL}/api/notes/featured`,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
i: this.request.headers.authorization?.replace('Bearer ', ''),
}),
})
.then(res => res.json() as Promise<Status[]>)
.then(data => data.map(status => this.mastoConverters.convertStatus(status, this.me)));
return Promise.all(data);
}
reply.send(data.data);
} catch (e) {
const data = getErrorData(e);
this.logger.error('GET /v1/search', data);
reply.code(401).send(data);
}
});
public async getSuggestions() {
const data = await fetch(`${this.BASE_URL}/api/users`,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
i: this.request.headers.authorization?.replace('Bearer ', ''),
limit: parseTimelineArgs(this.request.query).limit ?? 20,
origin: 'local',
sort: '+follower',
state: 'alive',
}),
})
.then(res => res.json() as Promise<Account[]>)
.then(data => data.map((entry => ({
source: 'global',
account: entry,
}))));
return Promise.all(data.map(async suggestion => {
suggestion.account = await this.mastoConverters.convertAccount(suggestion.account);
return suggestion;
}));
fastify.get<ApiSearchMastodonRoute>('/v2/search', async (_request, reply) => {
try {
if (!_request.query.q) return reply.code(400).send({ error: 'Missing required property "q"' });
const query = parseTimelineArgs(_request.query);
const type = _request.query.type;
const { client, me } = await this.clientService.getAuthClient(_request);
const acct = !type || type === 'accounts' ? await client.search(_request.query.q, { type: 'accounts', ...query }) : null;
const stat = !type || type === 'statuses' ? await client.search(_request.query.q, { type: 'statuses', ...query }) : null;
const tags = !type || type === 'hashtags' ? await client.search(_request.query.q, { type: 'hashtags', ...query }) : null;
const response = {
accounts: await Promise.all(acct?.data.accounts.map(async (account: Account) => await this.mastoConverters.convertAccount(account)) ?? []),
statuses: await Promise.all(stat?.data.statuses.map(async (status: Status) => await this.mastoConverters.convertStatus(status, me)) ?? []),
hashtags: tags?.data.hashtags ?? [],
};
reply.send(response);
} catch (e) {
const data = getErrorData(e);
this.logger.error('GET /v2/search', data);
reply.code(401).send(data);
}
});
fastify.get<ApiSearchMastodonRoute>('/v1/trends/statuses', async (_request, reply) => {
try {
const baseUrl = this.clientService.getBaseUrl(_request);
const res = await fetch(`${baseUrl}/api/notes/featured`,
{
method: 'POST',
headers: {
..._request.headers as HeadersInit,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: '{}',
});
const data = await res.json() as Status[];
const me = await this.clientService.getAuth(_request);
const response = await Promise.all(data.map(status => this.mastoConverters.convertStatus(status, me)));
reply.send(response);
} catch (e) {
const data = getErrorData(e);
this.logger.error('GET /v1/trends/statuses', data);
reply.code(401).send(data);
}
});
fastify.get<ApiSearchMastodonRoute>('/v2/suggestions', async (_request, reply) => {
try {
const baseUrl = this.clientService.getBaseUrl(_request);
const res = await fetch(`${baseUrl}/api/users`,
{
method: 'POST',
headers: {
..._request.headers as HeadersInit,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
limit: parseTimelineArgs(_request.query).limit ?? 20,
origin: 'local',
sort: '+follower',
state: 'alive',
}),
});
const data = await res.json() as Account[];
const response = await Promise.all(data.map(async entry => {
return {
source: 'global',
account: await this.mastoConverters.convertAccount(entry),
};
}));
reply.send(response);
} catch (e) {
const data = getErrorData(e);
this.logger.error('GET /v2/suggestions', data);
reply.code(401).send(data);
}
});
}
}