[mastodon-client] GET /accounts/:id/following

This commit is contained in:
Laura Hausmann 2023-09-24 19:19:57 +02:00
parent c86ab31a29
commit 97067648e8
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
3 changed files with 54 additions and 27 deletions

View file

@ -9,6 +9,7 @@ import authenticate from "@/server/api/authenticate.js";
import { NoteConverter } from "@/server/api/mastodon/converters/note.js";
import { UserHelpers } from "@/server/api/mastodon/helpers/user.js";
import config from "@/config/index.js";
import { PaginationHelpers } from "@/server/api/mastodon/helpers/pagination.js";
const relationshipModel = {
id: "",
@ -202,20 +203,7 @@ export function apiAccountMastodon(router: Router): void {
const followers = await UserConverter.encodeMany(res.data, cache);
ctx.body = followers.map((account) => convertAccount(account));
const link: string[] = [];
const limit = args.limit ?? 40;
if (res.maxId) {
const l = `<${config.url}/api/v1/accounts/${ctx.params.id}/followers?limit=${limit}&max_id=${convertId(res.maxId, IdType.MastodonId)}>; rel="next"`;
link.push(l);
}
if (res.minId) {
const l = `<${config.url}/api/v1/accounts/${ctx.params.id}/followers?limit=${limit}&min_id=${convertId(res.minId, IdType.MastodonId)}>; rel="prev"`;
link.push(l);
}
if (link.length > 0){
ctx.response.append('Link', link.join(', '));
}
PaginationHelpers.appendLinkPaginationHeader(args, ctx, res, `accounts/${ctx.params.id}/followers`);
} catch (e: any) {
console.error(e);
console.error(e.response.data);
@ -227,15 +215,20 @@ export function apiAccountMastodon(router: Router): void {
router.get<{ Params: { id: string } }>(
"/v1/accounts/:id/following",
async (ctx) => {
const BASE_URL = `${ctx.protocol}://${ctx.hostname}`;
const accessTokens = ctx.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.getAccountFollowing(
convertId(ctx.params.id, IdType.IceshrimpId),
convertTimelinesArgsId(limitToInt(ctx.query as any)),
);
ctx.body = data.data.map((account) => convertAccount(account));
const auth = await authenticate(ctx.headers.authorization, null);
const user = auth[0] ?? null;
const userId = convertId(ctx.params.id, IdType.IceshrimpId);
const cache = UserHelpers.getFreshAccountCache();
const query = await UserHelpers.getUserCached(userId, cache);
const args = normalizeUrlQuery(convertTimelinesArgsId(limitToInt(ctx.query as any)));
const res = await UserHelpers.getUserFollowing(query, user, args.max_id, args.since_id, args.min_id, args.limit);
const following = await UserConverter.encodeMany(res.data, cache);
ctx.body = following.map((account) => convertAccount(account));
PaginationHelpers.appendLinkPaginationHeader(args, ctx, res, `accounts/${ctx.params.id}/following`);
} catch (e: any) {
console.error(e);
console.error(e.response.data);

View file

@ -1,4 +1,6 @@
import { ObjectLiteral, SelectQueryBuilder } from "typeorm";
import config from "@/config/index.js";
import { convertId, IdType } from "../../index.js";
export class PaginationHelpers {
public static makePaginationQuery<T extends ObjectLiteral>(
@ -31,4 +33,20 @@ export class PaginationHelpers {
}
return q;
}
public static appendLinkPaginationHeader(args: any, ctx: any, res: any, route: string): void {
const link: string[] = [];
const limit = args.limit ?? 40;
if (res.maxId) {
const l = `<${config.url}/api/v1/${route}?limit=${limit}&max_id=${convertId(res.maxId, IdType.MastodonId)}>; rel="next"`;
link.push(l);
}
if (res.minId) {
const l = `<${config.url}/api/v1/${route}?limit=${limit}&min_id=${convertId(res.minId, IdType.MastodonId)}>; rel="prev"`;
link.push(l);
}
if (link.length > 0){
ctx.response.append('Link', link.join(', '));
}
}
}

View file

@ -24,6 +24,8 @@ export type LinkPaginationObject<T> = {
minId?: string | undefined;
}
type RelationshipType = 'followers' | 'following';
export class UserHelpers {
public static async getUserStatuses(user: User, localUser: ILocalUser | null, maxId: string | undefined, sinceId: string | undefined, minId: string | undefined, limit: number = 20, onlyMedia: boolean = false, excludeReplies: boolean = false, excludeReblogs: boolean = false, pinned: boolean = false, tagged: string | undefined): Promise<Note[]> {
if (limit > 40) limit = 40;
@ -76,7 +78,7 @@ export class UserHelpers {
return NoteHelpers.execQuery(query, limit, minId !== undefined);
}
public static async getUserFollowers(user: User, localUser: ILocalUser | null, maxId: string | undefined, sinceId: string | undefined, minId: string | undefined, limit: number = 40): Promise<LinkPaginationObject<User[]>> {
private static async getUserRelationships(type: RelationshipType, user: User, localUser: ILocalUser | null, maxId: string | undefined, sinceId: string | undefined, minId: string | undefined, limit: number = 40): Promise<LinkPaginationObject<User[]>> {
if (limit > 80) limit = 80;
const profile = await UserProfiles.findOneByOrFail({ userId: user.id });
@ -99,21 +101,35 @@ export class UserHelpers {
sinceId,
maxId,
minId
)
.andWhere("following.followeeId = :userId", { userId: user.id })
.innerJoinAndSelect("following.follower", "follower");
);
if (type === "followers") {
query.andWhere("following.followeeId = :userId", {userId: user.id})
.innerJoinAndSelect("following.follower", "follower");
} else {
query.andWhere("following.followerId = :userId", {userId: user.id})
.innerJoinAndSelect("following.followee", "followee");
}
return query.take(limit).getMany().then(p => {
if (minId !== undefined) p = p.reverse();
return {
data: p.map(p => p.follower).filter(p => p) as User[],
data: p.map(p => type === "followers" ? p.follower : p.followee).filter(p => p) as User[],
maxId: p.map(p => p.id).at(-1),
minId: p.map(p => p.id)[0],
};
});
}
public static async getUserFollowers(user: User, localUser: ILocalUser | null, maxId: string | undefined, sinceId: string | undefined, minId: string | undefined, limit: number = 40): Promise<LinkPaginationObject<User[]>> {
return this.getUserRelationships('followers', user, localUser, maxId, sinceId, minId, limit);
}
public static async getUserFollowing(user: User, localUser: ILocalUser | null, maxId: string | undefined, sinceId: string | undefined, minId: string | undefined, limit: number = 40): Promise<LinkPaginationObject<User[]>> {
return this.getUserRelationships('following', user, localUser, maxId, sinceId, minId, limit);
}
public static async getUserCached(id: string, cache: AccountCache = UserHelpers.getFreshAccountCache()): Promise<User> {
return cache.locks.acquire(id, async () => {
const cacheHit = cache.users.find(p => p.id == id);