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
This commit is contained in:
@@ -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
@@ -120,6 +120,13 @@
|
|||||||
"when": 1792028149643,
|
"when": 1792028149643,
|
||||||
"tag": "0016_notifications",
|
"tag": "0016_notifications",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 17,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1792084480262,
|
||||||
|
"tag": "0017_comments",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -12,6 +12,7 @@ import { HttpError } from './lib/http';
|
|||||||
import { redis } from './lib/redis';
|
import { redis } from './lib/redis';
|
||||||
import { adminRoutes } from './routes/admin';
|
import { adminRoutes } from './routes/admin';
|
||||||
import { appUpdateRoutes } from './routes/appUpdates';
|
import { appUpdateRoutes } from './routes/appUpdates';
|
||||||
|
import { commentRoutes } from './routes/comments';
|
||||||
import { accountRoutes } from './routes/account';
|
import { accountRoutes } from './routes/account';
|
||||||
import { authRoutes } from './routes/auth';
|
import { authRoutes } from './routes/auth';
|
||||||
import { avatarRoutes } from './routes/avatars';
|
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(adminRoutes);
|
||||||
await app.register(trackRoutes);
|
await app.register(trackRoutes);
|
||||||
await app.register(reactionRoutes);
|
await app.register(reactionRoutes);
|
||||||
|
await app.register(commentRoutes);
|
||||||
await app.register(notificationRoutes);
|
await app.register(notificationRoutes);
|
||||||
await app.register(connectionRoutes);
|
await app.register(connectionRoutes);
|
||||||
await app.register(deviceRoutes);
|
await app.register(deviceRoutes);
|
||||||
|
|||||||
@@ -105,6 +105,9 @@ export const reports = pgTable(
|
|||||||
.references(() => users.id, { onDelete: 'cascade' }),
|
.references(() => users.id, { onDelete: 'cascade' }),
|
||||||
reason: text('reason').$type<ReportReason>().notNull(),
|
reason: text('reason').$type<ReportReason>().notNull(),
|
||||||
note: varchar('note', { length: 500 }),
|
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'),
|
status: text('status').$type<'open' | 'resolved'>().notNull().default('open'),
|
||||||
createdAt: createdAt(),
|
createdAt: createdAt(),
|
||||||
},
|
},
|
||||||
@@ -262,6 +265,23 @@ export const reactions = pgTable(
|
|||||||
(t) => [primaryKey({ columns: [t.listenId, t.userId] })],
|
(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. */
|
/** Email confirmation links (sign-up and email changes). Only a hash of the token is stored. */
|
||||||
export const emailVerifications = pgTable(
|
export const emailVerifications = pgTable(
|
||||||
'email_verifications',
|
'email_verifications',
|
||||||
@@ -306,7 +326,7 @@ export const lyrics = pgTable('lyrics', {
|
|||||||
fetchedAt: timestamp('fetched_at', { withTimezone: true }).notNull().defaultNow(),
|
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(
|
export const notifications = pgTable(
|
||||||
'notifications',
|
'notifications',
|
||||||
{
|
{
|
||||||
@@ -319,10 +339,12 @@ export const notifications = pgTable(
|
|||||||
.notNull()
|
.notNull()
|
||||||
.references(() => users.id, { onDelete: 'cascade' }),
|
.references(() => users.id, { onDelete: 'cascade' }),
|
||||||
trackId: uuid('track_id').references(() => tracks.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' }),
|
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 }),
|
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 }),
|
message: varchar('message', { length: 280 }),
|
||||||
readAt: timestamp('read_at', { withTimezone: true }),
|
readAt: timestamp('read_at', { withTimezone: true }),
|
||||||
createdAt: createdAt(),
|
createdAt: createdAt(),
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ export async function adminRoutes(app: FastifyInstance) {
|
|||||||
createdAt: report.createdAt.toISOString(),
|
createdAt: report.createdAt.toISOString(),
|
||||||
reporter: by ? toUserSummary(by) : null,
|
reporter: by ? toUserSummary(by) : null,
|
||||||
reported: { ...toUserSummary(who), suspended: Boolean(who.suspendedAt) },
|
reported: { ...toUserSummary(who), suspended: Boolean(who.suspendedAt) },
|
||||||
|
comment: report.commentBody ? { id: report.commentId, body: report.commentBody } : null,
|
||||||
}));
|
}));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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))),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import { HttpError } from '../lib/http';
|
|||||||
import { FOLLOWS_CHANGED_CHANNEL, redis } from '../lib/redis';
|
import { FOLLOWS_CHANGED_CHANNEL, redis } from '../lib/redis';
|
||||||
import { removeNotificationsBetween } from '../services/notifications';
|
import { removeNotificationsBetween } from '../services/notifications';
|
||||||
import { toUserSummary } from '../services/nowPlaying';
|
import { toUserSummary } from '../services/nowPlaying';
|
||||||
|
import { removeCommentsBetween } from './comments';
|
||||||
import { removeReactionsBetween } from './reactions';
|
import { removeReactionsBetween } from './reactions';
|
||||||
|
|
||||||
async function findUser(username: string) {
|
async function findUser(username: string) {
|
||||||
@@ -49,6 +50,7 @@ export async function safetyRoutes(app: FastifyInstance) {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
await removeReactionsBetween(me.id, them.id);
|
await removeReactionsBetween(me.id, them.id);
|
||||||
|
await removeCommentsBetween(me.id, them.id);
|
||||||
await removeNotificationsBetween(me.id, them.id);
|
await removeNotificationsBetween(me.id, them.id);
|
||||||
await followsChanged(me.id, them.id);
|
await followsChanged(me.id, them.id);
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ export async function notify(input: {
|
|||||||
listenId?: string | null;
|
listenId?: string | null;
|
||||||
emoji?: string | null;
|
emoji?: string | null;
|
||||||
message?: string | null;
|
message?: string | null;
|
||||||
|
commentId?: string | null;
|
||||||
}): Promise<string | null> {
|
}): Promise<string | null> {
|
||||||
if (input.userId === input.actorId) return null;
|
if (input.userId === input.actorId) return null;
|
||||||
const n = schema.notifications;
|
const n = schema.notifications;
|
||||||
@@ -91,6 +92,7 @@ export async function toNotificationDTOs(rows: Row[]): Promise<NotificationDTO[]
|
|||||||
type: r.type,
|
type: r.type,
|
||||||
actor,
|
actor,
|
||||||
track: r.trackId ? (tracks.get(r.trackId) ?? null) : null,
|
track: r.trackId ? (tracks.get(r.trackId) ?? null) : null,
|
||||||
|
listenId: r.listenId,
|
||||||
emoji: r.emoji,
|
emoji: r.emoji,
|
||||||
message: r.message,
|
message: r.message,
|
||||||
read: Boolean(r.readAt),
|
read: Boolean(r.readAt),
|
||||||
|
|||||||
@@ -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 type { NowPlayingDTO, NowPlayingProvider, ReactionDTO, RecentPlayDTO, UserSummaryDTO } from '@musicshare/shared';
|
||||||
import { db, schema } from '../db';
|
import { db, schema } from '../db';
|
||||||
import type { User } from '../db/schema';
|
import type { User } from '../db/schema';
|
||||||
@@ -40,6 +40,18 @@ export async function getReactions(listenIds: string[]): Promise<Map<string, Rea
|
|||||||
return result;
|
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". */
|
/** 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;
|
export const DEVICE_STALE_MS = 9 * 60_000;
|
||||||
const PUSH_SOURCES = new Set<NowPlayingProvider>(['android_media_session']);
|
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);
|
const l = listenIds.get(np.userId);
|
||||||
return l && l.trackId === np.trackId ? l.id : null;
|
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();
|
const now = Date.now();
|
||||||
return rows
|
return rows
|
||||||
.map(({ np, user }) => ({ np, user, track: tracks.get(np.trackId)! }))
|
.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(),
|
updatedAt: np.updatedAt.toISOString(),
|
||||||
listenId: listenFor(np),
|
listenId: listenFor(np),
|
||||||
reactions: reactions.get(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));
|
.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)
|
.offset(LISTEN_HISTORY_LIMIT - 1)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
if (cutoff) {
|
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.
|
// 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 [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 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) => ({
|
return plays.map((p) => ({
|
||||||
listenId: p.id,
|
listenId: p.id,
|
||||||
track: tracks.get(p.trackId)!,
|
track: tracks.get(p.trackId)!,
|
||||||
source: p.source,
|
source: p.source,
|
||||||
playedAt: p.startedAt.toISOString(),
|
playedAt: p.startedAt.toISOString(),
|
||||||
reactions: reactions.get(p.id) ?? [],
|
reactions: reactions.get(p.id) ?? [],
|
||||||
|
commentCount: commentCounts.get(p.id) ?? 0,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -76,8 +76,8 @@ describe('notifications', () => {
|
|||||||
|
|
||||||
it('saves notification settings', async () => {
|
it('saves notification settings', async () => {
|
||||||
const { alice } = await setup();
|
const { alice } = await setup();
|
||||||
const me = (await app().inject({ method: 'PATCH', url: '/me', headers: bearer(alice.token), payload: { notifyPrefs: { follow: false } } })).json();
|
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, follow: false, share: true });
|
expect(me.notifyPrefs).toEqual({ reaction: true, comment: true, reply: false, follow: false, share: true });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -109,6 +109,7 @@ function AppNavigator() {
|
|||||||
<Stack.Screen name="scan" options={{ title: 'Scan a code', presentation: 'modal' }} />
|
<Stack.Screen name="scan" options={{ title: 'Scan a code', presentation: 'modal' }} />
|
||||||
<Stack.Screen name="notifications" options={{ title: 'Notifications' }} />
|
<Stack.Screen name="notifications" options={{ title: 'Notifications' }} />
|
||||||
<Stack.Screen name="t/[id]" options={{ title: '' }} />
|
<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.Screen name="send/[trackId]" options={{ title: 'Send to friends', presentation: 'modal' }} />
|
||||||
</Stack.Protected>
|
</Stack.Protected>
|
||||||
<Stack.Protected guard={!signedIn}>
|
<Stack.Protected guard={!signedIn}>
|
||||||
|
|||||||
@@ -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 },
|
||||||
|
});
|
||||||
@@ -8,7 +8,8 @@ import { api } from '@/lib/api';
|
|||||||
import { showError } from '@/lib/errors';
|
import { showError } from '@/lib/errors';
|
||||||
|
|
||||||
export default function ReportScreen() {
|
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 [reason, setReason] = useState<ReportReason | null>(null);
|
||||||
const [note, setNote] = useState('');
|
const [note, setNote] = useState('');
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
@@ -18,7 +19,8 @@ export default function ReportScreen() {
|
|||||||
if (!reason) return;
|
if (!reason) return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
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);
|
setSent(true);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showError(err, "Couldn't send the report");
|
showError(err, "Couldn't send the report");
|
||||||
@@ -38,7 +40,7 @@ export default function ReportScreen() {
|
|||||||
return (
|
return (
|
||||||
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
|
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
|
||||||
<Screen>
|
<Screen>
|
||||||
<Body muted>What's wrong with @{username}'s account?</Body>
|
<Body muted>{comment ? `What's wrong with @${username}'s comment?` : `What's wrong with @${username}'s account?`}</Body>
|
||||||
<Row>
|
<Row>
|
||||||
{REPORT_REASONS.map((r) => (
|
{REPORT_REASONS.map((r) => (
|
||||||
<Chip key={r} label={REPORT_REASON_LABELS[r]} selected={reason === r} onPress={() => setReason(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} />
|
<TrackRow track={np.track} preferred={preferred} expanded={expanded} onToggle={toggle} />
|
||||||
</Animated.View>
|
</Animated.View>
|
||||||
<ProgressBar np={np} compact={!expanded} />
|
<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 && (
|
{expanded && (
|
||||||
<Animated.View entering={FadeIn.duration(200)} exiting={FadeOut.duration(120)} style={styles.details}>
|
<Animated.View entering={FadeIn.duration(200)} exiting={FadeOut.duration(120)} style={styles.details}>
|
||||||
<ServiceLinks track={np.track} preferred={preferred} />
|
<ServiceLinks track={np.track} preferred={preferred} />
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { FlatList, Modal, Pressable, StyleSheet, Text, TextInput, View, type ViewStyle } from 'react-native';
|
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 { EMOJI_PICKER_GROUPS, QUICK_REACTIONS, searchEmoji, type ReactionDTO } from '@musicshare/shared';
|
||||||
import { api } from '@/lib/api';
|
import { api } from '@/lib/api';
|
||||||
import { showError } from '@/lib/errors';
|
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); "☺+"
|
* 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.
|
* opens the quick six, and "+" the full picker. One reaction per person.
|
||||||
|
* With `commentCount`, a 💬 chip opens the play's comments.
|
||||||
*/
|
*/
|
||||||
export function Reactions({
|
export function Reactions({
|
||||||
listenId,
|
listenId,
|
||||||
reactions,
|
reactions,
|
||||||
ownerId,
|
ownerId,
|
||||||
|
commentCount,
|
||||||
style,
|
style,
|
||||||
}: {
|
}: {
|
||||||
listenId: string | null;
|
listenId: string | null;
|
||||||
reactions: ReactionDTO[];
|
reactions: ReactionDTO[];
|
||||||
ownerId: string;
|
ownerId: string;
|
||||||
|
commentCount?: number;
|
||||||
style?: ViewStyle;
|
style?: ViewStyle;
|
||||||
}) {
|
}) {
|
||||||
const { me } = useSession();
|
const { me } = useSession();
|
||||||
@@ -31,7 +35,8 @@ export function Reactions({
|
|||||||
const [pickerOpen, setPickerOpen] = useState(false);
|
const [pickerOpen, setPickerOpen] = useState(false);
|
||||||
|
|
||||||
const canReact = Boolean(me && listenId && me.id !== ownerId);
|
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 mine = me ? shown.find((r) => r.users.some((u) => u.id === me.id))?.emoji : undefined;
|
||||||
|
|
||||||
const choose = async (emoji: string) => {
|
const choose = async (emoji: string) => {
|
||||||
@@ -50,7 +55,7 @@ export function Reactions({
|
|||||||
<View style={[styles.wrap, style]}>
|
<View style={[styles.wrap, style]}>
|
||||||
<View style={styles.row}>
|
<View style={styles.row}>
|
||||||
{shown.map((r) => (
|
{shown.map((r) => (
|
||||||
<Animated.View key={r.emoji} entering={ZoomIn.springify()}>
|
<Animated.View key={r.emoji} entering={FadeIn.duration(150)}>
|
||||||
<Pressable
|
<Pressable
|
||||||
disabled={!canReact}
|
disabled={!canReact}
|
||||||
onPress={() => choose(r.emoji)}
|
onPress={() => choose(r.emoji)}
|
||||||
@@ -73,6 +78,17 @@ export function Reactions({
|
|||||||
<Text style={[styles.count, { color: colors.muted }]}>+</Text>
|
<Text style={[styles.count, { color: colors.muted }]}>+</Text>
|
||||||
</Pressable>
|
</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>
|
</View>
|
||||||
{quickOpen && (
|
{quickOpen && (
|
||||||
<Animated.View entering={FadeIn.duration(150)} exiting={FadeOut.duration(120)} style={styles.quick}>
|
<Animated.View entering={FadeIn.duration(150)} exiting={FadeOut.duration(120)} style={styles.quick}>
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export function RecentPlays({
|
|||||||
</View>
|
</View>
|
||||||
<Text style={styles.time}>{timeAgo(p.playedAt)}</Text>
|
<Text style={styles.time}>{timeAgo(p.playedAt)}</Text>
|
||||||
</Pressable>
|
</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>
|
</View>
|
||||||
))}
|
))}
|
||||||
{credits.map((s) => (
|
{credits.map((s) => (
|
||||||
|
|||||||
@@ -71,6 +71,11 @@ export default function AdminPage() {
|
|||||||
<strong>{REPORT_REASON_LABELS[r.reason as ReportReason] ?? r.reason}</strong>
|
<strong>{REPORT_REASON_LABELS[r.reason as ReportReason] ?? r.reason}</strong>
|
||||||
{r.reporter && <span className="muted"> · reported by @{r.reporter.username}</span>}
|
{r.reporter && <span className="muted"> · reported by @{r.reporter.username}</span>}
|
||||||
</p>
|
</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>}
|
{r.note && <blockquote>{r.note}</blockquote>}
|
||||||
<div className="row">
|
<div className="row">
|
||||||
{r.status === 'open' && (
|
{r.status === 'open' && (
|
||||||
|
|||||||
@@ -130,6 +130,24 @@ input:focus, textarea:focus, select:focus {
|
|||||||
.reaction-emoji { font-size: 1.05rem; line-height: 1.3; }
|
.reaction-emoji { font-size: 1.05rem; line-height: 1.3; }
|
||||||
.reaction-count { font-size: 0.78rem; font-variant-numeric: tabular-nums; }
|
.reaction-count { font-size: 0.78rem; font-variant-numeric: tabular-nums; }
|
||||||
.reaction-add { color: var(--muted); font-size: 1rem; }
|
.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 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-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; }
|
.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; }
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { notificationPath, notificationText, timeAgo, type NotificationListDTO }
|
|||||||
import { Avatar } from '@/components/Avatar';
|
import { Avatar } from '@/components/Avatar';
|
||||||
import { client, useMe } from '@/lib/api';
|
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() {
|
export default function NotificationsPage() {
|
||||||
const { me, loggedOut } = useMe();
|
const { me, loggedOut } = useMe();
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ import Link from 'next/link';
|
|||||||
|
|
||||||
export const metadata: Metadata = { title: 'Privacy policy · musicshare' };
|
export const metadata: Metadata = { title: 'Privacy policy · musicshare' };
|
||||||
|
|
||||||
const UPDATED = 'October 14, 2026';
|
const UPDATED = 'October 15, 2026';
|
||||||
const CONTACT = 'app@musicshare.binarygnome.com';
|
const CONTACT = 'app@musicshare.binarygnome.com';
|
||||||
|
|
||||||
export default function PrivacyPage() {
|
export default function PrivacyPage() {
|
||||||
@@ -40,11 +40,16 @@ export default function PrivacyPage() {
|
|||||||
“notification access”, but the app only reads the song, artist and album from music apps you allow.
|
“notification access”, but the app only reads the song, artist and album from music apps you allow.
|
||||||
It doesn't read or store your notifications, messages or anything from other apps.
|
It doesn't read or store your notifications, messages or anything from other apps.
|
||||||
</li>
|
</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't lost.
|
||||||
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>People:</strong> who you follow, who you've pinned, who you've blocked, and reports you send.
|
<strong>People:</strong> who you follow, who you've pinned, who you've blocked, and reports you send.
|
||||||
</li>
|
</li>
|
||||||
<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
|
notification settings. If you turn on push notifications, we store the push address your browser or
|
||||||
phone gives us and its encryption keys.
|
phone gives us and its encryption keys.
|
||||||
</li>
|
</li>
|
||||||
@@ -63,13 +68,17 @@ export default function PrivacyPage() {
|
|||||||
people who aren't signed in.
|
people who aren't signed in.
|
||||||
</li>
|
</li>
|
||||||
<li>Your followers see what you play in their feed, live.</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>
|
<li>
|
||||||
Your email address is never shown to other people. It's used to sign in, to send you confirmation and
|
Your email address is never shown to other people. It's used to sign in, to send you confirmation and
|
||||||
password reset emails, and to contact you about your account.
|
password reset emails, and to contact you about your account.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
People you block can't find you or see your profile, and you stop following each other. They aren't
|
People you block can't find you or see your profile, and you stop following each other. Their comments on
|
||||||
told.
|
your plays, and yours on theirs, are removed. They aren't told.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
You can <strong>pause sharing</strong> at any time in Settings. While paused, nothing new you play is shared or
|
You can <strong>pause sharing</strong> at any time in Settings. While paused, nothing new you play is shared or
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ export function NowPlayingCard({
|
|||||||
>
|
>
|
||||||
<TrackRow track={np.track} preferred={preferred} expanded={expanded} onToggle={() => setExpanded((v) => !v)} />
|
<TrackRow track={np.track} preferred={preferred} expanded={expanded} onToggle={() => setExpanded((v) => !v)} />
|
||||||
<ProgressBar np={np} compact={!expanded} />
|
<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}>
|
<AnimatePresence initial={false}>
|
||||||
{expanded && (
|
{expanded && (
|
||||||
<motion.div
|
<motion.div
|
||||||
|
|||||||
@@ -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 [reason, setReason] = useState<ReportReason | null>(null);
|
||||||
const [note, setNote] = useState('');
|
const [note, setNote] = useState('');
|
||||||
const [sent, setSent] = useState(false);
|
const [sent, setSent] = useState(false);
|
||||||
@@ -72,7 +73,8 @@ function ReportForm({ username, name, onClose }: { username: string; name: strin
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!reason) return;
|
if (!reason) return;
|
||||||
try {
|
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);
|
setSent(true);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError((err as Error).message);
|
setError((err as Error).message);
|
||||||
@@ -90,7 +92,7 @@ function ReportForm({ username, name, onClose }: { username: string; name: strin
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<Modal onClose={onClose} title={`Report ${name}`}>
|
<Modal onClose={onClose} title={commentId ? `Report ${name}'s comment` : `Report ${name}`}>
|
||||||
<form className="form" onSubmit={submit}>
|
<form className="form" onSubmit={submit}>
|
||||||
<fieldset className="choices">
|
<fieldset className="choices">
|
||||||
<legend className="muted">What's wrong?</legend>
|
<legend className="muted">What's wrong?</legend>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
|
import Link from 'next/link';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { EMOJI_PICKER_GROUPS, QUICK_REACTIONS, searchEmoji, type ReactionDTO } from '@musicshare/shared';
|
import { EMOJI_PICKER_GROUPS, QUICK_REACTIONS, searchEmoji, type ReactionDTO } from '@musicshare/shared';
|
||||||
import { client, useMe } from '@/lib/api';
|
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); "☺+"
|
* 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.
|
* 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();
|
const { me } = useMe();
|
||||||
// The server's answer to our last tap, until fresh props arrive (e.g. a realtime update).
|
// 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);
|
const [local, setLocal] = useState<{ from: ReactionDTO[]; value: ReactionDTO[] } | null>(null);
|
||||||
@@ -27,7 +39,8 @@ export function Reactions({ listenId, reactions, ownerId }: { listenId: string |
|
|||||||
}, [quickOpen]);
|
}, [quickOpen]);
|
||||||
|
|
||||||
const canReact = Boolean(me && listenId && me.id !== ownerId);
|
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 mine = me ? shown.find((r) => r.users.some((u) => u.id === me.id))?.emoji : undefined;
|
||||||
|
|
||||||
const choose = async (emoji: string) => {
|
const choose = async (emoji: string) => {
|
||||||
@@ -77,6 +90,16 @@ export function Reactions({ listenId, reactions, ownerId }: { listenId: string |
|
|||||||
)}
|
)}
|
||||||
</span>
|
</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>}
|
{error && <span className="error">{error}</span>}
|
||||||
{pickerOpen && <EmojiPicker onPick={choose} onClose={() => setPickerOpen(false)} />}
|
{pickerOpen && <EmojiPicker onPick={choose} onClose={() => setPickerOpen(false)} />}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export function RecentPlays({
|
|||||||
) : (
|
) : (
|
||||||
<div className="recent-row">{row}</div>
|
<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>
|
</li>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import type {
|
import type {
|
||||||
AdminReportDTO,
|
AdminReportDTO,
|
||||||
AdminStatsDTO,
|
AdminStatsDTO,
|
||||||
|
CommentDTO,
|
||||||
|
CommentThreadDTO,
|
||||||
ConnectionDTO,
|
ConnectionDTO,
|
||||||
FollowListDTO,
|
FollowListDTO,
|
||||||
ReactionDTO,
|
ReactionDTO,
|
||||||
@@ -17,6 +19,7 @@ import type { AppUpdateDTO } from './updates';
|
|||||||
import type {
|
import type {
|
||||||
ChangeEmailInput,
|
ChangeEmailInput,
|
||||||
ChangePasswordInput,
|
ChangePasswordInput,
|
||||||
|
CommentInput,
|
||||||
LoginInput,
|
LoginInput,
|
||||||
RegisterInput,
|
RegisterInput,
|
||||||
ReportReason,
|
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 } }),
|
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' }),
|
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)}`),
|
searchTracks: (query: string) => request<TrackSearchResultDTO[]>(`/tracks/search?q=${q(query)}`),
|
||||||
/** Null when no lyrics were found for the song. */
|
/** Null when no lyrics were found for the song. */
|
||||||
lyrics: (trackId: string) => request<LyricsDTO | null>(`/tracks/${q(trackId)}/lyrics`),
|
lyrics: (trackId: string) => request<LyricsDTO | null>(`/tracks/${q(trackId)}/lyrics`),
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ function item(username: string, opts: { pinnedAt?: string; isPlaying?: boolean;
|
|||||||
updatedAt: opts.updatedAt ?? '2026-01-01T00:00:00.000Z',
|
updatedAt: opts.updatedAt ?? '2026-01-01T00:00:00.000Z',
|
||||||
listenId: null,
|
listenId: null,
|
||||||
reactions: [],
|
reactions: [],
|
||||||
|
commentCount: 0,
|
||||||
pinnedAt: opts.pinnedAt ?? null,
|
pinnedAt: opts.pinnedAt ?? null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,9 +57,10 @@ export interface NowPlayingDTO {
|
|||||||
sourceUrl: string | null;
|
sourceUrl: string | null;
|
||||||
progressMs: number | null;
|
progressMs: number | null;
|
||||||
updatedAt: string;
|
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;
|
listenId: string | null;
|
||||||
reactions: ReactionDTO[];
|
reactions: ReactionDTO[];
|
||||||
|
commentCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A feed entry. pinnedAt is set when the viewer pinned this friend. */
|
/** A feed entry. pinnedAt is set when the viewer pinned this friend. */
|
||||||
@@ -90,6 +91,29 @@ export interface RecentPlayDTO {
|
|||||||
source: NowPlayingProvider;
|
source: NowPlayingProvider;
|
||||||
playedAt: string;
|
playedAt: string;
|
||||||
reactions: ReactionDTO[];
|
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 {
|
export interface ProfileDTO {
|
||||||
@@ -119,6 +143,8 @@ export interface AdminReportDTO {
|
|||||||
createdAt: string;
|
createdAt: string;
|
||||||
reporter: UserSummaryDTO | null;
|
reporter: UserSummaryDTO | null;
|
||||||
reported: UserSummaryDTO & { suspended: boolean };
|
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 {
|
export interface AdminStatsDTO {
|
||||||
|
|||||||
@@ -17,11 +17,22 @@ describe('notifications', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('links songs to the song and follows to the person', () => {
|
it('links songs to the song and follows to the person', () => {
|
||||||
expect(notificationPath({ type: 'share', actor, track })).toBe('/t/t1');
|
expect(notificationPath({ type: 'share', actor, track, listenId: null })).toBe('/t/t1');
|
||||||
expect(notificationPath({ type: 'follow', actor, track: null })).toBe('/u/bob');
|
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', () => {
|
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 });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { TrackDTO, UserSummaryDTO } from './dto';
|
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];
|
export type NotificationType = (typeof NOTIFICATION_TYPES)[number];
|
||||||
|
|
||||||
/** Which notifications get pushed to your phone/browser. */
|
/** 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> = {
|
export const NOTIFICATION_PREF_LABELS: Record<NotificationType, string> = {
|
||||||
reaction: 'Reactions to your songs',
|
reaction: 'Reactions to your songs',
|
||||||
|
comment: 'Comments on your songs',
|
||||||
|
reply: 'Replies where you commented',
|
||||||
follow: 'New followers',
|
follow: 'New followers',
|
||||||
share: 'Songs sent to you',
|
share: 'Songs sent to you',
|
||||||
};
|
};
|
||||||
@@ -15,6 +17,8 @@ export const NOTIFICATION_PREF_LABELS: Record<NotificationType, string> = {
|
|||||||
/** Missing settings mean on. */
|
/** Missing settings mean on. */
|
||||||
export const notificationPrefs = (stored: Partial<NotificationPrefs> | null | undefined): NotificationPrefs => ({
|
export const notificationPrefs = (stored: Partial<NotificationPrefs> | null | undefined): NotificationPrefs => ({
|
||||||
reaction: stored?.reaction ?? true,
|
reaction: stored?.reaction ?? true,
|
||||||
|
comment: stored?.comment ?? true,
|
||||||
|
reply: stored?.reply ?? true,
|
||||||
follow: stored?.follow ?? true,
|
follow: stored?.follow ?? true,
|
||||||
share: stored?.share ?? true,
|
share: stored?.share ?? true,
|
||||||
});
|
});
|
||||||
@@ -24,6 +28,8 @@ export interface NotificationDTO {
|
|||||||
type: NotificationType;
|
type: NotificationType;
|
||||||
actor: UserSummaryDTO;
|
actor: UserSummaryDTO;
|
||||||
track: TrackDTO | null;
|
track: TrackDTO | null;
|
||||||
|
/** The play a reaction or comment was on, while it exists. */
|
||||||
|
listenId: string | null;
|
||||||
emoji: string | null;
|
emoji: string | null;
|
||||||
message: string | null;
|
message: string | null;
|
||||||
read: boolean;
|
read: boolean;
|
||||||
@@ -47,6 +53,10 @@ export function notificationText(n: Pick<NotificationDTO, 'type' | 'actor' | 'tr
|
|||||||
switch (n.type) {
|
switch (n.type) {
|
||||||
case 'reaction':
|
case 'reaction':
|
||||||
return { title: `${who} reacted ${n.emoji ?? ''}`.trim(), body: `to ${song}` };
|
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':
|
case 'follow':
|
||||||
return { title: `${who} followed you`, body: 'Follow back to see what they play.' };
|
return { title: `${who} followed you`, body: 'Follow back to see what they play.' };
|
||||||
case 'share':
|
case 'share':
|
||||||
@@ -55,7 +65,8 @@ export function notificationText(n: Pick<NotificationDTO, 'type' | 'actor' | 'tr
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Where tapping it goes, as an app/web path. */
|
/** 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}`;
|
if ((n.type === 'share' || n.type === 'reaction') && n.track) return `/t/${n.track.id}`;
|
||||||
return `/u/${n.actor.username}`;
|
return `/u/${n.actor.username}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ export const updateMeSchema = z.object({
|
|||||||
.nullable()
|
.nullable()
|
||||||
.optional(),
|
.optional(),
|
||||||
notifyPrefs: z
|
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()
|
.partial()
|
||||||
.optional(),
|
.optional(),
|
||||||
/** Mark onboarding as finished. */
|
/** Mark onboarding as finished. */
|
||||||
@@ -112,6 +112,12 @@ export const REPORT_REASON_LABELS: Record<ReportReason, string> = {
|
|||||||
impersonation: 'Pretending to be someone else',
|
impersonation: 'Pretending to be someone else',
|
||||||
other: 'Something 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({
|
export const reportSchema = z.object({
|
||||||
reason: z.enum(REPORT_REASONS),
|
reason: z.enum(REPORT_REASONS),
|
||||||
note: z.string().trim().max(500).nullish(),
|
note: z.string().trim().max(500).nullish(),
|
||||||
|
|||||||
Reference in New Issue
Block a user