v3: follows, notifications, invite-only registration, unread markers

This commit is contained in:
khannurien
2026-03-21 18:42:47 +00:00
parent 7c098e7c4c
commit 608c6bc6a8
55 changed files with 4743 additions and 884 deletions

View File

@@ -31,14 +31,16 @@ router.get("/dumps/:dumpId/comments", async (ctx) => {
}
const dump = getDump(ctx.params.dumpId, requestingUserId);
const comments = getComments(dump.id);
const responseBody: APIResponse<Comment[]> = { success: true, data: comments };
const responseBody: APIResponse<Comment[]> = {
success: true,
data: comments,
};
ctx.response.body = responseBody;
});
// POST /api/dumps/:dumpId/comments — auth required
router.post("/dumps/:dumpId/comments", authMiddleware, async (ctx) => {
const userId = ctx.state.user.userId as string;
const isAdmin = (ctx.state.user.isAdmin ?? false) as boolean;
const dump = getDump(ctx.params.dumpId, userId);
const body = await ctx.request.body.json();
if (!isCreateCommentRequest(body)) {

View File

@@ -93,8 +93,17 @@ router.get("/", async (ctx) => {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const page = Math.max(1, parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1);
const limit = Math.min(Math.max(1, parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20), 100);
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const { items, total } = listDumps(page, limit, requestingUserId);
const responseBody: APIResponse<PaginatedData<Dump>> = {
success: true,

108
api/routes/follows.ts Normal file
View File

@@ -0,0 +1,108 @@
import { Router } from "@oak/oak";
import { authMiddleware } from "../middleware/auth.ts";
import {
type APIResponse,
type Dump,
type FollowStatus,
type PaginatedData,
} from "../model/interfaces.ts";
import {
followPlaylist,
followUser,
getFollowedPlaylistsDumpFeed,
getFollowedUsersDumpFeed,
getFollowStatus,
unfollowPlaylist,
unfollowUser,
} from "../services/follow-service.ts";
const router = new Router({ prefix: "/api/follows" });
// Static routes first to prevent Oak matching "status"/"feed" as a :param
// GET /api/follows/status
router.get("/status", authMiddleware, (ctx) => {
const status = getFollowStatus(ctx.state.user.userId as string);
const body: APIResponse<FollowStatus> = { success: true, data: status };
ctx.response.body = body;
});
// GET /api/follows/feed/users?page=&limit=
router.get("/feed/users", authMiddleware, (ctx) => {
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const { items, total } = getFollowedUsersDumpFeed(
ctx.state.user.userId as string,
page,
limit,
);
const data: PaginatedData<Dump> = {
items,
total,
hasMore: page * limit < total,
};
const body: APIResponse<PaginatedData<Dump>> = { success: true, data };
ctx.response.body = body;
});
// GET /api/follows/feed/playlists?page=&limit=
router.get("/feed/playlists", authMiddleware, (ctx) => {
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const { items, total } = getFollowedPlaylistsDumpFeed(
ctx.state.user.userId as string,
page,
limit,
);
const data: PaginatedData<Dump> = {
items,
total,
hasMore: page * limit < total,
};
const body: APIResponse<PaginatedData<Dump>> = { success: true, data };
ctx.response.body = body;
});
// POST /api/follows/users/:userId
router.post("/users/:userId", authMiddleware, (ctx) => {
followUser(ctx.state.user.userId as string, ctx.params.userId);
ctx.response.status = 204;
});
// DELETE /api/follows/users/:userId
router.delete("/users/:userId", authMiddleware, (ctx) => {
unfollowUser(ctx.state.user.userId as string, ctx.params.userId);
ctx.response.status = 204;
});
// POST /api/follows/playlists/:playlistId
router.post("/playlists/:playlistId", authMiddleware, (ctx) => {
followPlaylist(ctx.state.user.userId as string, ctx.params.playlistId);
ctx.response.status = 204;
});
// DELETE /api/follows/playlists/:playlistId
router.delete("/playlists/:playlistId", authMiddleware, (ctx) => {
unfollowPlaylist(ctx.state.user.userId as string, ctx.params.playlistId);
ctx.response.status = 204;
});
export default router;

32
api/routes/invites.ts Normal file
View File

@@ -0,0 +1,32 @@
import { Router } from "@oak/oak";
import { APIErrorCode, APIException } from "../model/interfaces.ts";
import { type AuthContext, authMiddleware } from "../middleware/auth.ts";
import { createInvite, validateInvite } from "../services/invite-service.ts";
const router = new Router({ prefix: "/api/invites" });
// Create a new invite link (any authenticated user)
router.post("/", authMiddleware, async (ctx: AuthContext) => {
if (!ctx.state.user) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Not authenticated");
}
const token = await createInvite(ctx.state.user.userId);
ctx.response.status = 201;
ctx.response.body = { success: true, data: { token } };
});
// Validate an invite token (used by the register page before showing the form)
router.get("/:token", async (ctx) => {
try {
await validateInvite(ctx.params.token);
ctx.response.body = { success: true };
} catch {
throw new APIException(
APIErrorCode.NOT_FOUND,
404,
"Invalid or expired invite",
);
}
});
export default router;

View File

@@ -0,0 +1,67 @@
import { Router } from "@oak/oak";
import {
APIErrorCode,
APIException,
type AuthPayload,
type PaginatedData,
} from "../model/interfaces.ts";
import { type AuthContext, authMiddleware } from "../middleware/auth.ts";
import {
getNotificationsForUser,
markAllRead,
markOneRead,
} from "../services/notification-service.ts";
const router = new Router({ prefix: "/api/notifications" });
// GET /api/notifications?page=N&limit=N
router.get("/", authMiddleware, (ctx: AuthContext) => {
if (!ctx.state.user) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Not authenticated");
}
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const { items, total } = getNotificationsForUser(
ctx.state.user.userId,
page,
limit,
);
ctx.response.body = {
success: true,
data: {
items,
total,
hasMore: page * limit < total,
} satisfies PaginatedData<typeof items[number]>,
};
});
// POST /api/notifications/read-all
router.post("/read-all", authMiddleware, (ctx: AuthContext) => {
if (!ctx.state.user) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Not authenticated");
}
markAllRead(ctx.state.user.userId);
ctx.response.status = 204;
});
// PATCH /api/notifications/:id/read
router.patch("/:id/read", authMiddleware, (ctx) => {
const user = ctx.state.user as AuthPayload;
if (!user) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Not authenticated");
}
markOneRead(ctx.params.id, user.userId);
ctx.response.status = 204;
});
export default router;

View File

@@ -15,52 +15,48 @@ import {
getUserById,
getUserByUsername,
} from "../services/user-service.ts";
import { redeemInvite, validateInvite } from "../services/invite-service.ts";
import {
getDumpsByUser,
getVotedDumpsByUser,
} from "../services/dump-service.ts";
import { listPlaylistsByUser } from "../services/playlist-service.ts";
import { getFollowedPlaylistsByUser } from "../services/follow-service.ts";
// Users router
const router = new Router({ prefix: "/api/users" });
// Register a new user
// Register a new user (requires a valid invite token)
router.post("/register", async (ctx) => {
try {
const body = await ctx.request.body.json();
if (!isRegisterUserRequest(body)) {
throw new APIException(
APIErrorCode.VALIDATION_ERROR,
400,
"Invalid request",
);
}
const user = await createUser(body);
const token = await createJWT({
userId: user.id,
username: user.username,
isAdmin: user.isAdmin,
});
ctx.response.status = 201;
ctx.response.body = {
success: true,
data: {
token,
user,
},
};
} catch (err) {
console.error(err);
const body = await ctx.request.body.json();
if (!isRegisterUserRequest(body)) {
throw new APIException(
APIErrorCode.SERVER_ERROR,
500,
"Failed to register user",
APIErrorCode.VALIDATION_ERROR,
400,
"Invalid request",
);
}
// Validate invite — throws 404/409 if bad
const inviterId = await validateInvite(body.inviteToken);
const user = await createUser(body, inviterId);
// Mark invite as used only after the user row is committed
redeemInvite(body.inviteToken);
const authToken = await createJWT({
userId: user.id,
username: user.username,
isAdmin: user.isAdmin,
});
ctx.response.status = 201;
ctx.response.body = {
success: true,
data: { token: authToken, user },
};
});
// Login
@@ -142,6 +138,31 @@ router.get("/by-id/:userId", (ctx) => {
ctx.response.body = { success: true, data: publicUser };
});
// Followed playlists for a user (public only)
router.get("/:username/followed-playlists", (ctx) => {
const user = getUserByUsername(ctx.params.username);
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const { items, total } = getFollowedPlaylistsByUser(user.id, page, limit);
ctx.response.body = {
success: true,
data: {
items,
total,
hasMore: page * limit < total,
} satisfies PaginatedData<typeof items[number]>,
};
});
// Playlists by user (optional auth: include private only if requester === owner)
router.get("/:username/playlists", async (ctx) => {
const user = getUserByUsername(ctx.params.username);
@@ -151,12 +172,30 @@ router.get("/:username/playlists", async (ctx) => {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const page = Math.max(1, parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1);
const limit = Math.min(Math.max(1, parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20), 100);
const { items, total } = listPlaylistsByUser(user.id, requestingUserId, page, limit);
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const { items, total } = listPlaylistsByUser(
user.id,
requestingUserId,
page,
limit,
);
ctx.response.body = {
success: true,
data: { items, total, hasMore: page * limit < total } satisfies PaginatedData<typeof items[number]>,
data: {
items,
total,
hasMore: page * limit < total,
} satisfies PaginatedData<typeof items[number]>,
};
});
@@ -176,13 +215,26 @@ router.get("/:username/dumps", async (ctx) => {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const page = Math.max(1, parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1);
const limit = Math.min(Math.max(1, parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20), 100);
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const includePrivate = requestingUserId === user.id;
const { items, total } = getDumpsByUser(user.id, page, limit, includePrivate);
ctx.response.body = {
success: true,
data: { items, total, hasMore: page * limit < total } satisfies PaginatedData<typeof items[number]>,
data: {
items,
total,
hasMore: page * limit < total,
} satisfies PaginatedData<typeof items[number]>,
};
});
@@ -195,12 +247,30 @@ router.get("/:username/votes", async (ctx) => {
const payload = await verifyJWT(authHeader.substring(7));
if (payload) requestingUserId = payload.userId;
}
const page = Math.max(1, parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1);
const limit = Math.min(Math.max(1, parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20), 100);
const { items, total } = getVotedDumpsByUser(user.id, page, limit, requestingUserId);
const page = Math.max(
1,
parseInt(ctx.request.url.searchParams.get("page") ?? "1") || 1,
);
const limit = Math.min(
Math.max(
1,
parseInt(ctx.request.url.searchParams.get("limit") ?? "20") || 20,
),
100,
);
const { items, total } = getVotedDumpsByUser(
user.id,
page,
limit,
requestingUserId,
);
ctx.response.body = {
success: true,
data: { items, total, hasMore: page * limit < total } satisfies PaginatedData<typeof items[number]>,
data: {
items,
total,
hasMore: page * limit < total,
} satisfies PaginatedData<typeof items[number]>,
};
});

View File

@@ -13,6 +13,7 @@ import {
getUserVotes,
removeVote,
} from "../services/vote-service.ts";
import { getUnreadCount } from "../services/notification-service.ts";
import { getUserById } from "../services/user-service.ts";
import { APIException } from "../model/interfaces.ts";
@@ -61,10 +62,14 @@ router.get("/ws", async (ctx) => {
try {
const myVotes = authPayload ? getUserVotes(authPayload.userId) : [];
const unreadNotificationCount = authPayload
? getUnreadCount(authPayload.userId)
: 0;
socket.send(JSON.stringify({
type: "welcome",
users: getOnlineUsers(),
myVotes,
unreadNotificationCount,
}));
} catch (err) {
console.error("[ws] welcome send failed:", err);