83 lines
2.6 KiB
TypeScript
83 lines
2.6 KiB
TypeScript
/**
|
|
* Stores and serves the users' avatars. The profile page uploads the avatar,
|
|
* and the client's `Avatar` component loads it at the size it shows, with the
|
|
* user's `updatedAt` as a cache-busting version.
|
|
*
|
|
* - `PUT /api/me/avatar` — signed in. Replaces the caller's avatar (multipart
|
|
* `file`, at most 5 MB), sends `user_updated` to everyone, and answers the
|
|
* caller's user. 400 for an account from another instance, whose avatar
|
|
* comes from there. The instances the caller signed in to are told.
|
|
* - `GET /api/users/:key/avatar?w=` — public. Serves a user's avatar, scaled
|
|
* down to `w` (`shared/image.ts`) when it names one; 404 without one.
|
|
*
|
|
* @module
|
|
*/
|
|
|
|
import { Router } from "@oak/oak";
|
|
import { authMiddleware } from "../middleware/auth.ts";
|
|
import {
|
|
assertLocalUser,
|
|
getUserById,
|
|
resolveUserKey,
|
|
setUserAvatar,
|
|
} from "../services/user-service.ts";
|
|
import { type APIResponse } from "../../shared/api.ts";
|
|
import { APIException } from "../lib/api-exception.ts";
|
|
import type { SelfUser } from "../../shared/user.ts";
|
|
import { toSelfUser } from "../model/user.ts";
|
|
import { serveUploadedFile } from "../lib/upload.ts";
|
|
import { notifyClients } from "../services/identity-provider-service.ts";
|
|
import { AVATARS_DIR } from "../config.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();
|
|
|
|
router.put("/api/me/avatar", authMiddleware, async (ctx) => {
|
|
const authPayload = ctx.state.user;
|
|
const contentType = ctx.request.headers.get("content-type") ?? "";
|
|
if (!contentType.includes("multipart/form-data")) {
|
|
throw new APIException(400, "Expected multipart/form-data");
|
|
}
|
|
|
|
const body = await ctx.request.body.formData();
|
|
const file = body.get("file");
|
|
|
|
if (!(file instanceof File)) {
|
|
throw new APIException(400, "Missing file field");
|
|
}
|
|
|
|
assertLocalUser(getUserById(authPayload.userId));
|
|
const user = await setUserAvatar(
|
|
authPayload.userId,
|
|
new Uint8Array(await file.arrayBuffer()),
|
|
);
|
|
await notifyClients(user.id, { type: "update" });
|
|
const responseBody: APIResponse<SelfUser> = {
|
|
success: true,
|
|
data: toSelfUser(user),
|
|
};
|
|
ctx.response.body = responseBody;
|
|
});
|
|
|
|
router.get("/api/users/:key/avatar", async (ctx) => {
|
|
let user;
|
|
try {
|
|
user = resolveUserKey(ctx.params.key);
|
|
} catch {
|
|
ctx.response.status = 404;
|
|
return;
|
|
}
|
|
|
|
if (!user.avatarMime) {
|
|
ctx.response.status = 404;
|
|
return;
|
|
}
|
|
|
|
await serveUploadedFile(ctx, `${AVATARS_DIR}/${user.id}`, user.avatarMime);
|
|
});
|
|
|
|
export default router;
|