|
| 1 | +import shortid from "shortid"; |
| 2 | +import * as fs from "fs"; |
| 3 | +import { writeFile } from "fs/promises"; |
| 4 | +import { encodedVideoExtentionCheck } from "./encodedVideoExtensionCheck"; |
| 5 | +import { errors, requestContext } from "../../libraries"; |
| 6 | +import { INVALID_FILE_TYPE } from "../../constants"; |
| 7 | +import { EncodedVideo } from "../../models/EncodedVideo"; |
| 8 | +import path from "path"; |
| 9 | +import { deletePreviousVideo } from "./deletePreviousVideo"; |
| 10 | + |
| 11 | +export const uploadEncodedVideo = async ( |
| 12 | + encodedVideoURL: string, |
| 13 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 14 | + previousVideoPath?: string | null |
| 15 | +): Promise<string> => { |
| 16 | + const isURLValidVideo = encodedVideoExtentionCheck(encodedVideoURL); |
| 17 | + |
| 18 | + if (!isURLValidVideo) { |
| 19 | + throw new errors.InvalidFileTypeError( |
| 20 | + requestContext.translate(INVALID_FILE_TYPE.MESSAGE), |
| 21 | + INVALID_FILE_TYPE.CODE, |
| 22 | + INVALID_FILE_TYPE.PARAM |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + const encodedVideoAlreadyExist = await EncodedVideo.findOne({ |
| 27 | + content: encodedVideoURL, |
| 28 | + }); |
| 29 | + |
| 30 | + if (previousVideoPath) { |
| 31 | + await deletePreviousVideo(previousVideoPath); |
| 32 | + } |
| 33 | + |
| 34 | + if (encodedVideoAlreadyExist) { |
| 35 | + await EncodedVideo.findOneAndUpdate( |
| 36 | + { |
| 37 | + content: encodedVideoURL, |
| 38 | + }, |
| 39 | + { |
| 40 | + $inc: { |
| 41 | + numberOfUses: 1, |
| 42 | + }, |
| 43 | + } |
| 44 | + ); |
| 45 | + return encodedVideoAlreadyExist.fileName; |
| 46 | + } |
| 47 | + |
| 48 | + let id = shortid.generate(); |
| 49 | + |
| 50 | + id = "videos/" + id + "video.mp4"; |
| 51 | + |
| 52 | + const uploadedEncodedVideo = await EncodedVideo.create({ |
| 53 | + fileName: id, |
| 54 | + content: encodedVideoURL, |
| 55 | + }); |
| 56 | + |
| 57 | + const data = encodedVideoURL.replace(/^data:video\/\w+;base64,/, ""); |
| 58 | + |
| 59 | + const buf = Buffer.from(data, "base64"); |
| 60 | + |
| 61 | + if (!fs.existsSync(path.join(__dirname, "../../../videos"))) { |
| 62 | + fs.mkdir(path.join(__dirname, "../../../videos"), (error) => { |
| 63 | + if (error) { |
| 64 | + throw error; |
| 65 | + } |
| 66 | + }); |
| 67 | + } |
| 68 | + |
| 69 | + await writeFile(path.join(__dirname, "../../../" + id), buf); |
| 70 | + |
| 71 | + return uploadedEncodedVideo.fileName; |
| 72 | +}; |
0 commit comments