video.service.ts163 lines, 4.5 KB
| 1 | import path from "path"; |
| 2 | import { AppDataSource } from "../config/database"; |
| 3 | import { Video } from "../entities/video.entity"; |
| 4 | import { mkdir } from "fs/promises"; |
| 5 | import youtubeDl from "youtube-dl-exec"; |
| 6 | import ffmpeg from "@ffmpeg-installer/ffmpeg"; |
| 7 | import { AppError } from "../utils/errors"; |
| 8 | import { StatusCodes } from "http-status-codes"; |
| 9 | import ytdl from "ytdl-core"; |
| 10 | import logger from "../utils/logger"; |
| 11 | |
| 12 | export interface VideoInfo { |
| 13 | title: string; |
| 14 | description: string; |
| 15 | duration: number; |
| 16 | author: string; |
| 17 | videoUrl: string; |
| 18 | thumbnail: string; |
| 19 | audioPath?: string; |
| 20 | } |
| 21 | |
| 22 | type YoutubeDLOutput = { |
| 23 | title: string; |
| 24 | description?: string; |
| 25 | duration: number; |
| 26 | uploader: string; |
| 27 | thumbnail: string; |
| 28 | } & Record<string, unknown>; |
| 29 | |
| 30 | export class VideoService { |
| 31 | private static readonly AUDIO_DIR = path.join(process.cwd(), "temp", "audio"); |
| 32 | private static readonly videoRepository = AppDataSource.getRepository(Video); |
| 33 | |
| 34 | static async getUserVideos(userId: string): Promise<Video[]> { |
| 35 | return this.videoRepository.find({ |
| 36 | where: { user: { id: userId } }, |
| 37 | relations: ["transcription", "analysis"], |
| 38 | order: { createdAt: "DESC" }, |
| 39 | }); |
| 40 | } |
| 41 | |
| 42 | static async getVideoById(id: string, userId: string): Promise<Video | null> { |
| 43 | const video = await this.videoRepository.findOne({ |
| 44 | where: { |
| 45 | id, |
| 46 | user: { id: userId }, |
| 47 | }, |
| 48 | relations: ["transcription", "analysis"], |
| 49 | }); |
| 50 | |
| 51 | if (!video) { |
| 52 | throw new AppError(StatusCodes.NOT_FOUND, "Video not found"); |
| 53 | } |
| 54 | |
| 55 | return video; |
| 56 | } |
| 57 | |
| 58 | static async ensureDirectoryExists() { |
| 59 | await mkdir(VideoService.AUDIO_DIR, { recursive: true }); |
| 60 | } |
| 61 | |
| 62 | static async getVideoInfo(url: string): Promise<VideoInfo> { |
| 63 | try { |
| 64 | //Get video info from youtube-dl |
| 65 | const rawInfo = await youtubeDl(url, { |
| 66 | dumpSingleJson: true, |
| 67 | noWarnings: true, |
| 68 | preferFreeFormats: true, |
| 69 | ffmpegLocation: ffmpeg.path, |
| 70 | }); |
| 71 | |
| 72 | const info = rawInfo as YoutubeDLOutput; |
| 73 | |
| 74 | if (!info.title || !info.uploader || typeof info.duration !== "number") { |
| 75 | throw new AppError(StatusCodes.BAD_REQUEST, "Invalid video info"); |
| 76 | } |
| 77 | |
| 78 | // get the best quality thumbnail |
| 79 | const thumbnail = |
| 80 | info.thumbnail || |
| 81 | (info as any).thumbnails?.[0]?.url || |
| 82 | `https://i.ytimg.com/vi/${ytdl.getVideoID(url)}/maxresdefault.jpg`; |
| 83 | |
| 84 | return { |
| 85 | title: info.title, |
| 86 | description: info.description || "", |
| 87 | duration: info.duration, |
| 88 | author: info.uploader, |
| 89 | videoUrl: url, |
| 90 | thumbnail: thumbnail, |
| 91 | }; |
| 92 | } catch (error) { |
| 93 | logger.error("Error getting video info", { error }); |
| 94 | if (error instanceof Error) { |
| 95 | if (error.message.includes("Private video")) { |
| 96 | throw new AppError(StatusCodes.FORBIDDEN, "This video is private"); |
| 97 | } |
| 98 | if (error.message.includes("not available")) { |
| 99 | throw new AppError(StatusCodes.NOT_FOUND, "Video not found"); |
| 100 | } |
| 101 | throw new AppError( |
| 102 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 103 | "Failed to get video info" |
| 104 | ); |
| 105 | } |
| 106 | throw new AppError( |
| 107 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 108 | "Failed to get video info" |
| 109 | ); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | static async downloadAudio(url: string): Promise<string> { |
| 114 | try { |
| 115 | await this.ensureDirectoryExists(); |
| 116 | |
| 117 | // extract video id from url |
| 118 | const videoId = ytdl.getVideoID(url); |
| 119 | const audioPath = path.join(this.AUDIO_DIR, `${videoId}.mp3`); |
| 120 | |
| 121 | // download audio |
| 122 | await youtubeDl(url, { |
| 123 | extractAudio: true, |
| 124 | audioFormat: "mp3", |
| 125 | audioQuality: 0, // best quality |
| 126 | output: audioPath, |
| 127 | noWarnings: true, |
| 128 | preferFreeFormats: true, |
| 129 | ffmpegLocation: ffmpeg.path, |
| 130 | }); |
| 131 | |
| 132 | const fileStats = await import("fs/promises").then((fs) => |
| 133 | fs.stat(audioPath) |
| 134 | ); |
| 135 | if (fileStats.size === 0) { |
| 136 | throw new AppError( |
| 137 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 138 | "Failed to download audio" |
| 139 | ); |
| 140 | } |
| 141 | |
| 142 | return audioPath; |
| 143 | } catch (error) { |
| 144 | logger.error("Error downloading audio", { error }); |
| 145 | if (error instanceof Error) { |
| 146 | if (error.message.includes("ffmpeg")) { |
| 147 | throw new AppError( |
| 148 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 149 | "Failed to download audio" |
| 150 | ); |
| 151 | } |
| 152 | throw new AppError( |
| 153 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 154 | "Failed to download audio" |
| 155 | ); |
| 156 | } |
| 157 | throw new AppError( |
| 158 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 159 | "Failed to download audio" |
| 160 | ); |
| 161 | } |
| 162 | } |
| 163 | } |