Files
gerbeur/api/routes/dumps.ts

271 lines
9.8 KiB
TypeScript

/**
* Posts, reads, edits and deletes dumps, for the feeds, the dump page, its
* edit page and the create form. `:dumpId` is a dump's id; the dump page reads
* a dump by its path, through `GET /api/users/:key/dumps/:slug`. A private
* dump answers 404 to anyone but its poster, moderators included. Its file and
* thumbnail are served by `routes/files.ts` and `routes/thumbnails.ts`, its
* comments by `routes/comments.ts`.
*
* - `POST /api/dumps` — signed in. Posts a link (JSON body) or a file
* (multipart `file`, with `title`, `comment`, `isPrivate` and `categoryIds`).
* - `GET /api/dumps?page=&limit=` — optional sign-in. Answers a page of the
* dumps the caller may see, newest first.
* - `GET /api/dumps?category=&page=&limit=` — optional sign-in. The same, in
* the category with that slug; 404 when there is none.
* - `GET /api/dumps?follow=users&category=&page=&limit=` — signed in. The
* index's "follow" tab: a page of the public dumps of the users the caller
* follows, newest first, optionally in one category.
* - `GET /api/dumps?follow=playlists&category=&page=&limit=` — signed in. Its
* `/follow/playlists` view: a page of the public dumps in the public
* playlists the caller follows, most recently added first.
* - `GET /api/dumps?url=` — optional sign-in. Answers the dumps already
* pointing at the same thing as `url`, for the create form's duplicate hint.
* - `GET /api/dumps/:dumpId` — optional sign-in. Answers a dump.
* - `GET /api/dumps/:dumpId/voters?page=&limit=` — optional sign-in. Answers a
* page of the users who upvoted it.
* - `GET /api/dumps/:dumpId/related` — optional sign-in. Answers the dumps
* linked to or from it.
* - `GET /api/dumps/:dumpId/playlists` — optional sign-in. Answers the
* playlists it appears in.
* - `PUT /api/dumps/:dumpId` — signed in, as its poster or with
* `dump:moderate`. Updates its title, slug, comment, visibility, categories,
* and a link's URL. A new slug keeps the old one as an alias, 3 times a day
* at most but for those with `dump:moderate`.
* - `POST /api/dumps/:dumpId/metadata` — signed in, as its poster or with
* `dump:moderate`. Fetches a link's preview again.
* - `DELETE /api/dumps/:dumpId` — signed in, as its poster or with
* `dump:moderate`. Deletes it.
*
* @module
*/
import { Router } from "@oak/oak";
import { type APIResponse, type PaginatedData } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type { Dump, DumpUrlMatch } from "../../shared/dump.ts";
import {
isCreateUrlDumpRequest,
isUpdateDumpRequest,
parseCategoryIds,
} from "../validators/dump.ts";
import type { Playlist } from "../../shared/playlist.ts";
import type { PublicUser } from "../../shared/user.ts";
import { toPublicUser } from "../model/user.ts";
import { authMiddleware } from "../middleware/auth.ts";
import { can } from "../lib/permissions.ts";
import { parseOptionalAuth } from "../lib/auth.ts";
import { type Page, parsePagination } from "../lib/pagination.ts";
import {
createFileDump,
createUrlDump,
deleteDump,
findDumpsByUrl,
getDump,
listDumps,
refreshDumpMetadata,
updateDump,
} from "../services/dump-service.ts";
import {
getCategoryBySlug,
listDumpsByCategory,
} from "../services/category-service.ts";
import {
getFollowedPlaylistsDumpFeed,
getFollowedUsersDumpFeed,
} from "../services/follow-service.ts";
import { FOLLOW_VIEWS, type FollowView } from "../../shared/paths.ts";
import { getDumpVoters } from "../services/vote-service.ts";
import { getRelatedDumps } from "../services/backlink-service.ts";
import { getPlaylistsForDump } from "../services/playlist-service.ts";
/**
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
* An `APIException` thrown by a handler becomes the JSON error response there.
*/
const router: Router = new Router({ prefix: "/api/dumps" });
// Each handler resolves `:dumpId` with getDump, which checks privacy, before
// acting on the dump.
router.post(
"/",
authMiddleware,
async (ctx) => {
const userId = ctx.state.user.userId;
const contentType = ctx.request.headers.get("content-type") ?? "";
let dump: Dump;
if (contentType.includes("multipart/form-data")) {
const formData = await ctx.request.body.formData();
const file = formData.get("file");
const comment = formData.get("comment");
const title = formData.get("title");
const isPrivate = formData.get("isPrivate") === "true";
if (!(file instanceof File)) {
throw new APIException(400, "A file is required");
}
dump = await createFileDump(
file,
typeof comment === "string" && comment ? comment : undefined,
userId,
isPrivate,
typeof title === "string" && title ? title : undefined,
parseCategoryIds(formData.get("categoryIds")),
);
} else {
const body: unknown = await ctx.request.body.json();
if (!isCreateUrlDumpRequest(body)) {
throw new APIException(400, "Invalid dump data");
}
dump = await createUrlDump(body, userId);
}
const responseBody: APIResponse<Dump> = { success: true, data: dump };
ctx.response.status = 201;
ctx.response.body = responseBody;
},
);
router.get("/:dumpId", async (ctx) => {
const requestingUserId = await parseOptionalAuth(ctx) ?? undefined;
const dump = getDump(ctx.params.dumpId, requestingUserId);
const responseBody: APIResponse<Dump> = { success: true, data: dump };
ctx.response.body = responseBody;
});
router.get("/:dumpId/voters", async (ctx) => {
const requestingUserId = await parseOptionalAuth(ctx) ?? undefined;
const dump = getDump(ctx.params.dumpId, requestingUserId);
const { page, limit } = parsePagination(ctx.request.url.searchParams);
const { items, hasMore } = getDumpVoters(dump.id, page, limit);
const responseBody: APIResponse<PaginatedData<PublicUser>> = {
success: true,
data: {
items: items.map(toPublicUser),
hasMore,
},
};
ctx.response.body = responseBody;
});
router.get("/:dumpId/related", async (ctx) => {
const requestingUserId = await parseOptionalAuth(ctx) ?? undefined;
const dump = getDump(ctx.params.dumpId, requestingUserId);
const related = getRelatedDumps(dump.id, requestingUserId);
const responseBody: APIResponse<Dump[]> = { success: true, data: related };
ctx.response.body = responseBody;
});
router.get("/:dumpId/playlists", async (ctx) => {
const requestingUserId = await parseOptionalAuth(ctx) ?? undefined;
const dump = getDump(ctx.params.dumpId, requestingUserId);
const playlists = getPlaylistsForDump(dump.id, requestingUserId);
const responseBody: APIResponse<Playlist[]> = {
success: true,
data: playlists,
};
ctx.response.body = responseBody;
});
router.get("/", async (ctx) => {
const requestingUserId = await parseOptionalAuth(ctx) ?? undefined;
const params = ctx.request.url.searchParams;
const url = params.get("url");
if (url !== null) {
const responseBody: APIResponse<DumpUrlMatch[]> = {
success: true,
data: findDumpsByUrl(url, requestingUserId),
};
ctx.response.body = responseBody;
return;
}
const { page, limit } = parsePagination(params);
const category = params.get("category");
const follow = params.get("follow");
let feed: Page<Dump>;
if (follow !== null) {
if (!requestingUserId) throw new APIException(401, "Missing token");
if (!(FOLLOW_VIEWS as readonly string[]).includes(follow)) {
throw new APIException(400, "follow must be users or playlists");
}
const categoryId = category
? getCategoryBySlug("dump", category).id
: undefined;
feed = (follow as FollowView) === "users"
? getFollowedUsersDumpFeed(requestingUserId, page, limit, categoryId)
: getFollowedPlaylistsDumpFeed(requestingUserId, page, limit, categoryId);
} else {
feed = category
? listDumpsByCategory(category, page, limit, requestingUserId)
: listDumps(page, limit, requestingUserId);
}
const { items, hasMore } = feed;
const responseBody: APIResponse<PaginatedData<Dump>> = {
success: true,
data: { items, hasMore },
};
ctx.response.body = responseBody;
});
router.put("/:dumpId", authMiddleware, async (ctx) => {
const dumpId = ctx.params.dumpId;
const userId = ctx.state.user.userId;
const body: unknown = await ctx.request.body.json();
if (!isUpdateDumpRequest(body)) {
throw new APIException(400, "Erroneous user input");
}
const dump = getDump(dumpId, userId);
if (userId !== dump.userId && !can(ctx.state.user, "dump:moderate")) {
throw new APIException(403, "Not authorized to update dump");
}
const updatedDump = await updateDump(
dump.id,
body,
can(ctx.state.user, "dump:moderate"),
);
const responseBody: APIResponse<Dump> = { success: true, data: updatedDump };
ctx.response.body = responseBody;
});
router.post("/:dumpId/metadata", authMiddleware, async (ctx) => {
const dumpId = ctx.params.dumpId;
const userId = ctx.state.user.userId;
const dump = getDump(dumpId, userId);
if (userId !== dump.userId && !can(ctx.state.user, "dump:moderate")) {
throw new APIException(403, "Not authorized to update dump");
}
const updatedDump = await refreshDumpMetadata(dump.id);
const responseBody: APIResponse<Dump> = { success: true, data: updatedDump };
ctx.response.body = responseBody;
});
router.delete("/:dumpId", authMiddleware, async (ctx) => {
const dumpId = ctx.params.dumpId;
const userId = ctx.state.user.userId;
const dump = getDump(dumpId, userId);
if (userId !== dump.userId && !can(ctx.state.user, "dump:moderate")) {
throw new APIException(403, "Not authorized to delete dump");
}
await deleteDump(dump.id);
const responseBody: APIResponse<null> = { success: true, data: null };
ctx.response.body = responseBody;
});
export default router;