71 lines
2.3 KiB
TypeScript
71 lines
2.3 KiB
TypeScript
import FilesRepository from "@Repositories/FilesRepository";
|
|
import BaseService from "@Services/BaseService";
|
|
import { Service } from "typedi";
|
|
import { File } from "le-coffre-resources/dist/SuperAdmin"
|
|
import CryptoService from "../CryptoService/CryptoService";
|
|
import IpfsService from "../IpfsService/IpfsService";
|
|
//import fs from "fs";
|
|
import { BackendVariables } from "@Common/config/variables/Variables";
|
|
import { Readable } from "stream";
|
|
|
|
@Service()
|
|
export default class FilesService extends BaseService {
|
|
constructor(private filesRepository: FilesRepository, private ipfsService: IpfsService, private variables: BackendVariables, private cryptoService: CryptoService) {
|
|
super();
|
|
}
|
|
|
|
/**
|
|
* @description : Get all files
|
|
* @throws {Error} If files cannot be ge
|
|
*/
|
|
public async get(query: any) {
|
|
return this.filesRepository.findMany(query);
|
|
}
|
|
|
|
/**
|
|
* @description : Create a new file
|
|
* @throws {Error} If file cannot be created
|
|
*/
|
|
public async create(file: File, fileData: Express.Multer.File) {
|
|
const upload = await this.ipfsService.pinFile(Readable.from(fileData.buffer), fileData.originalname);
|
|
const encryptedPath = await this.cryptoService.encrypt(this.variables.PINATA_GATEWAY.concat(upload.IpfsHash));
|
|
file.file_name = fileData.originalname;
|
|
file.file_path = encryptedPath.cipherText;
|
|
file.iv = encryptedPath.ivStringified;
|
|
return this.filesRepository.create(file);
|
|
}
|
|
|
|
/**
|
|
* @description : Modify a new file
|
|
* @throws {Error} If file cannot be modified
|
|
*/
|
|
public async update(uid: string, file: File) {
|
|
return this.filesRepository.update(uid, file);
|
|
}
|
|
|
|
/**
|
|
* @description : Delete a file
|
|
* @throws {Error} If file cannot be deleted
|
|
*/
|
|
public async delete(uid: string) {
|
|
try {
|
|
const fileToUnpin = await this.filesRepository.findOneByUid(uid);
|
|
const decryptedFilePath = await this.cryptoService.decrypt(fileToUnpin.file_path, fileToUnpin.iv);
|
|
const fileHash= decryptedFilePath.substring(this.variables.PINATA_GATEWAY.length);
|
|
await this.ipfsService.unpinFile(fileHash)
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
|
|
return this.filesRepository.delete(uid);
|
|
}
|
|
|
|
/**
|
|
* @description : Get a file by uid
|
|
* @throws {Error} If project cannot be created
|
|
*/
|
|
public async getByUid(uid: string) {
|
|
return this.filesRepository.findOneByUid(uid);
|
|
}
|
|
}
|