refactor: eslint and prettier conflict will be resolved and formatted

This commit is contained in:
Enes Köksal
2026-04-23 17:05:43 +03:00
parent 385b61f29b
commit 3cfea40fbd
219 changed files with 16638 additions and 13663 deletions
+156 -145
View File
@@ -9,158 +9,169 @@ type RouteParams = { params: Promise<{ videoId: string }> };
// GET /api/watch/[videoId]/progress - Get watch progress for the current user
export async function GET(request: NextRequest, { params }: RouteParams) {
try {
const session = await auth();
if (!session?.user?.id) {
return apiErrors.unauthorized('Authentication required');
}
try {
const session = await auth();
const { videoId } = await params;
// Get the video and its active version (project access data pre-fetched in same query)
const userId = session.user.id;
const video = await db.video.findUnique({
where: { id: videoId },
include: {
project: { include: projectAccessInclude(userId) },
versions: {
where: { isActive: true },
take: 1,
},
},
});
if (!video) {
return apiErrors.notFound('Video');
}
const access = computeProjectAccess(video.project, userId);
if (!access.hasAccess) {
return apiErrors.forbidden('Access denied');
}
const activeVersion = video.versions[0];
if (!activeVersion) {
return apiErrors.notFound('Video version');
}
// Get watch progress for this user and version
const progress = await db.watchProgress.findUnique({
where: {
userId_versionId: {
userId: session.user.id,
versionId: activeVersion.id,
},
},
});
return successResponse({
progress: progress ? progress.progress : 0,
duration: progress?.duration || activeVersion.duration || 0,
percentage: progress?.percentage || 0,
updatedAt: progress?.updatedAt || null,
});
} catch (error) {
logError('Error fetching watch progress:', error);
return apiErrors.internalError('Failed to fetch watch progress');
if (!session?.user?.id) {
return apiErrors.unauthorized('Authentication required');
}
const { videoId } = await params;
// Get the video and its active version (project access data pre-fetched in same query)
const userId = session.user.id;
const video = await db.video.findUnique({
where: { id: videoId },
include: {
project: { include: projectAccessInclude(userId) },
versions: {
where: { isActive: true },
take: 1,
},
},
});
if (!video) {
return apiErrors.notFound('Video');
}
const access = computeProjectAccess(video.project, userId);
if (!access.hasAccess) {
return apiErrors.forbidden('Access denied');
}
const activeVersion = video.versions[0];
if (!activeVersion) {
return apiErrors.notFound('Video version');
}
// Get watch progress for this user and version
const progress = await db.watchProgress.findUnique({
where: {
userId_versionId: {
userId: session.user.id,
versionId: activeVersion.id,
},
},
});
return successResponse({
progress: progress ? progress.progress : 0,
duration: progress?.duration || activeVersion.duration || 0,
percentage: progress?.percentage || 0,
updatedAt: progress?.updatedAt || null,
});
} catch (error) {
logError('Error fetching watch progress:', error);
return apiErrors.internalError('Failed to fetch watch progress');
}
}
// POST /api/watch/[videoId]/progress - Save watch progress for the current user
export async function POST(request: NextRequest, { params }: RouteParams) {
try {
// Rate limit watch progress updates (30 per minute to allow pause + periodic + visibility changes)
const limited = await rateLimit(request, 'watch-progress');
if (limited) return limited;
const session = await auth();
if (!session?.user?.id) {
return apiErrors.unauthorized('Authentication required');
}
try {
// Rate limit watch progress updates (30 per minute to allow pause + periodic + visibility changes)
const limited = await rateLimit(request, 'watch-progress');
if (limited) return limited;
const { videoId } = await params;
const body = await request.json();
const { progress, duration, versionId } = body;
const session = await auth();
const MAX_VIDEO_SECONDS = 86_400; // 24 hours — reasonable upper bound for any video
if (typeof progress !== 'number' || !isFinite(progress) || progress < 0 || progress > MAX_VIDEO_SECONDS) {
return apiErrors.badRequest('Invalid progress value');
}
if (duration !== undefined && (typeof duration !== 'number' || !isFinite(duration) || duration < 0 || duration > MAX_VIDEO_SECONDS)) {
return apiErrors.badRequest('Invalid duration value');
}
if (versionId !== undefined && typeof versionId !== 'string') {
return apiErrors.badRequest('Invalid versionId');
}
// Always load the requested video and validate access before writing progress.
// If versionId is provided, verify it belongs to this video; otherwise resolve active version.
// Project access data is pre-fetched in the same query — no extra round-trips.
const userId = session.user.id;
const video = await db.video.findUnique({
where: { id: videoId },
include: {
project: { include: projectAccessInclude(userId) },
versions: {
where: versionId ? { id: versionId } : { isActive: true },
take: 1,
},
},
});
if (!video) {
return apiErrors.notFound('Video');
}
const access = computeProjectAccess(video.project, userId);
if (!access.hasAccess) {
return apiErrors.forbidden('Access denied');
}
const targetVersion = video.versions[0];
if (!targetVersion) {
return apiErrors.notFound('Video version');
}
// Calculate percentage
const safeDuration = duration || 0;
const percentage = safeDuration > 0 ? Math.min(100, (progress / safeDuration) * 100) : 0;
// Client already filters tiny deltas (<2s) before sending — safe to upsert directly.
const watchProgress = await db.watchProgress.upsert({
where: {
userId_versionId: {
userId: session.user.id,
versionId: targetVersion.id,
},
},
update: {
progress,
duration: safeDuration,
percentage,
},
create: {
userId: session.user.id,
versionId: targetVersion.id,
progress,
duration: safeDuration,
percentage,
},
});
return successResponse({
success: true,
progress: watchProgress.progress,
percentage: watchProgress.percentage,
});
} catch (error) {
logError('Error saving watch progress:', error);
return apiErrors.internalError('Failed to save watch progress');
if (!session?.user?.id) {
return apiErrors.unauthorized('Authentication required');
}
const { videoId } = await params;
const body = await request.json();
const { progress, duration, versionId } = body;
const MAX_VIDEO_SECONDS = 86_400; // 24 hours — reasonable upper bound for any video
if (
typeof progress !== 'number' ||
!isFinite(progress) ||
progress < 0 ||
progress > MAX_VIDEO_SECONDS
) {
return apiErrors.badRequest('Invalid progress value');
}
if (
duration !== undefined &&
(typeof duration !== 'number' ||
!isFinite(duration) ||
duration < 0 ||
duration > MAX_VIDEO_SECONDS)
) {
return apiErrors.badRequest('Invalid duration value');
}
if (versionId !== undefined && typeof versionId !== 'string') {
return apiErrors.badRequest('Invalid versionId');
}
// Always load the requested video and validate access before writing progress.
// If versionId is provided, verify it belongs to this video; otherwise resolve active version.
// Project access data is pre-fetched in the same query — no extra round-trips.
const userId = session.user.id;
const video = await db.video.findUnique({
where: { id: videoId },
include: {
project: { include: projectAccessInclude(userId) },
versions: {
where: versionId ? { id: versionId } : { isActive: true },
take: 1,
},
},
});
if (!video) {
return apiErrors.notFound('Video');
}
const access = computeProjectAccess(video.project, userId);
if (!access.hasAccess) {
return apiErrors.forbidden('Access denied');
}
const targetVersion = video.versions[0];
if (!targetVersion) {
return apiErrors.notFound('Video version');
}
// Calculate percentage
const safeDuration = duration || 0;
const percentage = safeDuration > 0 ? Math.min(100, (progress / safeDuration) * 100) : 0;
// Client already filters tiny deltas (<2s) before sending — safe to upsert directly.
const watchProgress = await db.watchProgress.upsert({
where: {
userId_versionId: {
userId: session.user.id,
versionId: targetVersion.id,
},
},
update: {
progress,
duration: safeDuration,
percentage,
},
create: {
userId: session.user.id,
versionId: targetVersion.id,
progress,
duration: safeDuration,
percentage,
},
});
return successResponse({
success: true,
progress: watchProgress.progress,
percentage: watchProgress.percentage,
});
} catch (error) {
logError('Error saving watch progress:', error);
return apiErrors.internalError('Failed to save watch progress');
}
}
+200 -191
View File
@@ -12,203 +12,212 @@ type RouteParams = { params: Promise<{ videoId: string }> };
// GET /api/watch/[videoId] - Public watch endpoint (no projectId needed)
export async function GET(request: NextRequest, { params }: RouteParams) {
try {
// Rate limit: 60 requests per minute per IP for public watch endpoint
const limited = await rateLimit(request, 'watch', { windowMs: 60 * 1000, maxRequests: 60 });
if (limited) return limited;
try {
// Rate limit: 60 requests per minute per IP for public watch endpoint
const limited = await rateLimit(request, 'watch', { windowMs: 60 * 1000, maxRequests: 60 });
if (limited) return limited;
const session = await auth();
const { videoId } = await params;
const session = await auth();
const { videoId } = await params;
// Parse query params
const searchParams = request.nextUrl.searchParams;
const includeComments = searchParams.get('includeComments') === 'true';
// Parse query params
const searchParams = request.nextUrl.searchParams;
const includeComments = searchParams.get('includeComments') === 'true';
const video = await db.video.findUnique({
where: { id: videoId },
include: {
project: true,
versions: {
orderBy: { versionNumber: 'desc' },
...(includeComments ? {
include: {
comments: {
orderBy: { timestamp: 'asc' },
where: { parentId: null },
select: {
id: true,
content: true,
timestamp: true,
timestampEnd: true,
createdAt: true,
updatedAt: true,
isResolved: true,
resolvedAt: true,
voiceUrl: true,
voiceDuration: true,
imageUrl: true,
annotationData: true,
parentId: true,
authorId: true,
guestIdentityId: true,
tagId: true,
versionId: true,
guestName: true,
author: { select: { id: true, name: true, image: true } },
tag: { select: { id: true, name: true, color: true } },
replies: {
orderBy: { createdAt: 'asc' },
select: {
id: true,
content: true,
timestamp: true,
timestampEnd: true,
createdAt: true,
updatedAt: true,
isResolved: true,
resolvedAt: true,
voiceUrl: true,
voiceDuration: true,
imageUrl: true,
annotationData: true,
parentId: true,
authorId: true,
guestIdentityId: true,
tagId: true,
versionId: true,
guestName: true,
author: { select: { id: true, name: true, image: true } },
tag: { select: { id: true, name: true, color: true } },
},
},
},
},
_count: { select: { comments: true } },
},
} : {
const video = await db.video.findUnique({
where: { id: videoId },
include: {
project: true,
versions: {
orderBy: { versionNumber: 'desc' },
...(includeComments
? {
include: {
comments: {
orderBy: { timestamp: 'asc' },
where: { parentId: null },
select: {
id: true,
content: true,
timestamp: true,
timestampEnd: true,
createdAt: true,
updatedAt: true,
isResolved: true,
resolvedAt: true,
voiceUrl: true,
voiceDuration: true,
imageUrl: true,
annotationData: true,
parentId: true,
authorId: true,
guestIdentityId: true,
tagId: true,
versionId: true,
guestName: true,
author: { select: { id: true, name: true, image: true } },
tag: { select: { id: true, name: true, color: true } },
replies: {
orderBy: { createdAt: 'asc' },
select: {
id: true,
thumbnailUrl: true,
duration: true,
versionNumber: true,
versionLabel: true,
providerId: true,
videoId: true,
originalUrl: true,
title: true,
isActive: true,
_count: { select: { comments: true } },
id: true,
content: true,
timestamp: true,
timestampEnd: true,
createdAt: true,
updatedAt: true,
isResolved: true,
resolvedAt: true,
voiceUrl: true,
voiceDuration: true,
imageUrl: true,
annotationData: true,
parentId: true,
authorId: true,
guestIdentityId: true,
tagId: true,
versionId: true,
guestName: true,
author: { select: { id: true, name: true, image: true } },
tag: { select: { id: true, name: true, color: true } },
},
}),
},
},
},
_count: { select: { comments: true } },
},
},
});
}
: {
select: {
id: true,
thumbnailUrl: true,
duration: true,
versionNumber: true,
versionLabel: true,
providerId: true,
videoId: true,
originalUrl: true,
title: true,
isActive: true,
_count: { select: { comments: true } },
},
}),
},
},
});
if (!video) {
return apiErrors.notFound('Video');
}
// Check access including workspace membership
const access = await checkProjectAccess(video.project, session?.user?.id);
const shareSession = getShareSessionFromRequest(request, video.id);
const shareAccess = shareSession
? await validateShareLinkAccess({
token: shareSession.token,
projectId: video.projectId,
videoId: video.id,
requiredPermission: 'VIEW',
passwordVerified: shareSession.passwordVerified,
})
: { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false };
if (!access.hasAccess && !shareAccess.hasAccess) {
return apiErrors.forbidden('Access denied');
}
// Include auth context so the client knows if the viewer is a guest
const { project, ...videoData } = video;
const viewerUserId = session?.user?.id ?? null;
const viewerGuestIdentityId = viewerUserId ? null : getGuestIdentityFromRequest(request);
const isProjectOwner = viewerUserId === project.ownerId;
const versions = videoData.versions.map((version) => {
if (!('comments' in version)) {
return version;
}
return {
...version,
comments: version.comments.map((comment) => {
const canEditComment = viewerUserId
? comment.authorId === viewerUserId
: !!viewerGuestIdentityId
&& !!comment.guestIdentityId
&& comment.guestIdentityId === viewerGuestIdentityId;
const canDeleteComment = canEditComment || isProjectOwner;
const replies = comment.replies;
const commentData = Object.fromEntries(
Object.entries(comment).filter(
([key]) => key !== 'authorId' && key !== 'guestIdentityId' && key !== 'replies'
)
);
return {
...commentData,
canEdit: canEditComment,
canDelete: canDeleteComment,
replies: replies.map((reply) => {
const canEditReply = viewerUserId
? reply.authorId === viewerUserId
: !!viewerGuestIdentityId
&& !!reply.guestIdentityId
&& reply.guestIdentityId === viewerGuestIdentityId;
const canDeleteReply = canEditReply || isProjectOwner;
const replyData = Object.fromEntries(
Object.entries(reply).filter(
([key]) => key !== 'authorId' && key !== 'guestIdentityId'
)
);
return {
...replyData,
canEdit: canEditReply,
canDelete: canDeleteReply,
};
}),
};
}),
};
});
const canCommentWithMembership = access.hasAccess;
const canCommentWithShareLink = shareAccess.canComment && (session?.user?.id ? true : shareAccess.allowGuests);
const canDownloadWithMembership = access.hasAccess;
const canDownloadWithShareLink = shareAccess.hasAccess && shareAccess.canDownload;
const canUploadAssets = canCommentWithMembership || canCommentWithShareLink;
const canDownloadAssets = !!session?.user?.id && (access.hasAccess || shareAccess.hasAccess);
const response = successResponse({
...videoData,
versions,
projectId: video.projectId,
project: {
name: project.name,
ownerId: project.ownerId,
visibility: project.visibility,
},
isAuthenticated: !!session?.user?.id,
currentUserId: session?.user?.id || null,
currentUserName: session?.user?.name || null,
canComment: canCommentWithMembership || canCommentWithShareLink,
canDownload: canDownloadWithMembership || canDownloadWithShareLink,
canManageTags: access.canEdit,
canResolveComments: access.canEdit,
canShareVideo: access.canEdit,
canUploadAssets,
canDownloadAssets,
});
return withCacheControl(response, 'private, no-cache');
} catch (error) {
logError('Error fetching video:', error);
return apiErrors.internalError('Failed to fetch video');
if (!video) {
return apiErrors.notFound('Video');
}
// Check access including workspace membership
const access = await checkProjectAccess(video.project, session?.user?.id);
const shareSession = getShareSessionFromRequest(request, video.id);
const shareAccess = shareSession
? await validateShareLinkAccess({
token: shareSession.token,
projectId: video.projectId,
videoId: video.id,
requiredPermission: 'VIEW',
passwordVerified: shareSession.passwordVerified,
})
: {
hasAccess: false,
canComment: false,
canDownload: false,
allowGuests: false,
requiresPassword: false,
};
if (!access.hasAccess && !shareAccess.hasAccess) {
return apiErrors.forbidden('Access denied');
}
// Include auth context so the client knows if the viewer is a guest
const { project, ...videoData } = video;
const viewerUserId = session?.user?.id ?? null;
const viewerGuestIdentityId = viewerUserId ? null : getGuestIdentityFromRequest(request);
const isProjectOwner = viewerUserId === project.ownerId;
const versions = videoData.versions.map((version) => {
if (!('comments' in version)) {
return version;
}
return {
...version,
comments: version.comments.map((comment) => {
const canEditComment = viewerUserId
? comment.authorId === viewerUserId
: !!viewerGuestIdentityId &&
!!comment.guestIdentityId &&
comment.guestIdentityId === viewerGuestIdentityId;
const canDeleteComment = canEditComment || isProjectOwner;
const replies = comment.replies;
const commentData = Object.fromEntries(
Object.entries(comment).filter(
([key]) => key !== 'authorId' && key !== 'guestIdentityId' && key !== 'replies'
)
);
return {
...commentData,
canEdit: canEditComment,
canDelete: canDeleteComment,
replies: replies.map((reply) => {
const canEditReply = viewerUserId
? reply.authorId === viewerUserId
: !!viewerGuestIdentityId &&
!!reply.guestIdentityId &&
reply.guestIdentityId === viewerGuestIdentityId;
const canDeleteReply = canEditReply || isProjectOwner;
const replyData = Object.fromEntries(
Object.entries(reply).filter(
([key]) => key !== 'authorId' && key !== 'guestIdentityId'
)
);
return {
...replyData,
canEdit: canEditReply,
canDelete: canDeleteReply,
};
}),
};
}),
};
});
const canCommentWithMembership = access.hasAccess;
const canCommentWithShareLink =
shareAccess.canComment && (session?.user?.id ? true : shareAccess.allowGuests);
const canDownloadWithMembership = access.hasAccess;
const canDownloadWithShareLink = shareAccess.hasAccess && shareAccess.canDownload;
const canUploadAssets = canCommentWithMembership || canCommentWithShareLink;
const canDownloadAssets = !!session?.user?.id && (access.hasAccess || shareAccess.hasAccess);
const response = successResponse({
...videoData,
versions,
projectId: video.projectId,
project: {
name: project.name,
ownerId: project.ownerId,
visibility: project.visibility,
},
isAuthenticated: !!session?.user?.id,
currentUserId: session?.user?.id || null,
currentUserName: session?.user?.name || null,
canComment: canCommentWithMembership || canCommentWithShareLink,
canDownload: canDownloadWithMembership || canDownloadWithShareLink,
canManageTags: access.canEdit,
canResolveComments: access.canEdit,
canShareVideo: access.canEdit,
canUploadAssets,
canDownloadAssets,
});
return withCacheControl(response, 'private, no-cache');
} catch (error) {
logError('Error fetching video:', error);
return apiErrors.internalError('Failed to fetch video');
}
}
+13 -7
View File
@@ -64,13 +64,19 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
const shareSession = getShareSessionFromRequest(request, video.id);
const shareAccess = shareSession
? await validateShareLinkAccess({
token: shareSession.token,
projectId: video.projectId,
videoId: video.id,
requiredPermission: 'COMMENT',
passwordVerified: shareSession.passwordVerified,
})
: { hasAccess: false, canComment: false, canDownload: false, allowGuests: false, requiresPassword: false };
token: shareSession.token,
projectId: video.projectId,
videoId: video.id,
requiredPermission: 'COMMENT',
passwordVerified: shareSession.passwordVerified,
})
: {
hasAccess: false,
canComment: false,
canDownload: false,
allowGuests: false,
requiresPassword: false,
};
const canCommentWithMembership = !!session?.user?.id && access.hasAccess;
const canCommentWithShareLink = shareAccess.canComment && shareAccess.allowGuests;