Files
project-fileshare/apps/backend/src/modules/share-links/share-links.service.ts

584 lines
18 KiB
TypeScript
Raw Normal View History

2026-10-29 13:21:30 +06:00
import {
Injectable,
NotFoundException,
ForbiddenException,
BadRequestException,
UnauthorizedException,
Inject,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditService } from '../audit/audit.service';
import { STORAGE_PROVIDER, IStorageProvider } from '../storage/storage.interface';
import { CreateShareLinkDto } from './dto/create-share-link.dto';
import { ShareResourceType, UserRole } from '@prisma/client';
import * as crypto from 'crypto';
import * as argon2 from 'argon2';
@Injectable()
export class ShareLinksService {
constructor(
private readonly prisma: PrismaService,
private readonly auditService: AuditService,
@Inject(STORAGE_PROVIDER) private readonly storageProvider: IStorageProvider,
) {}
/**
* Create a Google Drive-like share link
*/
async createShareLink(
userId: string,
userRole: string,
dto: CreateShareLinkDto,
ipAddress?: string,
userAgent?: string,
) {
// 1. Verify user has permission to create share links (Superadmin decides who can share)
if (userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
const user = await this.prisma.user.findUnique({
where: { id: userId },
select: { canCreateShareLinks: true },
});
if (!user?.canCreateShareLinks) {
throw new ForbiddenException(
'You do not have permission to create share links. Please contact an administrator.',
);
}
}
let fileId: string | null = null;
let folderId: string | null = null;
let defaultTitle = dto.title?.trim() || '';
// 2. Validate Resource & Ownership
if (dto.resourceType === ShareResourceType.FILE) {
if (!dto.fileId) {
throw new BadRequestException('fileId is required when sharing a file');
}
const file = await this.prisma.fileAsset.findUnique({
where: { id: dto.fileId },
});
if (!file || file.isSoftDeleted) {
throw new NotFoundException('File not found or has been deleted');
}
if (file.ownerId !== userId && userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
throw new ForbiddenException('You can only create share links for your own files');
}
fileId = file.id;
if (!defaultTitle) defaultTitle = file.originalFilename;
} else if (dto.resourceType === ShareResourceType.FOLDER) {
if (!dto.folderId) {
throw new BadRequestException('folderId is required when sharing a folder');
}
const folder = await this.prisma.folder.findUnique({
where: { id: dto.folderId },
});
if (!folder) {
throw new NotFoundException('Folder not found');
}
if (folder.ownerId !== userId && userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
throw new ForbiddenException('You can only create share links for your own folders');
}
folderId = folder.id;
if (!defaultTitle) defaultTitle = folder.name;
} else {
throw new BadRequestException('Invalid resource type');
}
// 3. Password hashing (if password protected)
let passwordHash: string | null = null;
if (dto.password && dto.password.trim()) {
passwordHash = await argon2.hash(dto.password.trim(), { type: argon2.argon2id });
}
// 4. Calculate expiry
let expiresAt: Date | null = null;
if (dto.expiresInDays && dto.expiresInDays > 0) {
expiresAt = new Date(Date.now() + dto.expiresInDays * 24 * 60 * 60 * 1000);
}
// 5. Generate unique secure URL-safe token (24 hex characters)
const token = crypto.randomBytes(16).toString('hex');
const shareLink = await this.prisma.shareLink.create({
data: {
token,
title: defaultTitle,
ownerId: userId,
resourceType: dto.resourceType,
fileId,
folderId,
allowDownload: dto.allowDownload !== undefined ? dto.allowDownload : true,
passwordHash,
expiresAt,
isActive: true,
},
include: {
file: {
select: {
id: true,
originalFilename: true,
fileSizeBytes: true,
mimeType: true,
fileCategory: true,
},
},
folder: {
select: {
id: true,
name: true,
logicalPath: true,
},
},
},
});
await this.auditService.log({
actorUserId: userId,
action: 'SHARE_LINK_CREATED',
resourceType: dto.resourceType === ShareResourceType.FILE ? 'FILE' : 'FOLDER',
resourceId: (fileId || folderId) as string,
targetUserId: userId,
ipAddress,
userAgent,
details: {
token: shareLink.token,
resourceType: shareLink.resourceType,
allowDownload: shareLink.allowDownload,
hasPassword: !!passwordHash,
expiresAt: shareLink.expiresAt,
},
});
return {
id: shareLink.id,
token: shareLink.token,
title: shareLink.title,
resourceType: shareLink.resourceType,
fileId: shareLink.fileId,
folderId: shareLink.folderId,
allowDownload: shareLink.allowDownload,
hasPassword: !!shareLink.passwordHash,
expiresAt: shareLink.expiresAt,
viewCount: shareLink.viewCount,
downloadCount: shareLink.downloadCount,
createdAt: shareLink.createdAt,
file: shareLink.file
? {
...shareLink.file,
fileSizeBytes: shareLink.file.fileSizeBytes.toString(),
}
: null,
folder: shareLink.folder,
};
}
/**
* Get all share links created by current user
*/
async getMyShareLinks(userId: string) {
const links = await this.prisma.shareLink.findMany({
where: { ownerId: userId, isActive: true },
orderBy: { createdAt: 'desc' },
include: {
file: {
select: {
id: true,
originalFilename: true,
fileSizeBytes: true,
mimeType: true,
fileCategory: true,
},
},
folder: {
select: {
id: true,
name: true,
logicalPath: true,
},
},
},
});
return links.map((l) => ({
id: l.id,
token: l.token,
title: l.title,
resourceType: l.resourceType,
fileId: l.fileId,
folderId: l.folderId,
allowDownload: l.allowDownload,
hasPassword: !!l.passwordHash,
expiresAt: l.expiresAt,
viewCount: l.viewCount,
downloadCount: l.downloadCount,
isActive: l.isActive,
createdAt: l.createdAt,
file: l.file
? {
...l.file,
fileSizeBytes: l.file.fileSizeBytes.toString(),
}
: null,
folder: l.folder,
}));
}
/**
* Revoke or delete a share link
*/
async revokeShareLink(userId: string, userRole: string, linkId: string) {
const link = await this.prisma.shareLink.findUnique({ where: { id: linkId } });
if (!link) throw new NotFoundException('Share link not found');
if (link.ownerId !== userId && userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
throw new ForbiddenException('Unauthorized to revoke this share link');
}
await this.prisma.shareLink.delete({ where: { id: linkId } });
await this.auditService.log({
actorUserId: userId,
action: 'SHARE_LINK_REVOKED',
resourceType: link.resourceType === ShareResourceType.FILE ? 'FILE' : 'FOLDER',
resourceId: linkId,
details: { token: link.token },
});
return { success: true, message: 'Share link revoked successfully' };
}
/**
* Validate a public link token, check expiration & password
*/
private async validateAndGetLink(token: string, password?: string) {
const link = await this.prisma.shareLink.findUnique({
where: { token },
include: {
owner: { select: { id: true, username: true, fullName: true } },
},
});
if (!link || !link.isActive) {
throw new NotFoundException('This shared link does not exist or has been disabled');
}
if (link.expiresAt && link.expiresAt < new Date()) {
throw new BadRequestException('This share link has expired');
}
if (link.passwordHash) {
if (!password) {
return { link, requiresPassword: true as const };
}
const isMatch = await argon2.verify(link.passwordHash, password);
if (!isMatch) {
throw new UnauthorizedException('Incorrect password for this shared link');
}
}
return { link, requiresPassword: false as const };
}
/**
* Public View: Get shared file or folder metadata and items
*/
async getPublicResource(token: string, password?: string, subfolderId?: string) {
const validation = await this.validateAndGetLink(token, password);
const { link } = validation;
if (validation.requiresPassword) {
return {
requiresPassword: true,
title: link.title,
resourceType: link.resourceType,
ownerName: link.owner.fullName,
};
}
// Increment view count asynchronously
await this.prisma.shareLink.update({
where: { id: link.id },
data: { viewCount: { increment: 1 } },
});
// Case 1: Shared FILE
if (link.resourceType === ShareResourceType.FILE) {
const file = await this.prisma.fileAsset.findUnique({
where: { id: link.fileId as string },
});
if (!file || file.isSoftDeleted) {
throw new NotFoundException('The shared file has been removed or deleted');
}
return {
requiresPassword: false,
resourceType: ShareResourceType.FILE,
title: link.title || file.originalFilename,
allowDownload: link.allowDownload,
ownerName: link.owner.fullName,
createdAt: link.createdAt,
expiresAt: link.expiresAt,
file: {
id: file.id,
originalFilename: file.originalFilename,
mimeType: file.mimeType,
fileExtension: file.fileExtension,
fileSizeBytes: file.fileSizeBytes.toString(),
fileCategory: file.fileCategory,
status: file.status,
durationSeconds: file.durationSeconds,
width: file.width,
height: file.height,
hasHlsStream: !!file.hlsMasterPlaylistKey,
hasThumbnail: !!file.thumbnailStorageKey,
createdAt: file.createdAt,
},
};
}
// Case 2: Shared FOLDER
const rootSharedFolder = await this.prisma.folder.findUnique({
where: { id: link.folderId as string },
});
if (!rootSharedFolder) {
throw new NotFoundException('The shared folder has been removed or deleted');
}
// If browsing a subfolder, verify that subfolderId is descendant of rootSharedFolder
let currentFolder = rootSharedFolder;
if (subfolderId && subfolderId !== rootSharedFolder.id) {
const candidateFolder = await this.prisma.folder.findUnique({
where: { id: subfolderId },
});
if (!candidateFolder) {
throw new NotFoundException('Subfolder not found');
}
// Verify hierarchy: candidateFolder must reside under rootSharedFolder.logicalPath
if (
!candidateFolder.logicalPath.startsWith(rootSharedFolder.logicalPath) ||
candidateFolder.ownerId !== rootSharedFolder.ownerId
) {
throw new ForbiddenException('Access denied: Cannot browse outside the shared folder');
}
currentFolder = candidateFolder;
}
// Load subfolders in current folder
const subfolders = await this.prisma.folder.findMany({
where: { parentId: currentFolder.id },
orderBy: { name: 'asc' },
select: {
id: true,
name: true,
logicalPath: true,
createdAt: true,
_count: {
select: { files: { where: { isSoftDeleted: false } }, children: true },
},
},
});
// Load files in current folder
const files = await this.prisma.fileAsset.findMany({
where: { folderId: currentFolder.id, isSoftDeleted: false },
orderBy: { createdAt: 'desc' },
select: {
id: true,
originalFilename: true,
mimeType: true,
fileExtension: true,
fileSizeBytes: true,
fileCategory: true,
status: true,
durationSeconds: true,
width: true,
height: true,
thumbnailStorageKey: true,
hlsMasterPlaylistKey: true,
createdAt: true,
},
});
return {
requiresPassword: false,
resourceType: ShareResourceType.FOLDER,
title: link.title || rootSharedFolder.name,
allowDownload: link.allowDownload,
ownerName: link.owner.fullName,
createdAt: link.createdAt,
expiresAt: link.expiresAt,
rootFolderId: rootSharedFolder.id,
currentFolder: {
id: currentFolder.id,
name: currentFolder.name,
logicalPath: currentFolder.logicalPath,
isRootOfShare: currentFolder.id === rootSharedFolder.id,
},
subfolders: subfolders.map((f) => ({
id: f.id,
name: f.name,
logicalPath: f.logicalPath,
fileCount: f._count.files,
subfolderCount: f._count.children,
createdAt: f.createdAt,
})),
files: files.map((f) => ({
id: f.id,
originalFilename: f.originalFilename,
mimeType: f.mimeType,
fileExtension: f.fileExtension,
fileSizeBytes: f.fileSizeBytes.toString(),
fileCategory: f.fileCategory,
status: f.status,
durationSeconds: f.durationSeconds,
width: f.width,
height: f.height,
hasThumbnail: !!f.thumbnailStorageKey,
hasHlsStream: !!f.hlsMasterPlaylistKey,
createdAt: f.createdAt,
})),
};
}
/**
* Helper to verify file belongs to shared resource
*/
private async resolveSharedFile(link: any, requestedFileId?: string) {
if (link.resourceType === ShareResourceType.FILE) {
return this.prisma.fileAsset.findUnique({
where: { id: link.fileId, isSoftDeleted: false },
});
}
if (!requestedFileId) {
throw new BadRequestException('fileId is required when accessing a file in a shared folder');
}
const file = await this.prisma.fileAsset.findUnique({
where: { id: requestedFileId, isSoftDeleted: false },
include: { folder: true },
});
if (!file || !file.folder) {
throw new NotFoundException('File not found in shared folder');
}
// Verify folder hierarchy
const rootSharedFolder = await this.prisma.folder.findUnique({
where: { id: link.folderId },
});
if (
!rootSharedFolder ||
!file.folder.logicalPath.startsWith(rootSharedFolder.logicalPath) ||
file.ownerId !== rootSharedFolder.ownerId
) {
throw new ForbiddenException('Access denied: File does not belong to this shared folder');
}
return file;
}
/**
* Public Stream (Video playback with HTTP Range support)
*/
async streamPublicVideo(
token: string,
requestedFileId?: string,
rangeHeader?: string,
password?: string,
) {
const validation = await this.validateAndGetLink(token, password);
if (validation.requiresPassword) {
throw new UnauthorizedException('Password required for streaming');
}
const file = await this.resolveSharedFile(validation.link, requestedFileId);
if (!file) throw new NotFoundException('File not found');
const totalSize = await this.storageProvider.getSize(file.internalStorageKey);
if (rangeHeader) {
const parts = rangeHeader.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : totalSize - 1;
const chunkSize = end - start + 1;
const { stream } = await this.storageProvider.getStream(file.internalStorageKey, {
start,
end,
});
return {
isRange: true,
start,
end,
totalSize,
chunkSize,
mimeType: file.mimeType || 'video/mp4',
stream,
};
}
const { stream, contentType } = await this.storageProvider.getStream(file.internalStorageKey);
return {
isRange: false,
totalSize,
mimeType: contentType || file.mimeType || 'video/mp4',
stream,
};
}
/**
* Public Thumbnail Stream
*/
async getPublicThumbnail(token: string, requestedFileId?: string, password?: string) {
const validation = await this.validateAndGetLink(token, password);
if (validation.requiresPassword) {
throw new UnauthorizedException('Password required');
}
const file = await this.resolveSharedFile(validation.link, requestedFileId);
if (!file || !file.thumbnailStorageKey) {
throw new NotFoundException('Thumbnail not available');
}
return this.storageProvider.getStream(file.thumbnailStorageKey);
}
/**
* Public Download
*/
async downloadPublicFile(token: string, requestedFileId?: string, password?: string) {
const validation = await this.validateAndGetLink(token, password);
if (validation.requiresPassword) {
throw new UnauthorizedException('Password required');
}
const { link } = validation;
if (!link.allowDownload) {
throw new ForbiddenException('Downloading is disabled for this shared link');
}
const file = await this.resolveSharedFile(link, requestedFileId);
if (!file) throw new NotFoundException('File not found');
// Increment download count
await this.prisma.shareLink.update({
where: { id: link.id },
data: { downloadCount: { increment: 1 } },
});
const { stream, contentType } = await this.storageProvider.getStream(file.internalStorageKey);
return {
stream,
file,
contentType: contentType || file.mimeType || 'application/octet-stream',
};
}
}