28a03d19ecdfb2dceae4b35ee6cb766e004bd415
[oweals/peertube.git] / server / lib / job-queue / handlers / video-import.ts
1 import * as Bull from 'bull'
2 import { logger } from '../../../helpers/logger'
3 import { downloadYoutubeDLVideo } from '../../../helpers/youtube-dl'
4 import { VideoImportModel } from '../../../models/video/video-import'
5 import { VideoImportState } from '../../../../shared/models/videos'
6 import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
7 import { extname, join } from 'path'
8 import { VideoFileModel } from '../../../models/video/video-file'
9 import { renamePromise, statPromise, unlinkPromise } from '../../../helpers/core-utils'
10 import { CONFIG, sequelizeTypescript } from '../../../initializers'
11 import { doRequestAndSaveToFile } from '../../../helpers/requests'
12 import { VideoState } from '../../../../shared'
13 import { JobQueue } from '../index'
14 import { federateVideoIfNeeded } from '../../activitypub'
15 import { VideoModel } from '../../../models/video/video'
16 import { downloadWebTorrentVideo } from '../../../helpers/webtorrent'
17 import { getSecureTorrentName } from '../../../helpers/utils'
18
19 type VideoImportYoutubeDLPayload = {
20   type: 'youtube-dl'
21   videoImportId: number
22
23   thumbnailUrl: string
24   downloadThumbnail: boolean
25   downloadPreview: boolean
26 }
27
28 type VideoImportTorrentPayload = {
29   type: 'magnet-uri' | 'torrent-file'
30   videoImportId: number
31 }
32
33 export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
34
35 async function processVideoImport (job: Bull.Job) {
36   const payload = job.data as VideoImportPayload
37
38   if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
39   if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
40 }
41
42 // ---------------------------------------------------------------------------
43
44 export {
45   processVideoImport
46 }
47
48 // ---------------------------------------------------------------------------
49
50 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
51   logger.info('Processing torrent video import in job %d.', job.id)
52
53   const videoImport = await getVideoImportOrDie(payload.videoImportId)
54
55   const options = {
56     videoImportId: payload.videoImportId,
57
58     downloadThumbnail: false,
59     downloadPreview: false,
60
61     generateThumbnail: true,
62     generatePreview: true
63   }
64   const target = {
65     torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
66     magnetUri: videoImport.magnetUri
67   }
68   return processFile(() => downloadWebTorrentVideo(target), videoImport, options)
69 }
70
71 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
72   logger.info('Processing youtubeDL video import in job %d.', job.id)
73
74   const videoImport = await getVideoImportOrDie(payload.videoImportId)
75   const options = {
76     videoImportId: videoImport.id,
77
78     downloadThumbnail: payload.downloadThumbnail,
79     downloadPreview: payload.downloadPreview,
80     thumbnailUrl: payload.thumbnailUrl,
81
82     generateThumbnail: false,
83     generatePreview: false
84   }
85
86   return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl), videoImport, options)
87 }
88
89 async function getVideoImportOrDie (videoImportId: number) {
90   const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
91   if (!videoImport || !videoImport.Video) {
92     throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
93   }
94
95   return videoImport
96 }
97
98 type ProcessFileOptions = {
99   videoImportId: number
100
101   downloadThumbnail: boolean
102   downloadPreview: boolean
103   thumbnailUrl?: string
104
105   generateThumbnail: boolean
106   generatePreview: boolean
107 }
108 async function processFile (downloader: () => Promise<string>, videoImport: VideoImportModel, options: ProcessFileOptions) {
109   let tempVideoPath: string
110   let videoDestFile: string
111   let videoFile: VideoFileModel
112   try {
113     // Download video from youtubeDL
114     tempVideoPath = await downloader()
115
116     // Get information about this video
117     const { size } = await statPromise(tempVideoPath)
118     const isAble = await videoImport.User.isAbleToUploadVideo({ size })
119     if (isAble === false) {
120       throw new Error('The user video quota is exceeded with this video to import.')
121     }
122
123     const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
124     const fps = await getVideoFileFPS(tempVideoPath)
125     const duration = await getDurationFromVideoFile(tempVideoPath)
126
127     // Create video file object in database
128     const videoFileData = {
129       extname: extname(tempVideoPath),
130       resolution: videoFileResolution,
131       size,
132       fps,
133       videoId: videoImport.videoId
134     }
135     videoFile = new VideoFileModel(videoFileData)
136     // Import if the import fails, to clean files
137     videoImport.Video.VideoFiles = [ videoFile ]
138
139     // Move file
140     videoDestFile = join(CONFIG.STORAGE.VIDEOS_DIR, videoImport.Video.getVideoFilename(videoFile))
141     await renamePromise(tempVideoPath, videoDestFile)
142     tempVideoPath = null // This path is not used anymore
143
144     // Process thumbnail
145     if (options.downloadThumbnail) {
146       if (options.thumbnailUrl) {
147         const destThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoImport.Video.getThumbnailName())
148         await doRequestAndSaveToFile({ method: 'GET', uri: options.thumbnailUrl }, destThumbnailPath)
149       } else {
150         await videoImport.Video.createThumbnail(videoFile)
151       }
152     } else if (options.generateThumbnail) {
153       await videoImport.Video.createThumbnail(videoFile)
154     }
155
156     // Process preview
157     if (options.downloadPreview) {
158       if (options.thumbnailUrl) {
159         const destPreviewPath = join(CONFIG.STORAGE.PREVIEWS_DIR, videoImport.Video.getPreviewName())
160         await doRequestAndSaveToFile({ method: 'GET', uri: options.thumbnailUrl }, destPreviewPath)
161       } else {
162         await videoImport.Video.createPreview(videoFile)
163       }
164     } else if (options.generatePreview) {
165       await videoImport.Video.createPreview(videoFile)
166     }
167
168     // Create torrent
169     await videoImport.Video.createTorrentAndSetInfoHash(videoFile)
170
171     const videoImportUpdated: VideoImportModel = await sequelizeTypescript.transaction(async t => {
172       // Refresh video
173       const video = await VideoModel.load(videoImport.videoId, t)
174       if (!video) throw new Error('Video linked to import ' + videoImport.videoId + ' does not exist anymore.')
175       videoImport.Video = video
176
177       const videoFileCreated = await videoFile.save({ transaction: t })
178       video.VideoFiles = [ videoFileCreated ]
179
180       // Update video DB object
181       video.duration = duration
182       video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
183       const videoUpdated = await video.save({ transaction: t })
184
185       // Now we can federate the video (reload from database, we need more attributes)
186       const videoForFederation = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(video.uuid, t)
187       await federateVideoIfNeeded(videoForFederation, true, t)
188
189       // Update video import object
190       videoImport.state = VideoImportState.SUCCESS
191       const videoImportUpdated = await videoImport.save({ transaction: t })
192
193       logger.info('Video %s imported.', videoImport.targetUrl)
194
195       videoImportUpdated.Video = videoUpdated
196       return videoImportUpdated
197     })
198
199     // Create transcoding jobs?
200     if (videoImportUpdated.Video.state === VideoState.TO_TRANSCODE) {
201       // Put uuid because we don't have id auto incremented for now
202       const dataInput = {
203         videoUUID: videoImportUpdated.Video.uuid,
204         isNewVideo: true
205       }
206
207       await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
208     }
209
210   } catch (err) {
211     try {
212       if (tempVideoPath) await unlinkPromise(tempVideoPath)
213     } catch (errUnlink) {
214       logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
215     }
216
217     videoImport.error = err.message
218     videoImport.state = VideoImportState.FAILED
219     await videoImport.save()
220
221     throw err
222   }
223 }