5 Commits
Author SHA1 Message Date
chrisandClaude Opus 5.5 2025225fe4 Version 1.3.0
Android / build (push) Successful in 14m50s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Y2iUsKEWDuRGjK5FPmcUP
2026-10-15 13:33:10 -04:00
chrisandClaude Opus 5.5 4402171f46 Comments on plays
- Anyone who can see a play can read its comments; the player and the people they follow can write.
  The author, the player and admins can delete; comments can be reported (admins see the text).
- Notifications: "commented on" for the player, "replied on" for earlier commenters, each with its
  own setting. Reaction and comment notifications now open the play.
- A 💬 chip with the count next to reactions on the feed and recent plays, opening the thread on
  the app (/play/[id]) and the website. Threads refresh every few seconds while open.
- Blocking removes comments between the two people. Plays with comments survive history trimming.
- Privacy page updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Y2iUsKEWDuRGjK5FPmcUP
2026-10-15 13:32:14 -04:00
chrisandClaude Opus 5.5 31aed8dec4 Fix profile picture uploads from the app
Expo's fetch rejects React Native's { uri, name, type } FormData parts ("Unsupported FormDataPart
implementation"), so every upload failed. Upload an expo-file-system File instead, shrunk to 1024 px
first. The server also takes bigger photos (25 MB, sharp's default pixel limit) and logs why a
picture couldn't be read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Y2iUsKEWDuRGjK5FPmcUP
2026-10-15 13:20:12 -04:00
chrisandClaude Opus 5.5 b705bfcce4 Fix a gap under Friends listening, and lyrics failing while LRCLIB's exact lookup is overloaded
The feed's itemLayoutAnimation left the cards behind when the header above them shrank
(your own card's lyrics loading). LRCLIB rate-limits /api/get on its own; fall back to search.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Y2iUsKEWDuRGjK5FPmcUP
2026-10-15 13:16:18 -04:00
chrisandClaude Opus 5.5 82ff5336aa CI: no error message when a tag has no release yet
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:02:28 -04:00
45 changed files with 2924 additions and 58 deletions
+1 -1
View File
@@ -94,7 +94,7 @@ jobs:
auth="Authorization: token $TOKEN"
if [ "$REF_TYPE" = tag ]; then
# Reuse the release if this tag was built before.
id=$(curl -fsS -H "$auth" "$api/releases/tags/$REF_NAME" 2>/dev/null | node -p 'JSON.parse(require("fs").readFileSync(0)).id' || true)
id=$(curl -fsS -H "$auth" "$api/releases/tags/$REF_NAME" 2>/dev/null | node -p 'JSON.parse(require("fs").readFileSync(0, "utf8") || "{}").id ?? ""' || true)
if [ -z "$id" ]; then
# The changelog first (the app shows the text above "---" as what's new), then a note for this page.
body=$(node -e '
+16
View File
@@ -0,0 +1,16 @@
CREATE TABLE "comments" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"listen_id" uuid NOT NULL,
"user_id" uuid NOT NULL,
"body" varchar(500) NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "notifications" ADD COLUMN "comment_id" uuid;--> statement-breakpoint
ALTER TABLE "reports" ADD COLUMN "comment_id" uuid;--> statement-breakpoint
ALTER TABLE "reports" ADD COLUMN "comment_body" varchar(500);--> statement-breakpoint
ALTER TABLE "comments" ADD CONSTRAINT "comments_listen_id_listens_id_fk" FOREIGN KEY ("listen_id") REFERENCES "public"."listens"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "comments" ADD CONSTRAINT "comments_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "comments_listen_created_idx" ON "comments" USING btree ("listen_id","created_at");--> statement-breakpoint
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_comment_id_comments_id_fk" FOREIGN KEY ("comment_id") REFERENCES "public"."comments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "reports" ADD CONSTRAINT "reports_comment_id_comments_id_fk" FOREIGN KEY ("comment_id") REFERENCES "public"."comments"("id") ON DELETE set null ON UPDATE no action;
File diff suppressed because it is too large Load Diff
+7
View File
@@ -120,6 +120,13 @@
"when": 1792028149643,
"tag": "0016_notifications",
"breakpoints": true
},
{
"idx": 17,
"version": "7",
"when": 1792084480262,
"tag": "0017_comments",
"breakpoints": true
}
]
}
+2
View File
@@ -12,6 +12,7 @@ import { HttpError } from './lib/http';
import { redis } from './lib/redis';
import { adminRoutes } from './routes/admin';
import { appUpdateRoutes } from './routes/appUpdates';
import { commentRoutes } from './routes/comments';
import { accountRoutes } from './routes/account';
import { authRoutes } from './routes/auth';
import { avatarRoutes } from './routes/avatars';
@@ -78,6 +79,7 @@ export async function buildApp({ logger = true, rateLimits = true }: { logger?:
await app.register(adminRoutes);
await app.register(trackRoutes);
await app.register(reactionRoutes);
await app.register(commentRoutes);
await app.register(notificationRoutes);
await app.register(connectionRoutes);
await app.register(deviceRoutes);
+25 -3
View File
@@ -105,6 +105,9 @@ export const reports = pgTable(
.references(() => users.id, { onDelete: 'cascade' }),
reason: text('reason').$type<ReportReason>().notNull(),
note: varchar('note', { length: 500 }),
/** When a comment was reported: which, and what it said then (kept if the comment is deleted). */
commentId: uuid('comment_id').references(() => comments.id, { onDelete: 'set null' }),
commentBody: varchar('comment_body', { length: 500 }),
status: text('status').$type<'open' | 'resolved'>().notNull().default('open'),
createdAt: createdAt(),
},
@@ -262,6 +265,23 @@ export const reactions = pgTable(
(t) => [primaryKey({ columns: [t.listenId, t.userId] })],
);
/** Comments on a play. They go with the play (plays with comments are kept when history is trimmed). */
export const comments = pgTable(
'comments',
{
id: uuid('id').primaryKey().defaultRandom(),
listenId: uuid('listen_id')
.notNull()
.references(() => listens.id, { onDelete: 'cascade' }),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
body: varchar('body', { length: 500 }).notNull(),
createdAt: createdAt(),
},
(t) => [index('comments_listen_created_idx').on(t.listenId, t.createdAt)],
);
/** Email confirmation links (sign-up and email changes). Only a hash of the token is stored. */
export const emailVerifications = pgTable(
'email_verifications',
@@ -306,7 +326,7 @@ export const lyrics = pgTable('lyrics', {
fetchedAt: timestamp('fetched_at', { withTimezone: true }).notNull().defaultNow(),
});
/** Things that happened to a user: a reaction, a new follower, a song sent to them. */
/** Things that happened to a user: a reaction or comment, a new follower, a song sent to them. */
export const notifications = pgTable(
'notifications',
{
@@ -319,10 +339,12 @@ export const notifications = pgTable(
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
trackId: uuid('track_id').references(() => tracks.id, { onDelete: 'cascade' }),
/** The play a reaction was on (gone once the play is trimmed from history). */
/** The play a reaction or comment was on (gone once the play is trimmed from history). */
listenId: uuid('listen_id').references(() => listens.id, { onDelete: 'set null' }),
/** The comment (or reply); deleting the comment takes its notifications with it. */
commentId: uuid('comment_id').references(() => comments.id, { onDelete: 'cascade' }),
emoji: varchar('emoji', { length: 32 }),
/** A note sent with a song. */
/** A note sent with a song, or the start of a comment. */
message: varchar('message', { length: 280 }),
readAt: timestamp('read_at', { withTimezone: true }),
createdAt: createdAt(),
+7 -4
View File
@@ -3,7 +3,8 @@ import { env } from '../env';
import { HttpError } from './http';
export const AVATAR_SIZE = 512;
export const AVATAR_MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
/** Full-size photos from 50-200 MP phone cameras can be well over 10 MB (the app shrinks them first since 1.3.0). */
export const AVATAR_MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
/**
* Uploaded avatars are stored as a path (`/avatars/<id>?v=<version>`) so they keep
@@ -16,14 +17,16 @@ export const publicAvatarUrl = (stored: string | null): string | null =>
* Square-crops, resizes and re-encodes to WebP. Re-encoding also drops EXIF
* (phone photos carry GPS location) and anything that isn't image data.
*/
export async function processAvatar(input: Buffer): Promise<Buffer> {
export async function processAvatar(input: Buffer, log?: (err: unknown) => void): Promise<Buffer> {
try {
return await sharp(input, { limitInputPixels: 50_000_000, animated: false })
// sharp's default pixel limit (~268 MP) fits a 200 MP camera; JPEGs are shrunk while decoding, so it stays cheap.
return await sharp(input, { animated: false })
.rotate() // apply the EXIF orientation before it's stripped
.resize(AVATAR_SIZE, AVATAR_SIZE, { fit: 'cover', position: 'attention' })
.webp({ quality: 82 })
.toBuffer();
} catch {
} catch (err) {
log?.(err);
throw new HttpError(400, "That file isn't an image we can read. Try a JPEG, PNG, WebP or HEIC.");
}
}
+1
View File
@@ -40,6 +40,7 @@ export async function adminRoutes(app: FastifyInstance) {
createdAt: report.createdAt.toISOString(),
reporter: by ? toUserSummary(by) : null,
reported: { ...toUserSummary(who), suspended: Boolean(who.suspendedAt) },
comment: report.commentBody ? { id: report.commentId, body: report.commentBody } : null,
}));
});
+4 -2
View File
@@ -14,9 +14,11 @@ export async function avatarRoutes(app: FastifyInstance) {
const file = await req.file({ limits: { fileSize: AVATAR_MAX_UPLOAD_BYTES, files: 1 } }).catch(() => undefined);
if (!file) throw new HttpError(400, 'Choose a picture to upload');
const input = await file.toBuffer().catch(() => {
throw new HttpError(413, 'That picture is too big (10 MB max)');
throw new HttpError(413, `That picture is too big (${AVATAR_MAX_UPLOAD_BYTES / 1024 / 1024} MB max)`);
});
const image = await processAvatar(input);
const image = await processAvatar(input, (err) =>
req.log.warn({ err, bytes: input.length, mimetype: file.mimetype, filename: file.filename }, 'avatar not readable'),
);
const values = { image, contentType: 'image/webp', updatedAt: new Date() };
await db
+163
View File
@@ -0,0 +1,163 @@
import { and, asc, eq, inArray, isNull, ne, or } from 'drizzle-orm';
import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import { commentSchema, reportSchema, type CommentDTO, type CommentThreadDTO } from '@musicshare/shared';
import { db, schema } from '../db';
import type { User } from '../db/schema';
import { requireUser } from '../lib/auth';
import { HttpError } from '../lib/http';
import { blockStatus, hiddenUserIds } from '../services/blocks';
import { notify } from '../services/notifications';
import { getReactions, publishNowPlaying, toUserSummary } from '../services/nowPlaying';
import { getTrackDTOs } from '../services/tracks';
const params = z.object({ id: z.uuid() });
/** Who may write on a play: the person who played it, and the people they follow. */
async function canCommentOn(viewerId: string, ownerId: string) {
if (viewerId === ownerId) return true;
const [row] = await db
.select({ one: schema.follows.followerId })
.from(schema.follows)
.where(and(eq(schema.follows.followerId, ownerId), eq(schema.follows.followeeId, viewerId)));
return Boolean(row);
}
/** The play and its owner, if the viewer may see it: the owner isn't suspended, and no block either way. */
async function visiblePlay(viewerId: string, listenId: string) {
const [row] = await db
.select({ listen: schema.listens, owner: schema.users })
.from(schema.listens)
.innerJoin(schema.users, eq(schema.users.id, schema.listens.userId))
.where(eq(schema.listens.id, listenId));
if (!row || row.owner.suspendedAt) throw new HttpError(404, 'That play is gone');
const { viewerBlocked, blockedByThem } = await blockStatus(viewerId, row.owner.id);
if (viewerBlocked || blockedByThem) throw new HttpError(404, 'That play is gone');
return row;
}
const toCommentDTO = (c: typeof schema.comments.$inferSelect, author: User, viewer: User, ownerId: string): CommentDTO => ({
id: c.id,
user: toUserSummary(author),
body: c.body,
createdAt: c.createdAt.toISOString(),
canDelete: c.userId === viewer.id || ownerId === viewer.id || viewer.role === 'admin',
});
export async function commentRoutes(app: FastifyInstance) {
app.get('/listens/:id/comments', async (req): Promise<CommentThreadDTO> => {
const viewer = requireUser(req);
const { id } = params.parse(req.params);
const { listen, owner } = await visiblePlay(viewer.id, id);
const hidden = await hiddenUserIds(viewer.id);
const rows = await db
.select({ comment: schema.comments, author: schema.users })
.from(schema.comments)
.innerJoin(schema.users, eq(schema.users.id, schema.comments.userId))
.where(and(eq(schema.comments.listenId, id), isNull(schema.users.suspendedAt)))
.orderBy(asc(schema.comments.createdAt));
const [tracks, reactions, canComment] = await Promise.all([
getTrackDTOs([listen.trackId]),
getReactions([id]),
canCommentOn(viewer.id, owner.id),
]);
return {
listenId: id,
owner: toUserSummary(owner),
track: tracks.get(listen.trackId)!,
playedAt: listen.startedAt.toISOString(),
reactions: reactions.get(id) ?? [],
comments: rows.filter((r) => !hidden.has(r.author.id)).map((r) => toCommentDTO(r.comment, r.author, viewer, owner.id)),
canComment,
};
});
app.post(
'/listens/:id/comments',
{ config: { rateLimit: { max: 20, timeWindow: '1 minute' } } },
async (req): Promise<CommentDTO> => {
const viewer = requireUser(req);
const { id } = params.parse(req.params);
const { body } = commentSchema.parse(req.body);
const { listen, owner } = await visiblePlay(viewer.id, id);
if (!(await canCommentOn(viewer.id, owner.id))) {
throw new HttpError(403, `Only people @${owner.username} follows can comment on their songs`);
}
const [comment] = await db.insert(schema.comments).values({ listenId: id, userId: viewer.id, body }).returning();
const excerpt = body.length > 280 ? `${body.slice(0, 279)}…` : body;
const about = { actorId: viewer.id, listenId: id, trackId: listen.trackId, commentId: comment!.id, message: excerpt };
await notify({ ...about, userId: owner.id, type: 'comment' });
// Everyone else who has commented here hears about replies (unless either side has blocked the other).
const others = await db
.selectDistinct({ userId: schema.comments.userId })
.from(schema.comments)
.where(and(eq(schema.comments.listenId, id), ne(schema.comments.userId, viewer.id), ne(schema.comments.userId, owner.id)));
const hidden = await hiddenUserIds(viewer.id);
for (const { userId } of others) {
if (!hidden.has(userId)) await notify({ ...about, userId, type: 'reply' });
}
await publishNowPlaying(owner.id); // the comment count on the feed
return toCommentDTO(comment!, viewer, viewer, owner.id);
},
);
async function findComment(commentId: string) {
const [row] = await db
.select({ comment: schema.comments, ownerId: schema.listens.userId })
.from(schema.comments)
.innerJoin(schema.listens, eq(schema.listens.id, schema.comments.listenId))
.where(eq(schema.comments.id, commentId));
if (!row) throw new HttpError(404, 'That comment is gone');
return row;
}
/** The author, the play's owner, or an admin. Its notifications go with it. */
app.delete('/comments/:id', async (req) => {
const viewer = requireUser(req);
const { id } = params.parse(req.params);
const { comment, ownerId } = await findComment(id);
if (comment.userId !== viewer.id && ownerId !== viewer.id && viewer.role !== 'admin') {
throw new HttpError(403, "You can't delete that comment");
}
await db.delete(schema.comments).where(eq(schema.comments.id, id));
await publishNowPlaying(ownerId);
return { ok: true };
});
app.post(
'/comments/:id/report',
{ config: { rateLimit: { max: 10, timeWindow: '1 hour' } } },
async (req) => {
const viewer = requireUser(req);
const { id } = params.parse(req.params);
const { comment } = await findComment(id);
await visiblePlay(viewer.id, comment.listenId);
if (comment.userId === viewer.id) throw new HttpError(400, "You can't report your own comment");
const input = reportSchema.parse(req.body);
await db.insert(schema.reports).values({
reporterId: viewer.id,
reportedId: comment.userId,
reason: input.reason,
note: input.note || null,
commentId: comment.id,
commentBody: comment.body,
});
return { ok: true };
},
);
}
/** When someone's blocked, their comments on each other's plays go too. */
export async function removeCommentsBetween(a: string, b: string) {
const playsOf = (userId: string) => db.select({ id: schema.listens.id }).from(schema.listens).where(eq(schema.listens.userId, userId));
await db
.delete(schema.comments)
.where(
or(
and(eq(schema.comments.userId, a), inArray(schema.comments.listenId, playsOf(b))),
and(eq(schema.comments.userId, b), inArray(schema.comments.listenId, playsOf(a))),
),
);
}
+2
View File
@@ -11,6 +11,7 @@ import { HttpError } from '../lib/http';
import { FOLLOWS_CHANGED_CHANNEL, redis } from '../lib/redis';
import { removeNotificationsBetween } from '../services/notifications';
import { toUserSummary } from '../services/nowPlaying';
import { removeCommentsBetween } from './comments';
import { removeReactionsBetween } from './reactions';
async function findUser(username: string) {
@@ -49,6 +50,7 @@ export async function safetyRoutes(app: FastifyInstance) {
);
});
await removeReactionsBetween(me.id, them.id);
await removeCommentsBetween(me.id, them.id);
await removeNotificationsBetween(me.id, them.id);
await followsChanged(me.id, them.id);
return { ok: true };
+2 -4
View File
@@ -65,10 +65,8 @@ async function lookup(track: { title: string; artist: string; album: string | nu
if (track.durationMs) {
const params = new URLSearchParams({ track_name: track.title, artist_name: artist, duration: String(Math.round(track.durationMs / 1000)) });
if (track.album) params.set('album_name', track.album);
const exact = await fetchJson<LrclibRecord>(`${env.LRCLIB_URL}/api/get?${params}`, { headers }).catch((e: unknown) => {
if (e instanceof HttpError && e.status === 404) return null;
throw e;
});
// Not found, or LRCLIB's exact lookup is overloaded (it rate-limits /api/get separately): try the search.
const exact = await fetchJson<LrclibRecord>(`${env.LRCLIB_URL}/api/get?${params}`, { headers }).catch(() => null);
if (exact) return exact;
}
const params = new URLSearchParams({ track_name: track.title, artist_name: artist });
+2
View File
@@ -34,6 +34,7 @@ export async function notify(input: {
listenId?: string | null;
emoji?: string | null;
message?: string | null;
commentId?: string | null;
}): Promise<string | null> {
if (input.userId === input.actorId) return null;
const n = schema.notifications;
@@ -91,6 +92,7 @@ export async function toNotificationDTOs(rows: Row[]): Promise<NotificationDTO[]
type: r.type,
actor,
track: r.trackId ? (tracks.get(r.trackId) ?? null) : null,
listenId: r.listenId,
emoji: r.emoji,
message: r.message,
read: Boolean(r.readAt),
+28 -4
View File
@@ -1,4 +1,4 @@
import { and, desc, eq, inArray, isNull, lt } from 'drizzle-orm';
import { and, count, desc, eq, inArray, isNull, lt, notExists } from 'drizzle-orm';
import type { NowPlayingDTO, NowPlayingProvider, ReactionDTO, RecentPlayDTO, UserSummaryDTO } from '@musicshare/shared';
import { db, schema } from '../db';
import type { User } from '../db/schema';
@@ -40,6 +40,18 @@ export async function getReactions(listenIds: string[]): Promise<Map<string, Rea
return result;
}
/** How many comments each play has (from people who aren't suspended). */
export async function getCommentCounts(listenIds: string[]): Promise<Map<string, number>> {
if (listenIds.length === 0) return new Map();
const rows = await db
.select({ listenId: schema.comments.listenId, n: count() })
.from(schema.comments)
.innerJoin(schema.users, eq(schema.users.id, schema.comments.userId))
.where(and(inArray(schema.comments.listenId, listenIds), isNull(schema.users.suspendedAt)))
.groupBy(schema.comments.listenId);
return new Map(rows.map((r) => [r.listenId, r.n]));
}
/** Phones report changes and a heartbeat every few minutes; if they go quiet (app killed, no signal), stop showing "listening now". */
export const DEVICE_STALE_MS = 9 * 60_000;
const PUSH_SOURCES = new Set<NowPlayingProvider>(['android_media_session']);
@@ -63,7 +75,8 @@ export async function getNowPlaying(userIds: string[]): Promise<NowPlayingDTO[]>
const l = listenIds.get(np.userId);
return l && l.trackId === np.trackId ? l.id : null;
};
const reactions = await getReactions(rows.map((r) => listenFor(r.np)).filter((id): id is string => Boolean(id)));
const shownListens = rows.map((r) => listenFor(r.np)).filter((id): id is string => Boolean(id));
const [reactions, commentCounts] = await Promise.all([getReactions(shownListens), getCommentCounts(shownListens)]);
const now = Date.now();
return rows
.map(({ np, user }) => ({ np, user, track: tracks.get(np.trackId)! }))
@@ -78,6 +91,7 @@ export async function getNowPlaying(userIds: string[]): Promise<NowPlayingDTO[]>
updatedAt: np.updatedAt.toISOString(),
listenId: listenFor(np),
reactions: reactions.get(listenFor(np) ?? '') ?? [],
commentCount: commentCounts.get(listenFor(np) ?? '') ?? 0,
}))
.sort((a, b) => Number(b.isPlaying) - Number(a.isPlaying) || b.updatedAt.localeCompare(a.updatedAt));
}
@@ -108,7 +122,11 @@ async function recordListen(userId: string, trackId: string, source: NowPlayingP
.offset(LISTEN_HISTORY_LIMIT - 1)
.limit(1);
if (cutoff) {
await db.delete(schema.listens).where(and(eq(schema.listens.userId, userId), lt(schema.listens.startedAt, cutoff.startedAt)));
// Plays with comments stay, so conversations don't vanish as new songs come in.
const commented = db.select({ one: schema.comments.id }).from(schema.comments).where(eq(schema.comments.listenId, schema.listens.id));
await db
.delete(schema.listens)
.where(and(eq(schema.listens.userId, userId), lt(schema.listens.startedAt, cutoff.startedAt), notExists(commented)));
}
}
@@ -122,13 +140,19 @@ export async function getRecentPlays(userId: string, limit = 10): Promise<Recent
// Don't repeat the track that's playing right now.
const [current] = await db.select().from(schema.nowPlaying).where(eq(schema.nowPlaying.userId, userId));
const plays = current?.isPlaying && rows[0]?.trackId === current.trackId ? rows.slice(1) : rows.slice(0, limit);
const [tracks, reactions] = await Promise.all([getTrackDTOs(plays.map((p) => p.trackId)), getReactions(plays.map((p) => p.id))]);
const ids = plays.map((p) => p.id);
const [tracks, reactions, commentCounts] = await Promise.all([
getTrackDTOs(plays.map((p) => p.trackId)),
getReactions(ids),
getCommentCounts(ids),
]);
return plays.map((p) => ({
listenId: p.id,
track: tracks.get(p.trackId)!,
source: p.source,
playedAt: p.startedAt.toISOString(),
reactions: reactions.get(p.id) ?? [],
commentCount: commentCounts.get(p.id) ?? 0,
}));
}
+8
View File
@@ -22,6 +22,14 @@ const photo = () =>
.toBuffer();
describe('avatars', () => {
it('takes a full-size photo from a high-resolution phone camera (64 MP)', async () => {
const { token } = await createUser(app(), 'hires');
const big = await sharp({ create: { width: 8000, height: 8000, channels: 3, background: '#203040' } }).jpeg().toBuffer();
const { payload, headers } = multipart(big);
const res = await app().inject({ method: 'POST', url: '/me/avatar', payload, headers: { ...headers, ...bearer(token) } });
expect(res.statusCode).toBe(200);
});
it('resizes, re-encodes and serves an uploaded picture', async () => {
const { token, user } = await createUser(app(), 'alice');
const { payload, headers } = multipart(await photo());
+116
View File
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest';
import { applyPollResult, LISTEN_HISTORY_LIMIT } from '../src/services/nowPlaying';
import { bearer, createUser, follow, useTestApp } from './helpers';
const app = useTestApp();
const song = (title: string) => ({ track: { title, artist: 'Massive Attack' }, isPlaying: true, progressMs: null });
/** Alice plays a song. Bob follows her and she follows him back; Carol follows her, but she doesn't follow Carol. */
async function setup() {
const alice = await createUser(app(), 'alice');
const bob = await createUser(app(), 'bob');
const carol = await createUser(app(), 'carol');
await follow(app(), bob.token, 'alice');
await follow(app(), alice.token, 'bob');
await follow(app(), carol.token, 'alice');
await applyPollResult(alice.user.id, 'lastfm', song('Teardrop'));
const feed = (await app().inject({ url: '/feed', headers: bearer(bob.token) })).json();
return { alice, bob, carol, listenId: feed[0].listenId as string };
}
const comment = (token: string, listenId: string, body: string) =>
app().inject({ method: 'POST', url: `/listens/${listenId}/comments`, headers: bearer(token), payload: { body } });
const thread = (token: string, listenId: string) => app().inject({ url: `/listens/${listenId}/comments`, headers: bearer(token) });
/** Comment and reply notifications (setup's follows make some too). */
const notifications = async (token: string) =>
((await app().inject({ url: '/notifications', headers: bearer(token) })).json().notifications as { type: string; message: string }[]).filter(
(n) => n.type === 'comment' || n.type === 'reply',
);
describe('comments', () => {
it('lets the player and people they follow comment, oldest first, with a count on the feed', async () => {
const { alice, bob, carol, listenId } = await setup();
expect((await comment(bob.token, listenId, ' what a tune ')).json()).toMatchObject({ body: 'what a tune', canDelete: true });
await comment(alice.token, listenId, 'right?');
const res = await comment(carol.token, listenId, 'hi');
expect(res.statusCode).toBe(403);
expect(res.json().error).toBe('Only people @alice follows can comment on their songs');
const forCarol = (await thread(carol.token, listenId)).json();
expect(forCarol).toMatchObject({ canComment: false, owner: { username: 'alice' }, track: { title: 'Teardrop' } });
expect(forCarol.comments.map((c: { body: string; canDelete: boolean }) => [c.body, c.canDelete])).toEqual([
['what a tune', false],
['right?', false],
]);
expect((await thread(alice.token, listenId)).json().comments.every((c: { canDelete: boolean }) => c.canDelete)).toBe(true);
const feed = (await app().inject({ url: '/feed', headers: bearer(carol.token) })).json();
expect(feed[0].commentCount).toBe(2);
});
it('rejects empty and overlong comments', async () => {
const { bob, listenId } = await setup();
expect((await comment(bob.token, listenId, ' ')).statusCode).toBe(400);
expect((await comment(bob.token, listenId, 'x'.repeat(501))).statusCode).toBe(400);
});
it('notifies the player, and earlier commenters about replies', async () => {
const { alice, bob, listenId } = await setup();
const dave = await createUser(app(), 'dave');
await follow(app(), alice.token, 'dave');
await comment(bob.token, listenId, 'what a tune');
await comment(dave.token, listenId, 'agreed');
await comment(alice.token, listenId, 'thanks both');
expect((await notifications(alice.token)).map((n) => [n.type, n.message])).toEqual([
['comment', 'agreed'],
['comment', 'what a tune'],
]);
expect((await notifications(bob.token)).map((n) => [n.type, n.message])).toEqual([
['reply', 'thanks both'],
['reply', 'agreed'],
]);
const [latest] = (await app().inject({ url: '/notifications', headers: bearer(bob.token) })).json().notifications;
expect(latest).toMatchObject({ type: 'reply', listenId });
});
it('can be deleted by the author, the player or an admin (taking its notifications along), not anyone else', async () => {
const { alice, bob, carol, listenId } = await setup();
const { id } = (await comment(bob.token, listenId, 'first')).json();
const del = (token: string) => app().inject({ method: 'DELETE', url: `/comments/${id}`, headers: bearer(token) });
expect((await del(carol.token)).statusCode).toBe(403);
expect(await notifications(alice.token)).toHaveLength(1);
expect((await del(alice.token)).statusCode).toBe(200);
expect((await thread(bob.token, listenId)).json().comments).toEqual([]);
expect(await notifications(alice.token)).toEqual([]);
});
it('can be reported, keeping what it said for the admins', async () => {
const { bob, carol, listenId } = await setup();
const { id } = (await comment(bob.token, listenId, 'rude words')).json();
const report = (token: string) =>
app().inject({ method: 'POST', url: `/comments/${id}/report`, headers: bearer(token), payload: { reason: 'harassment' } });
expect((await report(bob.token)).statusCode).toBe(400);
expect((await report(carol.token)).statusCode).toBe(200);
});
it('goes away with a block, both ways', async () => {
const { alice, bob, listenId } = await setup();
await comment(bob.token, listenId, 'hello');
await app().inject({ method: 'POST', url: '/users/bob/block', headers: bearer(alice.token), payload: {} });
expect((await thread(bob.token, listenId)).statusCode).toBe(404);
expect((await thread(alice.token, listenId)).json().comments).toEqual([]);
});
it('keeps plays with comments when old history is trimmed', async () => {
const { alice, bob, listenId } = await setup();
await comment(bob.token, listenId, 'keep this');
for (let i = 0; i < LISTEN_HISTORY_LIMIT + 2; i++) {
await applyPollResult(alice.user.id, 'lastfm', song(`Song ${i}`));
}
const res = await thread(bob.token, listenId);
expect(res.statusCode).toBe(200);
expect(res.json().comments).toHaveLength(1);
});
});
+14
View File
@@ -55,6 +55,20 @@ describe('lyrics', () => {
expect(body.plain).toBe('the one');
});
it("uses the search when LRCLIB's exact lookup is rate-limited", async () => {
const { id } = await upsertTrack({ title: 'Midnight City', artist: 'M83', durationMs: 241_000 });
vi.stubGlobal(
'fetch',
routeFetch([
[/\/api\/get\?/, () => json({ message: 'slow down' }, 429)],
[/\/api\/search\?/, () => json([record()])],
]),
);
const res = await lyrics(id);
expect(res.statusCode).toBe(200);
expect(res.json().synced).toHaveLength(2);
});
it('returns null when nothing matches, and 503 when LRCLIB is down', async () => {
const { id } = await upsertTrack({ title: 'Unknown', artist: 'Nobody', durationMs: 100_000 });
vi.stubGlobal('fetch', routeFetch([[/lrclib/, () => json({ message: 'down' }, 500)]]));
+2 -2
View File
@@ -76,8 +76,8 @@ describe('notifications', () => {
it('saves notification settings', async () => {
const { alice } = await setup();
const me = (await app().inject({ method: 'PATCH', url: '/me', headers: bearer(alice.token), payload: { notifyPrefs: { follow: false } } })).json();
expect(me.notifyPrefs).toEqual({ reaction: true, follow: false, share: true });
const me = (await app().inject({ method: 'PATCH', url: '/me', headers: bearer(alice.token), payload: { notifyPrefs: { follow: false, reply: false } } })).json();
expect(me.notifyPrefs).toEqual({ reaction: true, comment: true, reply: false, follow: false, share: true });
});
});
+2 -2
View File
@@ -2,7 +2,7 @@
"expo": {
"name": "musicshare",
"slug": "musicshare",
"version": "1.2.0",
"version": "1.3.0",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "musicshare",
@@ -23,7 +23,7 @@
},
"predictiveBackGestureEnabled": false,
"package": "tech.chrisedwards.musicshare",
"versionCode": 3
"versionCode": 4
},
"plugins": [
"expo-router",
+3 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@musicshare/mobile",
"main": "expo-router/entry",
"version": "1.2.0",
"version": "1.3.0",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@expo-google-fonts/space-grotesk": "^0.4.1",
@@ -12,10 +12,12 @@
"expo-camera": "~57.0.6",
"expo-constants": "~57.0.20",
"expo-device": "~57.0.2",
"expo-file-system": "~57.0.7",
"expo-font": "~57.0.4",
"expo-glass-effect": "~57.0.4",
"expo-haptics": "~57.0.3",
"expo-image": "~57.0.5",
"expo-image-manipulator": "~57.0.21",
"expo-image-picker": "~57.0.20",
"expo-linear-gradient": "~57.0.2",
"expo-linking": "~57.0.11",
+3 -3
View File
@@ -1,7 +1,7 @@
import { router } from 'expo-router';
import { useEffect, useState } from 'react';
import { Pressable, RefreshControl, ScrollView, StyleSheet, Text, View } from 'react-native';
import Animated, { FadeIn, LinearTransition } from 'react-native-reanimated';
import Animated, { FadeIn } from 'react-native-reanimated';
import { SafeAreaView } from 'react-native-safe-area-context';
import useSWR, { useSWRConfig } from 'swr';
import { sortFeed, type ConnectionDTO, type FeedItemDTO, type FollowListDTO, type ProfileDTO } from '@musicshare/shared';
@@ -85,9 +85,9 @@ export default function FeedScreen() {
return (
<SafeAreaView style={styles.safe} edges={['top']}>
<AmbientBackground />
{/* Cards fade in and slide to new positions when someone pins or starts playing. */}
{/* No itemLayoutAnimation: it leaves the cards behind when the header above them changes height
(e.g. your own card's lyrics loading), opening a gap under "Friends listening". */}
<Animated.FlatList
itemLayoutAnimation={LinearTransition.duration(200)}
data={feed ?? []}
keyExtractor={(item) => item.user.id}
contentContainerStyle={styles.list}
+14 -4
View File
@@ -1,3 +1,5 @@
import { File } from 'expo-file-system';
import { ImageManipulator, SaveFormat } from 'expo-image-manipulator';
import * as ImagePicker from 'expo-image-picker';
import { router } from 'expo-router';
import { useState } from 'react';
@@ -103,10 +105,18 @@ function AvatarPicker() {
});
const asset = result.canceled ? null : result.assets[0];
if (!asset) return;
const form = new FormData();
// React Native's FormData takes a file as { uri, name, type }.
form.append('file', { uri: asset.uri, name: asset.fileName ?? 'avatar.jpg', type: asset.mimeType ?? 'image/jpeg' } as unknown as Blob);
run(() => api.uploadAvatar(form));
run(async () => {
// Shrink first: photos from 50-200 MP cameras are huge, and the server keeps 512 px anyway.
const side = Math.min(1024, asset.width || 1024);
const image = await (await ImageManipulator.manipulate(asset.uri).resize({ width: side }).renderAsync()).saveAsync({
compress: 0.85,
format: SaveFormat.JPEG,
});
const form = new FormData();
// Expo's fetch needs a real file object (it rejects React Native's { uri, name, type } parts).
form.append('file', new File(image.uri) as unknown as Blob);
return api.uploadAvatar(form);
});
};
const remove = () =>
+1
View File
@@ -109,6 +109,7 @@ function AppNavigator() {
<Stack.Screen name="scan" options={{ title: 'Scan a code', presentation: 'modal' }} />
<Stack.Screen name="notifications" options={{ title: 'Notifications' }} />
<Stack.Screen name="t/[id]" options={{ title: '' }} />
<Stack.Screen name="play/[id]" options={{ title: 'Comments' }} />
<Stack.Screen name="send/[trackId]" options={{ title: 'Send to friends', presentation: 'modal' }} />
</Stack.Protected>
<Stack.Protected guard={!signedIn}>
+195
View File
@@ -0,0 +1,195 @@
import { Stack, router, useLocalSearchParams } from 'expo-router';
import { useState } from 'react';
import { ActivityIndicator, Alert, FlatList, KeyboardAvoidingView, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import useSWR from 'swr';
import { COMMENT_MAX_LENGTH, timeAgo, type CommentDTO, type CommentThreadDTO } from '@musicshare/shared';
import { AmbientBackground } from '@/components/AmbientBackground';
import { Avatar } from '@/components/Avatar';
import { Reactions } from '@/components/Reactions';
import { TrackCard } from '@/components/TrackCard';
import { Body, Card } from '@/components/ui';
import { api } from '@/lib/api';
import { showError } from '@/lib/errors';
import { tapHaptic } from '@/lib/haptics';
import { useSession } from '@/lib/session';
import { colors, radius, space } from '@/lib/theme';
/** One play and its comments: where the 💬 chip and comment notifications lead. */
export default function PlayScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const { me } = useSession();
// Polled while open so other people's comments show up without refreshing.
const { data, error, mutate } = useSWR<CommentThreadDTO>(id ? `/listens/${id}/comments` : null, { refreshInterval: 5000 });
const [draft, setDraft] = useState('');
const [sending, setSending] = useState(false);
const send = async () => {
const body = draft.trim();
if (!body || !id) return;
setSending(true);
try {
const comment = await api.addComment(id, { body });
tapHaptic();
setDraft('');
await mutate((t) => (t ? { ...t, comments: [...t.comments, comment] } : t), { revalidate: false });
} catch (err) {
showError(err, "Couldn't post that");
}
setSending(false);
};
const remove = (c: CommentDTO) =>
Alert.alert('Delete this comment?', undefined, [
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete',
style: 'destructive',
onPress: async () => {
try {
await api.deleteComment(c.id);
await mutate((t) => (t ? { ...t, comments: t.comments.filter((x) => x.id !== c.id) } : t), { revalidate: false });
} catch (err) {
showError(err, "Couldn't delete it");
}
},
},
]);
const options = (c: CommentDTO) => {
const mine = c.user.id === me?.id;
Alert.alert(c.user.displayName ?? c.user.username, undefined, [
...(c.canDelete ? [{ text: 'Delete', style: 'destructive' as const, onPress: () => remove(c) }] : []),
...(!mine ? [{ text: 'Report', onPress: () => router.push(`/report/${c.user.username}?comment=${c.id}`) }] : []),
{ text: 'Cancel', style: 'cancel' as const },
]);
};
if (error) {
return (
<View style={styles.center}>
<Stack.Screen options={{ title: '' }} />
<Body muted>That play is gone.</Body>
</View>
);
}
if (!data) {
return (
<View style={styles.center}>
<ActivityIndicator color={colors.muted} />
</View>
);
}
const owner = data.owner.displayName ?? data.owner.username;
return (
<SafeAreaView style={styles.safe} edges={['bottom']}>
<Stack.Screen options={{ title: 'Comments' }} />
<AmbientBackground />
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={90}>
<FlatList
data={data.comments}
keyExtractor={(c) => c.id}
contentContainerStyle={styles.list}
keyboardShouldPersistTaps="handled"
ListHeaderComponent={
<View style={styles.header}>
<Pressable onPress={() => router.push(`/u/${data.owner.username}`)} style={styles.playedBy}>
<Avatar user={data.owner} size={28} />
<Text style={styles.muted}>
<Text style={styles.name}>{owner}</Text> played this · {timeAgo(data.playedAt)}
</Text>
</Pressable>
<TrackCard track={data.track} preferred={me?.preferredService} />
<Reactions listenId={data.listenId} reactions={data.reactions} ownerId={data.owner.id} style={{ marginTop: 0 }} />
</View>
}
ListEmptyComponent={<Body muted>{data.canComment ? 'No comments yet. Say something!' : 'No comments yet.'}</Body>}
renderItem={({ item }) => (
<Pressable onLongPress={() => options(item)} delayLongPress={300} style={styles.comment}>
<Pressable onPress={() => router.push(`/u/${item.user.username}`)} hitSlop={4}>
<Avatar user={item.user} size={34} />
</Pressable>
<View style={{ flex: 1, minWidth: 0, gap: 2 }}>
<Text style={styles.muted}>
<Text style={styles.name}>{item.user.displayName ?? item.user.username}</Text> · {timeAgo(item.createdAt)}
</Text>
<Text style={styles.body} selectable>
{item.body}
</Text>
</View>
<Pressable onPress={() => options(item)} hitSlop={10} accessibilityLabel="Comment options">
<Text style={styles.more}>⋯</Text>
</Pressable>
</Pressable>
)}
/>
{data.canComment ? (
<View style={styles.composer}>
<TextInput
value={draft}
onChangeText={setDraft}
placeholder={data.owner.id === me?.id ? 'Comment on your song' : `Comment on ${owner}'s song`}
placeholderTextColor={colors.muted}
multiline
maxLength={COMMENT_MAX_LENGTH}
style={styles.input}
/>
<Pressable
onPress={send}
disabled={!draft.trim() || sending}
accessibilityRole="button"
accessibilityLabel="Post comment"
style={[styles.send, (!draft.trim() || sending) && { opacity: 0.4 }]}>
{sending ? <ActivityIndicator color="#fff" size="small" /> : <Text style={styles.sendText}>Post</Text>}
</Pressable>
</View>
) : (
<Card style={styles.closed}>
<Body muted style={{ fontSize: 13 }}>
Only people {owner} follows can comment on their songs.
</Body>
</Card>
)}
</KeyboardAvoidingView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safe: { flex: 1, backgroundColor: colors.bg },
center: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.bg },
list: { padding: space.lg, gap: space.md, paddingBottom: space.xl },
header: { gap: space.md, marginBottom: space.sm },
playedBy: { flexDirection: 'row', alignItems: 'center', gap: space.sm },
comment: { flexDirection: 'row', gap: space.md, alignItems: 'flex-start' },
name: { color: colors.text, fontWeight: '700' },
muted: { color: colors.muted, fontSize: 13 },
body: { color: colors.text, fontSize: 15, lineHeight: 21 },
more: { color: colors.muted, fontSize: 18, paddingHorizontal: space.xs },
composer: {
flexDirection: 'row',
alignItems: 'flex-end',
gap: space.sm,
paddingHorizontal: space.lg,
paddingVertical: space.sm,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: colors.border,
backgroundColor: colors.bg,
},
input: {
flex: 1,
maxHeight: 120,
color: colors.text,
fontSize: 15,
paddingHorizontal: space.md,
paddingVertical: space.sm,
borderRadius: radius.md,
backgroundColor: colors.surface,
borderWidth: 1,
borderColor: colors.border,
},
send: { paddingHorizontal: space.md, paddingVertical: space.sm + 2, borderRadius: radius.pill, backgroundColor: colors.accent },
sendText: { color: '#fff', fontWeight: '700' },
closed: { margin: space.lg, marginTop: 0 },
});
+5 -3
View File
@@ -8,7 +8,8 @@ import { api } from '@/lib/api';
import { showError } from '@/lib/errors';
export default function ReportScreen() {
const { username } = useLocalSearchParams<{ username: string }>();
// ?comment=<id> reports one comment of theirs rather than their account.
const { username, comment } = useLocalSearchParams<{ username: string; comment?: string }>();
const [reason, setReason] = useState<ReportReason | null>(null);
const [note, setNote] = useState('');
const [busy, setBusy] = useState(false);
@@ -18,7 +19,8 @@ export default function ReportScreen() {
if (!reason) return;
setBusy(true);
try {
await api.report(username, { reason, note: note.trim() || null });
const input = { reason, note: note.trim() || null };
await (comment ? api.reportComment(comment, input) : api.report(username, input));
setSent(true);
} catch (err) {
showError(err, "Couldn't send the report");
@@ -38,7 +40,7 @@ export default function ReportScreen() {
return (
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
<Screen>
<Body muted>What&apos;s wrong with @{username}&apos;s account?</Body>
<Body muted>{comment ? `What's wrong with @${username}'s comment?` : `What's wrong with @${username}'s account?`}</Body>
<Row>
{REPORT_REASONS.map((r) => (
<Chip key={r} label={REPORT_REASON_LABELS[r]} selected={reason === r} onPress={() => setReason(r)} />
@@ -101,7 +101,7 @@ export function NowPlayingCard({
<TrackRow track={np.track} preferred={preferred} expanded={expanded} onToggle={toggle} />
</Animated.View>
<ProgressBar np={np} compact={!expanded} />
<Reactions listenId={np.listenId} reactions={np.reactions} ownerId={np.user.id} />
<Reactions listenId={np.listenId} reactions={np.reactions} ownerId={np.user.id} commentCount={np.commentCount ?? 0} />
{expanded && (
<Animated.View entering={FadeIn.duration(200)} exiting={FadeOut.duration(120)} style={styles.details}>
<ServiceLinks track={np.track} preferred={preferred} />
+19 -3
View File
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { FlatList, Modal, Pressable, StyleSheet, Text, TextInput, View, type ViewStyle } from 'react-native';
import Animated, { FadeIn, FadeOut, ZoomIn } from 'react-native-reanimated';
import { router } from 'expo-router';
import Animated, { FadeIn, FadeOut } from 'react-native-reanimated';
import { EMOJI_PICKER_GROUPS, QUICK_REACTIONS, searchEmoji, type ReactionDTO } from '@musicshare/shared';
import { api } from '@/lib/api';
import { showError } from '@/lib/errors';
@@ -11,16 +12,19 @@ import { colors, radius, space } from '@/lib/theme';
/**
* Emoji reactions on one play. Tap an emoji to add yours (or take it back); "☺+"
* opens the quick six, and "+" the full picker. One reaction per person.
* With `commentCount`, a 💬 chip opens the play's comments.
*/
export function Reactions({
listenId,
reactions,
ownerId,
commentCount,
style,
}: {
listenId: string | null;
reactions: ReactionDTO[];
ownerId: string;
commentCount?: number;
style?: ViewStyle;
}) {
const { me } = useSession();
@@ -31,7 +35,8 @@ export function Reactions({
const [pickerOpen, setPickerOpen] = useState(false);
const canReact = Boolean(me && listenId && me.id !== ownerId);
if (!listenId || (!canReact && shown.length === 0)) return null;
const showComments = commentCount !== undefined && Boolean(me);
if (!listenId || (!canReact && shown.length === 0 && !showComments)) return null;
const mine = me ? shown.find((r) => r.users.some((u) => u.id === me.id))?.emoji : undefined;
const choose = async (emoji: string) => {
@@ -50,7 +55,7 @@ export function Reactions({
<View style={[styles.wrap, style]}>
<View style={styles.row}>
{shown.map((r) => (
<Animated.View key={r.emoji} entering={ZoomIn.springify()}>
<Animated.View key={r.emoji} entering={FadeIn.duration(150)}>
<Pressable
disabled={!canReact}
onPress={() => choose(r.emoji)}
@@ -73,6 +78,17 @@ export function Reactions({
<Text style={[styles.count, { color: colors.muted }]}>+</Text>
</Pressable>
)}
{showComments && (
<Pressable
onPress={() => router.push(`/play/${listenId}`)}
accessibilityRole="button"
accessibilityLabel={commentCount ? `${commentCount} comment${commentCount === 1 ? '' : 's'}` : 'Comments'}
hitSlop={6}
style={({ pressed }) => [styles.chip, pressed && { transform: [{ scale: 0.9 }] }]}>
<Text style={styles.emoji}>💬</Text>
{commentCount ? <Text style={styles.count}>{commentCount}</Text> : null}
</Pressable>
)}
</View>
{quickOpen && (
<Animated.View entering={FadeIn.duration(150)} exiting={FadeOut.duration(120)} style={styles.quick}>
+1 -1
View File
@@ -47,7 +47,7 @@ export function RecentPlays({
</View>
<Text style={styles.time}>{timeAgo(p.playedAt)}</Text>
</Pressable>
<Reactions listenId={p.listenId} reactions={p.reactions} ownerId={ownerId} style={styles.reactions} />
<Reactions listenId={p.listenId} reactions={p.reactions} ownerId={ownerId} commentCount={p.commentCount ?? 0} style={styles.reactions} />
</View>
))}
{credits.map((s) => (
+5
View File
@@ -71,6 +71,11 @@ export default function AdminPage() {
<strong>{REPORT_REASON_LABELS[r.reason as ReportReason] ?? r.reason}</strong>
{r.reporter && <span className="muted"> · reported by @{r.reporter.username}</span>}
</p>
{r.comment && (
<p className="muted small">
Their comment{r.comment.id ? '' : ' (since deleted)'}: <q>{r.comment.body}</q>
</p>
)}
{r.note && <blockquote>{r.note}</blockquote>}
<div className="row">
{r.status === 'open' && (
+18
View File
@@ -130,6 +130,24 @@ input:focus, textarea:focus, select:focus {
.reaction-emoji { font-size: 1.05rem; line-height: 1.3; }
.reaction-count { font-size: 0.78rem; font-variant-numeric: tabular-nums; }
.reaction-add { color: var(--muted); font-size: 1rem; }
a.reaction { text-decoration: none; }
/* Comments on a play (/play/[id]) */
.played-by { display: flex; align-items: center; gap: 0.4rem; flex-wrap: wrap; }
.played-by-user { display: inline-flex; align-items: center; gap: 0.4rem; color: var(--text); }
.comments { display: flex; flex-direction: column; gap: 0.9rem; }
.comments h2 { margin: 0; }
.comment { display: flex; gap: 0.75rem; align-items: flex-start; }
.comment-main { flex: 1; min-width: 0; }
.comment-main a { color: var(--text); }
.comment-body { margin: 0.15rem 0 0; white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.45; }
.comment-actions { display: flex; gap: 0.6rem; opacity: 0.6; }
.comment:hover .comment-actions, .comment:focus-within .comment-actions { opacity: 1; }
.link-button { background: none; border: 0; padding: 0; font: inherit; font-size: 0.8rem; color: var(--muted); cursor: pointer; }
.link-button:hover { color: var(--text); text-decoration: underline; }
.comment-form { display: flex; gap: 0.6rem; align-items: flex-end; }
.comment-form textarea { flex: 1; resize: vertical; min-height: 2.6rem; }
@media (max-width: 520px) { .comment-actions { opacity: 1; } }
.reaction-add span { font-size: 0.75rem; margin-left: -0.15rem; }
.reaction-add-wrap { position: static; } /* the quick menu anchors to the row, so it never runs off the card */
.reaction-quick { position: absolute; bottom: calc(100% + 0.4rem); left: 0; z-index: 30; display: flex; align-items: center; gap: 0.15rem; padding: 0.3rem; border-radius: 999px; background: #1a1535; border: 1px solid rgba(255, 255, 255, 0.14); box-shadow: 0 14px 30px -10px rgba(0, 0, 0, 0.7); animation: pop 0.18s ease-out; white-space: nowrap; }
+1 -1
View File
@@ -8,7 +8,7 @@ import { notificationPath, notificationText, timeAgo, type NotificationListDTO }
import { Avatar } from '@/components/Avatar';
import { client, useMe } from '@/lib/api';
/** Reactions, new followers and songs sent to you, newest first. Opening it marks them read. */
/** Reactions, comments, new followers and songs sent to you, newest first. Opening it marks them read. */
export default function NotificationsPage() {
const { me, loggedOut } = useMe();
const { mutate } = useSWRConfig();
+145
View File
@@ -0,0 +1,145 @@
'use client';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useState } from 'react';
import useSWR from 'swr';
import { COMMENT_MAX_LENGTH, timeAgo, type CommentDTO, type CommentThreadDTO } from '@musicshare/shared';
import { Avatar } from '@/components/Avatar';
import { ReportForm } from '@/components/ProfileMenu';
import { Reactions } from '@/components/Reactions';
import { TrackCard } from '@/components/TrackCard';
import { client, fetcher, useMe } from '@/lib/api';
/** One play and its comments: where the 💬 link and comment notifications lead. */
export default function PlayPage() {
const { id } = useParams<{ id: string }>();
const { me, loggedOut } = useMe();
// Polled while open so other people's comments show up without reloading.
const { data, error, mutate } = useSWR<CommentThreadDTO>(me ? `/listens/${id}/comments` : null, fetcher, { refreshInterval: 5000 });
const [draft, setDraft] = useState('');
const [sending, setSending] = useState(false);
const [problem, setProblem] = useState<string | null>(null);
const [reporting, setReporting] = useState<CommentDTO | null>(null);
if (loggedOut) {
return (
<p className="muted">
<Link href="/login">Log in</Link> to see the comments.
</p>
);
}
if (error) return <p className="muted">That play is gone.</p>;
if (!data) return null;
const owner = data.owner.displayName ?? data.owner.username;
const send = async (e: React.FormEvent) => {
e.preventDefault();
const body = draft.trim();
if (!body) return;
setSending(true);
setProblem(null);
try {
const comment = await client.addComment(id, { body });
setDraft('');
await mutate((t) => (t ? { ...t, comments: [...t.comments, comment] } : t), { revalidate: false });
} catch (err) {
setProblem((err as Error).message);
}
setSending(false);
};
const remove = async (c: CommentDTO) => {
if (!confirm('Delete this comment?')) return;
try {
await client.deleteComment(c.id);
await mutate((t) => (t ? { ...t, comments: t.comments.filter((x) => x.id !== c.id) } : t), { revalidate: false });
} catch (err) {
setProblem((err as Error).message);
}
};
return (
<div className="stack">
<p className="muted played-by">
<Link href={`/u/${data.owner.username}`} className="played-by-user">
<Avatar user={data.owner} size={28} />
<strong>{owner}</strong>
</Link>{' '}
played this · {timeAgo(data.playedAt)}
</p>
<section className="card">
<TrackCard track={data.track} preferred={me?.preferredService} />
<Reactions listenId={data.listenId} reactions={data.reactions} ownerId={data.owner.id} />
</section>
<section className="card comments">
<h2>Comments</h2>
{data.comments.length === 0 && <p className="muted">{data.canComment ? 'No comments yet. Say something!' : 'No comments yet.'}</p>}
{data.comments.map((c) => (
<div key={c.id} className="comment">
<Link href={`/u/${c.user.username}`}>
<Avatar user={c.user} size={34} />
</Link>
<div className="comment-main">
<div className="muted small">
<Link href={`/u/${c.user.username}`}>
<strong>{c.user.displayName ?? c.user.username}</strong>
</Link>{' '}
· {timeAgo(c.createdAt)}
</div>
<p className="comment-body">{c.body}</p>
</div>
<div className="comment-actions">
{c.canDelete && (
<button type="button" className="link-button" onClick={() => remove(c)}>
Delete
</button>
)}
{c.user.id !== me?.id && (
<button type="button" className="link-button" onClick={() => setReporting(c)}>
Report
</button>
)}
</div>
</div>
))}
{data.canComment ? (
<form className="comment-form" onSubmit={send}>
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
// Enter posts; Shift+Enter is a new line.
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
e.currentTarget.form?.requestSubmit();
}
}}
placeholder={data.owner.id === me?.id ? 'Comment on your song' : `Comment on ${owner}'s song`}
maxLength={COMMENT_MAX_LENGTH}
rows={2}
/>
<button className="btn btn-primary" disabled={!draft.trim() || sending}>
Post
</button>
</form>
) : (
<p className="muted small">Only people {owner} follows can comment on their songs.</p>
)}
{problem && <p className="error">{problem}</p>}
</section>
{reporting && (
<ReportForm
username={reporting.user.username}
name={reporting.user.displayName ?? reporting.user.username}
commentId={reporting.id}
onClose={() => setReporting(null)}
/>
)}
</div>
);
}
+13 -4
View File
@@ -3,7 +3,7 @@ import Link from 'next/link';
export const metadata: Metadata = { title: 'Privacy policy · musicshare' };
const UPDATED = 'October 14, 2026';
const UPDATED = 'October 15, 2026';
const CONTACT = 'app@musicshare.binarygnome.com';
export default function PrivacyPage() {
@@ -40,11 +40,16 @@ export default function PrivacyPage() {
&ldquo;notification access&rdquo;, but the app only reads the song, artist and album from music apps you allow.
It doesn&apos;t read or store your notifications, messages or anything from other apps.
</li>
<li>
<strong>Comments and reactions</strong> you leave on plays. Comments stay until you or the person who played the
song deletes them, or one of your accounts is deleted. Plays with comments are kept in their history so the
conversation isn&apos;t lost.
</li>
<li>
<strong>People:</strong> who you follow, who you&apos;ve pinned, who you&apos;ve blocked, and reports you send.
</li>
<li>
<strong>Notifications:</strong> reactions, new followers and songs (with any note) sent to you, and your
<strong>Notifications:</strong> reactions, comments and replies, new followers and songs (with any note) sent to you, and your
notification settings. If you turn on push notifications, we store the push address your browser or
phone gives us and its encryption keys.
</li>
@@ -63,13 +68,17 @@ export default function PrivacyPage() {
people who aren&apos;t signed in.
</li>
<li>Your followers see what you play in their feed, live.</li>
<li>
Comments on a play can be read by signed-in people who can see that play. Only you and the people you follow can
write them, and you can delete any comment on your plays.
</li>
<li>
Your email address is never shown to other people. It&apos;s used to sign in, to send you confirmation and
password reset emails, and to contact you about your account.
</li>
<li>
People you block can&apos;t find you or see your profile, and you stop following each other. They aren&apos;t
told.
People you block can&apos;t find you or see your profile, and you stop following each other. Their comments on
your plays, and yours on theirs, are removed. They aren&apos;t told.
</li>
<li>
You can <strong>pause sharing</strong> at any time in Settings. While paused, nothing new you play is shared or
+1 -1
View File
@@ -89,7 +89,7 @@ export function NowPlayingCard({
>
<TrackRow track={np.track} preferred={preferred} expanded={expanded} onToggle={() => setExpanded((v) => !v)} />
<ProgressBar np={np} compact={!expanded} />
<Reactions listenId={np.listenId} reactions={np.reactions} ownerId={np.user.id} />
<Reactions listenId={np.listenId} reactions={np.reactions} ownerId={np.user.id} commentCount={np.commentCount ?? 0} />
<AnimatePresence initial={false}>
{expanded && (
<motion.div
+5 -3
View File
@@ -62,7 +62,8 @@ export function ProfileMenu({ profile, onChanged }: { profile: ProfileDTO; onCha
);
}
function ReportForm({ username, name, onClose }: { username: string; name: string; onClose: () => void }) {
/** Report someone's account, or one of their comments (`commentId`). */
export function ReportForm({ username, name, commentId, onClose }: { username: string; name: string; commentId?: string; onClose: () => void }) {
const [reason, setReason] = useState<ReportReason | null>(null);
const [note, setNote] = useState('');
const [sent, setSent] = useState(false);
@@ -72,7 +73,8 @@ function ReportForm({ username, name, onClose }: { username: string; name: strin
e.preventDefault();
if (!reason) return;
try {
await client.report(username, { reason, note: note.trim() || null });
const input = { reason, note: note.trim() || null };
await (commentId ? client.reportComment(commentId, input) : client.report(username, input));
setSent(true);
} catch (err) {
setError((err as Error).message);
@@ -90,7 +92,7 @@ function ReportForm({ username, name, onClose }: { username: string; name: strin
);
}
return (
<Modal onClose={onClose} title={`Report ${name}`}>
<Modal onClose={onClose} title={commentId ? `Report ${name}'s comment` : `Report ${name}`}>
<form className="form" onSubmit={submit}>
<fieldset className="choices">
<legend className="muted">What&apos;s wrong?</legend>
+25 -2
View File
@@ -1,5 +1,6 @@
'use client';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { EMOJI_PICKER_GROUPS, QUICK_REACTIONS, searchEmoji, type ReactionDTO } from '@musicshare/shared';
import { client, useMe } from '@/lib/api';
@@ -9,7 +10,18 @@ import { Modal } from './ProfileMenu';
* Emoji reactions on one play. Tap an emoji to add yours (or take it back); "☺+"
* offers the quick six, and "More" opens the full picker. One reaction per person.
*/
export function Reactions({ listenId, reactions, ownerId }: { listenId: string | null; reactions: ReactionDTO[]; ownerId: string }) {
export function Reactions({
listenId,
reactions,
ownerId,
commentCount,
}: {
listenId: string | null;
reactions: ReactionDTO[];
ownerId: string;
/** Shows a 💬 link to the play's comments. */
commentCount?: number;
}) {
const { me } = useMe();
// The server's answer to our last tap, until fresh props arrive (e.g. a realtime update).
const [local, setLocal] = useState<{ from: ReactionDTO[]; value: ReactionDTO[] } | null>(null);
@@ -27,7 +39,8 @@ export function Reactions({ listenId, reactions, ownerId }: { listenId: string |
}, [quickOpen]);
const canReact = Boolean(me && listenId && me.id !== ownerId);
if (!listenId || (!canReact && shown.length === 0)) return null;
const showComments = commentCount !== undefined && Boolean(me);
if (!listenId || (!canReact && shown.length === 0 && !showComments)) return null;
const mine = me ? shown.find((r) => r.users.some((u) => u.id === me.id))?.emoji : undefined;
const choose = async (emoji: string) => {
@@ -77,6 +90,16 @@ export function Reactions({ listenId, reactions, ownerId }: { listenId: string |
)}
</span>
)}
{showComments && (
<Link
href={`/play/${listenId}`}
className="reaction"
aria-label={commentCount ? `${commentCount} comment${commentCount === 1 ? '' : 's'}` : 'Comments'}
>
<span className="reaction-emoji">💬</span>
{commentCount ? <span className="reaction-count">{commentCount}</span> : null}
</Link>
)}
{error && <span className="error">{error}</span>}
{pickerOpen && <EmojiPicker onPick={choose} onClose={() => setPickerOpen(false)} />}
</div>
+1 -1
View File
@@ -48,7 +48,7 @@ export function RecentPlays({
) : (
<div className="recent-row">{row}</div>
)}
<Reactions listenId={p.listenId} reactions={p.reactions} ownerId={ownerId} />
<Reactions listenId={p.listenId} reactions={p.reactions} ownerId={ownerId} commentCount={p.commentCount ?? 0} />
</li>
);
})}
@@ -0,0 +1 @@
Comments: tap 💬 next to a song's reactions to talk about it. The person who played it and the people they follow can comment, and you'll be notified about comments and replies. Changing your profile picture works again, and lyrics load more reliably.
+15 -1
View File
@@ -809,7 +809,7 @@
},
"apps/mobile": {
"name": "@musicshare/mobile",
"version": "1.2.0",
"version": "1.3.0",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@expo-google-fonts/space-grotesk": "^0.4.1",
@@ -820,10 +820,12 @@
"expo-camera": "~57.0.6",
"expo-constants": "~57.0.20",
"expo-device": "~57.0.2",
"expo-file-system": "~57.0.7",
"expo-font": "~57.0.4",
"expo-glass-effect": "~57.0.4",
"expo-haptics": "~57.0.3",
"expo-image": "~57.0.5",
"expo-image-manipulator": "~57.0.21",
"expo-image-picker": "~57.0.20",
"expo-linear-gradient": "~57.0.2",
"expo-linking": "~57.0.11",
@@ -11288,6 +11290,18 @@
"expo": "*"
}
},
"node_modules/expo-image-manipulator": {
"version": "57.0.21",
"resolved": "https://registry.npmjs.org/expo-image-manipulator/-/expo-image-manipulator-57.0.21.tgz",
"integrity": "sha512-NZeNvZxBNf/PK97Df5zORmtqRR/LovkA+lHdRLm1IJFiVKjs4xr+Ib6/jWhDxn04VOX3TJswCQyu4SCxkgMe4Q==",
"license": "MIT",
"dependencies": {
"expo-image-loader": "~57.0.1"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-image-picker": {
"version": "57.0.20",
"resolved": "https://registry.npmjs.org/expo-image-picker/-/expo-image-picker-57.0.20.tgz",
+11
View File
@@ -1,6 +1,8 @@
import type {
AdminReportDTO,
AdminStatsDTO,
CommentDTO,
CommentThreadDTO,
ConnectionDTO,
FollowListDTO,
ReactionDTO,
@@ -17,6 +19,7 @@ import type { AppUpdateDTO } from './updates';
import type {
ChangeEmailInput,
ChangePasswordInput,
CommentInput,
LoginInput,
RegisterInput,
ReportReason,
@@ -136,6 +139,14 @@ export function createApiClient({ baseUrl, getToken, credentials }: ApiClientOpt
react: (listenId: string, emoji: string) => request<ReactionDTO[]>(`/listens/${q(listenId)}/reaction`, { method: 'PUT', body: { emoji } }),
unreact: (listenId: string) => request<ReactionDTO[]>(`/listens/${q(listenId)}/reaction`, { method: 'DELETE' }),
/** A play with its comments. */
comments: (listenId: string) => request<CommentThreadDTO>(`/listens/${q(listenId)}/comments`),
addComment: (listenId: string, input: CommentInput) =>
request<CommentDTO>(`/listens/${q(listenId)}/comments`, { method: 'POST', body: input }),
deleteComment: (id: string) => request<{ ok: true }>(`/comments/${q(id)}`, { method: 'DELETE' }),
reportComment: (id: string, input: { reason: ReportReason; note?: string | null }) =>
request<{ ok: true }>(`/comments/${q(id)}/report`, { body: input }),
searchTracks: (query: string) => request<TrackSearchResultDTO[]>(`/tracks/search?q=${q(query)}`),
/** Null when no lyrics were found for the song. */
lyrics: (trackId: string) => request<LyricsDTO | null>(`/tracks/${q(trackId)}/lyrics`),
+1
View File
@@ -13,6 +13,7 @@ function item(username: string, opts: { pinnedAt?: string; isPlaying?: boolean;
updatedAt: opts.updatedAt ?? '2026-01-01T00:00:00.000Z',
listenId: null,
reactions: [],
commentCount: 0,
pinnedAt: opts.pinnedAt ?? null,
};
}
+27 -1
View File
@@ -57,9 +57,10 @@ export interface NowPlayingDTO {
sourceUrl: string | null;
progressMs: number | null;
updatedAt: string;
/** The play this is, for reactions (null for very old rows). */
/** The play this is, for reactions and comments (null for very old rows). */
listenId: string | null;
reactions: ReactionDTO[];
commentCount: number;
}
/** A feed entry. pinnedAt is set when the viewer pinned this friend. */
@@ -90,6 +91,29 @@ export interface RecentPlayDTO {
source: NowPlayingProvider;
playedAt: string;
reactions: ReactionDTO[];
commentCount: number;
}
/** A comment on a play. */
export interface CommentDTO {
id: string;
user: UserSummaryDTO;
body: string;
createdAt: string;
/** The viewer wrote it, owns the play, or is an admin. */
canDelete: boolean;
}
/** A play and its comments, oldest first (GET /listens/:id/comments). */
export interface CommentThreadDTO {
listenId: string;
owner: UserSummaryDTO;
track: TrackDTO;
playedAt: string;
reactions: ReactionDTO[];
comments: CommentDTO[];
/** False when the viewer can read but not write (only the player and people they follow can comment). */
canComment: boolean;
}
export interface ProfileDTO {
@@ -119,6 +143,8 @@ export interface AdminReportDTO {
createdAt: string;
reporter: UserSummaryDTO | null;
reported: UserSummaryDTO & { suspended: boolean };
/** When a comment was reported: what it said (kept even if it's since been deleted). */
comment: { id: string | null; body: string } | null;
}
export interface AdminStatsDTO {
+14 -3
View File
@@ -17,11 +17,22 @@ describe('notifications', () => {
});
it('links songs to the song and follows to the person', () => {
expect(notificationPath({ type: 'share', actor, track })).toBe('/t/t1');
expect(notificationPath({ type: 'follow', actor, track: null })).toBe('/u/bob');
expect(notificationPath({ type: 'share', actor, track, listenId: null })).toBe('/t/t1');
expect(notificationPath({ type: 'follow', actor, track: null, listenId: null })).toBe('/u/bob');
});
it('opens the play for comments, replies and reactions', () => {
expect(notificationPath({ type: 'comment', actor, track, listenId: 'l1' })).toBe('/play/l1');
expect(notificationPath({ type: 'reaction', actor, track, listenId: 'l1' })).toBe('/play/l1');
// The play was trimmed from history: fall back to the song.
expect(notificationPath({ type: 'reaction', actor, track, listenId: null })).toBe('/t/t1');
expect(notificationText({ type: 'reply', actor, track, emoji: null, message: 'same' })).toEqual({
title: 'Bob replied on Teardrop by Massive Attack',
body: 'same',
});
});
it('treats missing settings as on', () => {
expect(notificationPrefs({ follow: false })).toEqual({ reaction: true, follow: false, share: true });
expect(notificationPrefs({ follow: false })).toEqual({ reaction: true, comment: true, reply: true, follow: false, share: true });
});
});
+13 -2
View File
@@ -1,6 +1,6 @@
import type { TrackDTO, UserSummaryDTO } from './dto';
export const NOTIFICATION_TYPES = ['reaction', 'follow', 'share'] as const;
export const NOTIFICATION_TYPES = ['reaction', 'comment', 'reply', 'follow', 'share'] as const;
export type NotificationType = (typeof NOTIFICATION_TYPES)[number];
/** Which notifications get pushed to your phone/browser. */
@@ -8,6 +8,8 @@ export type NotificationPrefs = Record<NotificationType, boolean>;
export const NOTIFICATION_PREF_LABELS: Record<NotificationType, string> = {
reaction: 'Reactions to your songs',
comment: 'Comments on your songs',
reply: 'Replies where you commented',
follow: 'New followers',
share: 'Songs sent to you',
};
@@ -15,6 +17,8 @@ export const NOTIFICATION_PREF_LABELS: Record<NotificationType, string> = {
/** Missing settings mean on. */
export const notificationPrefs = (stored: Partial<NotificationPrefs> | null | undefined): NotificationPrefs => ({
reaction: stored?.reaction ?? true,
comment: stored?.comment ?? true,
reply: stored?.reply ?? true,
follow: stored?.follow ?? true,
share: stored?.share ?? true,
});
@@ -24,6 +28,8 @@ export interface NotificationDTO {
type: NotificationType;
actor: UserSummaryDTO;
track: TrackDTO | null;
/** The play a reaction or comment was on, while it exists. */
listenId: string | null;
emoji: string | null;
message: string | null;
read: boolean;
@@ -47,6 +53,10 @@ export function notificationText(n: Pick<NotificationDTO, 'type' | 'actor' | 'tr
switch (n.type) {
case 'reaction':
return { title: `${who} reacted ${n.emoji ?? ''}`.trim(), body: `to ${song}` };
case 'comment':
return { title: `${who} commented on ${song}`, body: n.message ?? '' };
case 'reply':
return { title: `${who} replied on ${song}`, body: n.message ?? '' };
case 'follow':
return { title: `${who} followed you`, body: 'Follow back to see what they play.' };
case 'share':
@@ -55,7 +65,8 @@ export function notificationText(n: Pick<NotificationDTO, 'type' | 'actor' | 'tr
}
/** Where tapping it goes, as an app/web path. */
export function notificationPath(n: Pick<NotificationDTO, 'type' | 'actor' | 'track'>): string {
export function notificationPath(n: Pick<NotificationDTO, 'type' | 'actor' | 'track' | 'listenId'>): string {
if ((n.type === 'comment' || n.type === 'reply' || n.type === 'reaction') && n.listenId) return `/play/${n.listenId}`;
if ((n.type === 'share' || n.type === 'reaction') && n.track) return `/t/${n.track.id}`;
return `/u/${n.actor.username}`;
}
+7 -1
View File
@@ -53,7 +53,7 @@ export const updateMeSchema = z.object({
.nullable()
.optional(),
notifyPrefs: z
.object({ reaction: z.boolean(), follow: z.boolean(), share: z.boolean() })
.object({ reaction: z.boolean(), comment: z.boolean(), reply: z.boolean(), follow: z.boolean(), share: z.boolean() })
.partial()
.optional(),
/** Mark onboarding as finished. */
@@ -112,6 +112,12 @@ export const REPORT_REASON_LABELS: Record<ReportReason, string> = {
impersonation: 'Pretending to be someone else',
other: 'Something else',
};
export const COMMENT_MAX_LENGTH = 500;
export const commentSchema = z.object({
body: z.string().trim().min(1, 'Write something first').max(COMMENT_MAX_LENGTH, `Keep it under ${COMMENT_MAX_LENGTH} characters`),
});
export type CommentInput = z.infer<typeof commentSchema>;
export const reportSchema = z.object({
reason: z.enum(REPORT_REASONS),
note: z.string().trim().max(500).nullish(),