diff --git a/packages/server/src/controllers/FilesController/index.js b/packages/server/src/controllers/FilesController/index.js index 609dbef6..8e564866 100644 --- a/packages/server/src/controllers/FilesController/index.js +++ b/packages/server/src/controllers/FilesController/index.js @@ -2,7 +2,6 @@ import { Controller } from "linebridge/dist/server" import path from "path" import fs from "fs" import stream from "stream" - const formidable = require("formidable") function resolveToUrl(filepath, req) { @@ -25,31 +24,39 @@ const acceptedMimeTypes = [ "video/x-ms-wmv", ] -function transcodeVideoToWebM(originalFilePath, outputPath) { +function videoTranscode(originalFilePath, outputPath, options = {}) { return new Promise((resolve, reject) => { const ffmpeg = require("fluent-ffmpeg") const filename = path.basename(originalFilePath) - const outputFilepath = `${outputPath}/${filename.split(".")[0]}.webm` + const outputFilepath = `${outputPath}/${filename.split(".")[0]}.${options.format ?? "webm"}` - console.log(`[TRANSCODING] Transcoding ${originalFilePath} to ${outputFilepath}`) + console.debug(`[TRANSCODING] Transcoding ${originalFilePath} to ${outputFilepath}`) + + const onEnd = async () => { + // remove + await fs.promises.unlink(originalFilePath) + + console.debug(`[TRANSCODING] Transcoding ${originalFilePath} to ${outputFilepath} finished`) + + return resolve(outputFilepath) + } + + const onError = (err) => { + console.error(`[TRANSCODING] Transcoding ${originalFilePath} to ${outputFilepath} failed`, err) + + return reject(err) + } ffmpeg(originalFilePath) - .audioBitrate(128) - .videoBitrate(1024) - .videoCodec("libvpx") - .audioCodec("libvorbis") - .format("webm") + .audioBitrate(options.audioBitrate ?? 128) + .videoBitrate(options.videoBitrate ?? 1024) + .videoCodec(options.videoCodec ?? "libvpx") + .audioCodec(options.audioCodec ?? "libvorbis") + .format(options.format ?? "webm") .output(outputFilepath) - .on("error", (err) => { - console.log("Error: " + err.message) - - return reject(err) - }) - .on("end", () => { - console.log("[Transcoding finished]") - return resolve(outputFilepath) - }) + .on("error", onError) + .on("end", onEnd) .run() }) } @@ -122,7 +129,7 @@ export default class FilesController extends Controller { // check if is video need to transcode switch (file.mimetype) { case "video/quicktime": { - file.filepath = await transcodeVideoToWebM(file.filepath, global.uploadCachePath) + file.filepath = await videoTranscode(file.filepath, global.uploadCachePath) file.newFilename = path.basename(file.filepath) break }