MediaService: Implement delete feature

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2020-10-17 21:54:08 +02:00
parent db869418d4
commit 9e7e15a20a
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
2 changed files with 37 additions and 1 deletions

View file

@ -5,3 +5,7 @@ export class NotInDBError extends Error {
export class ClientError extends Error {
name = 'ClientError';
}
export class PermissionError extends Error {
name = 'PermissionError';
}

View file

@ -3,7 +3,7 @@ import { ModuleRef } from '@nestjs/core';
import { InjectRepository } from '@nestjs/typeorm';
import * as FileType from 'file-type';
import { Repository } from 'typeorm';
import { ClientError } from '../errors/errors';
import { ClientError, NotInDBError, PermissionError } from '../errors/errors';
import { ConsoleLoggerService } from '../logger/console-logger.service';
import { NotesService } from '../notes/notes.service';
import { UsersService } from '../users/users.service';
@ -75,4 +75,36 @@ export class MediaService {
await this.mediaUploadRepository.save(mediaUpload);
return url;
}
public async deleteFile(filename: string, username: string) {
this.logger.debug(
`Deleting '${filename}' for user '${username}'`,
'deleteFile',
);
const mediaUpload = await this.findUploadByFilename(filename);
if (mediaUpload.user.userName !== username) {
this.logger.warn(
`${username} tried to delete '${filename}', but is not the owner`,
'deleteFile',
);
throw new PermissionError(
`File '${filename}' is not owned by '${username}'`,
);
}
const backend = this.moduleRef.get(FilesystemBackend);
await backend.deleteFile(filename, mediaUpload.backendData);
await this.mediaUploadRepository.remove(mediaUpload);
}
public async findUploadByFilename(filename: string): Promise<MediaUpload> {
const mediaUpload = await this.mediaUploadRepository.findOne(filename, {
relations: ['user'],
});
if (mediaUpload === undefined) {
throw new NotInDBError(
`MediaUpload with filename '${filename}' not found`,
);
}
return mediaUpload;
}
}