[mastodon-client] GET /timelines/public

This commit is contained in:
Laura Hausmann 2023-09-15 16:40:25 +02:00
parent f747d6b8c1
commit b8cbcafe3a
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
2 changed files with 129 additions and 65 deletions

View file

@ -45,6 +45,8 @@ export function argsToBools(q: ParsedUrlQuery) {
if (typeof q.pinned === "string") object.pinned = toBoolean(q.pinned); if (typeof q.pinned === "string") object.pinned = toBoolean(q.pinned);
if (q.local) if (q.local)
if (typeof q.local === "string") object.local = toBoolean(q.local); if (typeof q.local === "string") object.local = toBoolean(q.local);
if (q.remote)
if (typeof q.local === "string") object.local = toBoolean(q.local);
return q; return q;
} }
@ -70,20 +72,20 @@ export function normalizeUrlQuery(q: ParsedUrlQuery): any {
export function apiTimelineMastodon(router: Router): void { export function apiTimelineMastodon(router: Router): void {
router.get("/v1/timelines/public", async (ctx, reply) => { router.get("/v1/timelines/public", async (ctx, reply) => {
const BASE_URL = `${ctx.protocol}://${ctx.hostname}`;
const accessTokens = ctx.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try { try {
const query: any = ctx.query; const auth = await authenticate(ctx.headers.authorization, null);
const data = const user = auth[0] ?? undefined;
query.local === "true"
? await client.getLocalTimeline( if (!user) {
convertTimelinesArgsId(argsToBools(limitToInt(query))), ctx.status = 401;
) return;
: await client.getPublicTimeline( }
convertTimelinesArgsId(argsToBools(limitToInt(query))),
); const args = normalizeUrlQuery(convertTimelinesArgsId(argsToBools(limitToInt(ctx.query))));
ctx.body = data.data.map((status) => convertStatus(status)); const tl = await TimelineHelpers.getPublicTimeline(user, args.max_id, args.since_id, args.min_id, args.limit, args.only_media, args.local, args.remote)
.then(n => NoteConverter.encodeMany(n, user));
ctx.body = tl.map(s => convertStatus(s));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);

View file

@ -2,7 +2,7 @@ import { Note } from "@/models/entities/note.js";
import { ILocalUser } from "@/models/entities/user.js"; import { ILocalUser } from "@/models/entities/user.js";
import { Followings, Notes } from "@/models/index.js"; import { Followings, Notes } from "@/models/index.js";
import { makePaginationQuery } from "@/server/api/common/make-pagination-query.js"; import { makePaginationQuery } from "@/server/api/common/make-pagination-query.js";
import { Brackets } from "typeorm"; import { Brackets, SelectQueryBuilder } from "typeorm";
import { generateChannelQuery } from "@/server/api/common/generate-channel-query.js"; import { generateChannelQuery } from "@/server/api/common/generate-channel-query.js";
import { generateRepliesQuery } from "@/server/api/common/generate-replies-query.js"; import { generateRepliesQuery } from "@/server/api/common/generate-replies-query.js";
import { generateVisibilityQuery } from "@/server/api/common/generate-visibility-query.js"; import { generateVisibilityQuery } from "@/server/api/common/generate-visibility-query.js";
@ -10,7 +10,35 @@ import { generateMutedUserQuery } from "@/server/api/common/generate-muted-user-
import { generateMutedNoteQuery } from "@/server/api/common/generate-muted-note-query.js"; import { generateMutedNoteQuery } from "@/server/api/common/generate-muted-note-query.js";
import { generateBlockedUserQuery } from "@/server/api/common/generate-block-query.js"; import { generateBlockedUserQuery } from "@/server/api/common/generate-block-query.js";
import { generateMutedUserRenotesQueryForNotes } from "@/server/api/common/generated-muted-renote-query.js"; import { generateMutedUserRenotesQueryForNotes } from "@/server/api/common/generated-muted-renote-query.js";
import { fetchMeta } from "@/misc/fetch-meta.js";
import { ApiError } from "@/server/api/error.js";
import { meta } from "@/server/api/endpoints/notes/global-timeline.js";
export class TimelineHelpers { export class TimelineHelpers {
private static async execQuery(query: SelectQueryBuilder<Note>, limit: number): Promise<Note[]> {
// We fetch more than requested because some may be filtered out, and if there's less than
// requested, the pagination stops.
const found = [];
const take = Math.floor(limit * 1.5);
let skip = 0;
try {
while (found.length < limit) {
const notes = await query.take(take).skip(skip).getMany();
found.push(...notes);
skip += take;
if (notes.length < take) break;
}
} catch (error) {
return [];
}
if (found.length > limit) {
found.length = limit;
}
return found;
}
public static async getHomeTimeline(user: ILocalUser, maxId?: string, sinceId?: string, minId?: string, limit: number = 20): Promise<Note[]> { public static async getHomeTimeline(user: ILocalUser, maxId?: string, sinceId?: string, minId?: string, limit: number = 20): Promise<Note[]> {
if (limit > 40) limit = 40; if (limit > 40) limit = 40;
@ -24,7 +52,7 @@ export class TimelineHelpers {
const followingQuery = Followings.createQueryBuilder("following") const followingQuery = Followings.createQueryBuilder("following")
.select("following.followeeId") .select("following.followeeId")
.where("following.followerId = :followerId", { followerId: user.id }); .where("following.followerId = :followerId", {followerId: user.id});
//FIXME respect minId //FIXME respect minId
const query = makePaginationQuery( const query = makePaginationQuery(
@ -34,7 +62,7 @@ export class TimelineHelpers {
) )
.andWhere( .andWhere(
new Brackets((qb) => { new Brackets((qb) => {
qb.where("note.userId = :meId", { meId: user.id }); qb.where("note.userId = :meId", {meId: user.id});
if (hasFollowing) if (hasFollowing)
qb.orWhere(`note.userId IN (${followingQuery.getQuery()})`); qb.orWhere(`note.userId IN (${followingQuery.getQuery()})`);
}), }),
@ -62,26 +90,60 @@ export class TimelineHelpers {
query.andWhere("note.visibility != 'hidden'"); query.andWhere("note.visibility != 'hidden'");
// We fetch more than requested because some may be filtered out, and if there's less than return this.execQuery(query, limit);
// requested, the pagination stops.
const found = [];
const take = Math.floor(limit * 1.5);
let skip = 0;
try {
while (found.length < limit) {
const notes = await query.take(take).skip(skip).getMany();
found.push(...notes);
skip += take;
if (notes.length < take) break;
}
} catch (error) {
return [];
} }
if (found.length > limit) { public static async getPublicTimeline(user: ILocalUser, maxId?: string, sinceId?: string, minId?: string, limit: number = 20, onlyMedia: boolean = false, local: boolean = false, remote: boolean = false): Promise<Note[]> {
found.length = limit; if (limit > 40) limit = 40;
const m = await fetchMeta();
if (m.disableGlobalTimeline) {
if (user == null || !(user.isAdmin || user.isModerator)) {
throw new ApiError(meta.errors.gtlDisabled);
}
} }
return found; if (local && remote) {
throw new Error("local and remote are mutually exclusive options");
}
//FIXME respect minId
const query = makePaginationQuery(
Notes.createQueryBuilder("note"),
sinceId ?? minId,
maxId,
)
.andWhere("note.visibility = 'public'");
if (remote) query.andWhere("note.userHost IS NOT NULL");
if (local) query.andWhere("note.userHost IS NULL");
if (!local) query.andWhere("note.channelId IS NULL");
query
.innerJoinAndSelect("note.user", "user")
.leftJoinAndSelect("user.avatar", "avatar")
.leftJoinAndSelect("user.banner", "banner")
.leftJoinAndSelect("note.reply", "reply")
.leftJoinAndSelect("note.renote", "renote")
.leftJoinAndSelect("reply.user", "replyUser")
.leftJoinAndSelect("replyUser.avatar", "replyUserAvatar")
.leftJoinAndSelect("replyUser.banner", "replyUserBanner")
.leftJoinAndSelect("renote.user", "renoteUser")
.leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar")
.leftJoinAndSelect("renoteUser.banner", "renoteUserBanner");
generateRepliesQuery(query, true, user);
if (user) {
generateMutedUserQuery(query, user);
generateMutedNoteQuery(query, user);
generateBlockedUserQuery(query, user);
generateMutedUserRenotesQueryForNotes(query, user);
}
if (onlyMedia) query.andWhere("note.fileIds != '{}'");
query.andWhere("note.visibility != 'hidden'");
return this.execQuery(query, limit);
} }
} }