d96bfdf43cd1022454da6bf45b2630497d2a86f1
[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 { CONFIG, PREVIEWS_SIZE, sequelizeTypescript, THUMBNAILS_SIZE, VIDEO_IMPORT_TIMEOUT } from '../../../initializers'
10 import { downloadImage } from '../../../helpers/requests'
11 import { VideoState } from '../../../../shared'
12 import { JobQueue } from '../index'
13 import { federateVideoIfNeeded } from '../../activitypub'
14 import { VideoModel } from '../../../models/video/video'
15 import { downloadWebTorrentVideo } from '../../../helpers/webtorrent'
16 import { getSecureTorrentName } from '../../../helpers/utils'
17 import { remove, move, stat } from 'fs-extra'
18 import { Notifier } from '../../notifier'
19
20 type VideoImportYoutubeDLPayload = {
21   type: 'youtube-dl'
22   videoImportId: number
23
24   thumbnailUrl: string
25   downloadThumbnail: boolean
26   downloadPreview: boolean
27 }
28
29 type VideoImportTorrentPayload = {
30   type: 'magnet-uri' | 'torrent-file'
31   videoImportId: number
32 }
33
34 export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
35
36 async function processVideoImport (job: Bull.Job) {
37   const payload = job.data as VideoImportPayload
38
39   if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
40   if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
41 }
42
43 // ---------------------------------------------------------------------------
44
45 export {
46   processVideoImport
47 }
48
49 // ---------------------------------------------------------------------------
50
51 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
52   logger.info('Processing torrent video import in job %d.', job.id)
53
54   const videoImport = await getVideoImportOrDie(payload.videoImportId)
55
56   const options = {
57     videoImportId: payload.videoImportId,
58
59     downloadThumbnail: false,
60     downloadPreview: false,
61
62     generateThumbnail: true,
63     generatePreview: true
64   }
65   const target = {
66     torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
67     magnetUri: videoImport.magnetUri
68   }
69   return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
70 }
71
72 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
73   logger.info('Processing youtubeDL video import in job %d.', job.id)
74
75   const videoImport = await getVideoImportOrDie(payload.videoImportId)
76   const options = {
77     videoImportId: videoImport.id,
78
79     downloadThumbnail: payload.downloadThumbnail,
80     downloadPreview: payload.downloadPreview,
81     thumbnailUrl: payload.thumbnailUrl,
82
83     generateThumbnail: false,
84     generatePreview: false
85   }
86
87   return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl, VIDEO_IMPORT_TIMEOUT), videoImport, options)
88 }
89
90 async function getVideoImportOrDie (videoImportId: number) {
91   const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
92   if (!videoImport || !videoImport.Video) {
93     throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
94   }
95
96   return videoImport
97 }
98
99 type ProcessFileOptions = {
100   videoImportId: number
101
102   downloadThumbnail: boolean
103   downloadPreview: boolean
104   thumbnailUrl?: string
105
106   generateThumbnail: boolean
107   generatePreview: boolean
108 }
109 async function processFile (downloader: () => Promise<string>, videoImport: VideoImportModel, options: ProcessFileOptions) {
110   let tempVideoPath: string
111   let videoDestFile: string
112   let videoFile: VideoFileModel
113
114   try {
115     // Download video from youtubeDL
116     tempVideoPath = await downloader()
117
118     // Get information about this video
119     const stats = await stat(tempVideoPath)
120     const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
121     if (isAble === false) {
122       throw new Error('The user video quota is exceeded with this video to import.')
123     }
124
125     const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
126     const fps = await getVideoFileFPS(tempVideoPath)
127     const duration = await getDurationFromVideoFile(tempVideoPath)
128
129     // Create video file object in database
130     const videoFileData = {
131       extname: extname(tempVideoPath),
132       resolution: videoFileResolution,
133       size: stats.size,
134       fps,
135       videoId: videoImport.videoId
136     }
137     videoFile = new VideoFileModel(videoFileData)
138     // To clean files if the import fails
139     videoImport.Video.VideoFiles = [ videoFile ]
140
141     // Move file
142     videoDestFile = join(CONFIG.STORAGE.VIDEOS_DIR, videoImport.Video.getVideoFilename(videoFile))
143     await move(tempVideoPath, videoDestFile)
144     tempVideoPath = null // This path is not used anymore
145
146     // Process thumbnail
147     if (options.downloadThumbnail) {
148       if (options.thumbnailUrl) {
149         await downloadImage(options.thumbnailUrl, CONFIG.STORAGE.THUMBNAILS_DIR, videoImport.Video.getThumbnailName(), THUMBNAILS_SIZE)
150       } else {
151         await videoImport.Video.createThumbnail(videoFile)
152       }
153     } else if (options.generateThumbnail) {
154       await videoImport.Video.createThumbnail(videoFile)
155     }
156
157     // Process preview
158     if (options.downloadPreview) {
159       if (options.thumbnailUrl) {
160         await downloadImage(options.thumbnailUrl, CONFIG.STORAGE.PREVIEWS_DIR, videoImport.Video.getPreviewName(), PREVIEWS_SIZE)
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       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.loadAndPopulateAccountAndServerAndTags(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.', video.uuid)
194
195       videoImportUpdated.Video = videoForFederation
196       return videoImportUpdated
197     })
198
199     Notifier.Instance.notifyOnNewVideo(videoImportUpdated.Video)
200     Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
201
202     // Create transcoding jobs?
203     if (videoImportUpdated.Video.state === VideoState.TO_TRANSCODE) {
204       // Put uuid because we don't have id auto incremented for now
205       const dataInput = {
206         videoUUID: videoImportUpdated.Video.uuid,
207         isNewVideo: true
208       }
209
210       await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
211     }
212
213   } catch (err) {
214     try {
215       if (tempVideoPath) await remove(tempVideoPath)
216     } catch (errUnlink) {
217       logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
218     }
219
220     videoImport.error = err.message
221     videoImport.state = VideoImportState.FAILED
222     await videoImport.save()
223
224     Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)
225
226     throw err
227   }
228 }