]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/handlers/video-import.ts
2f74e9fbd6c9548142f24582088f2c7870194a14
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-import.ts
1 import { Job } from 'bull'
2 import { move, remove, stat } from 'fs-extra'
3 import { retryTransactionWrapper } from '@server/helpers/database-utils'
4 import { YoutubeDLWrapper } from '@server/helpers/youtube-dl'
5 import { isPostImportVideoAccepted } from '@server/lib/moderation'
6 import { generateWebTorrentVideoFilename } from '@server/lib/paths'
7 import { Hooks } from '@server/lib/plugins/hooks'
8 import { ServerConfigManager } from '@server/lib/server-config-manager'
9 import { isAbleToUploadVideo } from '@server/lib/user'
10 import { addMoveToObjectStorageJob, addOptimizeOrMergeAudioJob } from '@server/lib/video'
11 import { VideoPathManager } from '@server/lib/video-path-manager'
12 import { buildNextVideoState } from '@server/lib/video-state'
13 import { ThumbnailModel } from '@server/models/video/thumbnail'
14 import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import'
15 import { getLowercaseExtension } from '@shared/core-utils'
16 import { isAudioFile } from '@shared/extra-utils'
17 import {
18 ThumbnailType,
19 VideoImportPayload,
20 VideoImportState,
21 VideoImportTorrentPayload,
22 VideoImportTorrentPayloadType,
23 VideoImportYoutubeDLPayload,
24 VideoImportYoutubeDLPayloadType,
25 VideoResolution,
26 VideoState
27 } from '@shared/models'
28 import { ffprobePromise, getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
29 import { logger } from '../../../helpers/logger'
30 import { getSecureTorrentName } from '../../../helpers/utils'
31 import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
32 import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
33 import { sequelizeTypescript } from '../../../initializers/database'
34 import { VideoModel } from '../../../models/video/video'
35 import { VideoFileModel } from '../../../models/video/video-file'
36 import { VideoImportModel } from '../../../models/video/video-import'
37 import { MThumbnail } from '../../../types/models/video/thumbnail'
38 import { federateVideoIfNeeded } from '../../activitypub/videos'
39 import { Notifier } from '../../notifier'
40 import { generateVideoMiniature } from '../../thumbnail'
41
42 async function processVideoImport (job: Job) {
43 const payload = job.data as VideoImportPayload
44
45 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
46 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
47 }
48
49 // ---------------------------------------------------------------------------
50
51 export {
52 processVideoImport
53 }
54
55 // ---------------------------------------------------------------------------
56
57 async function processTorrentImport (job: Job, payload: VideoImportTorrentPayload) {
58 logger.info('Processing torrent video import in job %d.', job.id)
59
60 const videoImport = await getVideoImportOrDie(payload.videoImportId)
61
62 const options = {
63 type: payload.type,
64 videoImportId: payload.videoImportId
65 }
66 const target = {
67 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
68 uri: videoImport.magnetUri
69 }
70 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
71 }
72
73 async function processYoutubeDLImport (job: Job, payload: VideoImportYoutubeDLPayload) {
74 logger.info('Processing youtubeDL video import in job %d.', job.id)
75
76 const videoImport = await getVideoImportOrDie(payload.videoImportId)
77 const options = {
78 type: payload.type,
79 videoImportId: videoImport.id
80 }
81
82 const youtubeDL = new YoutubeDLWrapper(videoImport.targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod'))
83
84 return processFile(
85 () => youtubeDL.downloadVideo(payload.fileExt, VIDEO_IMPORT_TIMEOUT),
86 videoImport,
87 options
88 )
89 }
90
91 async function getVideoImportOrDie (videoImportId: number) {
92 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
93 if (!videoImport || !videoImport.Video) {
94 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
95 }
96
97 return videoImport
98 }
99
100 type ProcessFileOptions = {
101 type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
102 videoImportId: number
103 }
104 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
105 let tempVideoPath: string
106 let videoFile: VideoFileModel
107
108 try {
109 // Download video from youtubeDL
110 tempVideoPath = await downloader()
111
112 // Get information about this video
113 const stats = await stat(tempVideoPath)
114 const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size)
115 if (isAble === false) {
116 throw new Error('The user video quota is exceeded with this video to import.')
117 }
118
119 const probe = await ffprobePromise(tempVideoPath)
120
121 const { resolution } = await isAudioFile(tempVideoPath, probe)
122 ? { resolution: VideoResolution.H_NOVIDEO }
123 : await getVideoFileResolution(tempVideoPath)
124
125 const fps = await getVideoFileFPS(tempVideoPath, probe)
126 const duration = await getDurationFromVideoFile(tempVideoPath, probe)
127
128 // Prepare video file object for creation in database
129 const fileExt = getLowercaseExtension(tempVideoPath)
130 const videoFileData = {
131 extname: fileExt,
132 resolution,
133 size: stats.size,
134 filename: generateWebTorrentVideoFilename(resolution, fileExt),
135 fps,
136 videoId: videoImport.videoId
137 }
138 videoFile = new VideoFileModel(videoFileData)
139
140 const hookName = options.type === 'youtube-dl'
141 ? 'filter:api.video.post-import-url.accept.result'
142 : 'filter:api.video.post-import-torrent.accept.result'
143
144 // Check we accept this video
145 const acceptParameters = {
146 videoImport,
147 video: videoImport.Video,
148 videoFilePath: tempVideoPath,
149 videoFile,
150 user: videoImport.User
151 }
152 const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName)
153
154 if (acceptedResult.accepted !== true) {
155 logger.info('Refused imported video.', { acceptedResult, acceptParameters })
156
157 videoImport.state = VideoImportState.REJECTED
158 await videoImport.save()
159
160 throw new Error(acceptedResult.errorMessage)
161 }
162
163 // Video is accepted, resuming preparation
164 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
165 // To clean files if the import fails
166 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
167
168 // Move file
169 const videoDestFile = VideoPathManager.Instance.getFSVideoFileOutputPath(videoImportWithFiles.Video, videoFile)
170 await move(tempVideoPath, videoDestFile)
171 tempVideoPath = null // This path is not used anymore
172
173 // Generate miniature if the import did not created it
174 let thumbnailModel: MThumbnail
175 let thumbnailSave: object
176 if (!videoImportWithFiles.Video.getMiniature()) {
177 thumbnailModel = await generateVideoMiniature({
178 video: videoImportWithFiles.Video,
179 videoFile,
180 type: ThumbnailType.MINIATURE
181 })
182 thumbnailSave = thumbnailModel.toJSON()
183 }
184
185 // Generate preview if the import did not created it
186 let previewModel: MThumbnail
187 let previewSave: object
188 if (!videoImportWithFiles.Video.getPreview()) {
189 previewModel = await generateVideoMiniature({
190 video: videoImportWithFiles.Video,
191 videoFile,
192 type: ThumbnailType.PREVIEW
193 })
194 previewSave = previewModel.toJSON()
195 }
196
197 // Create torrent
198 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
199
200 const videoFileSave = videoFile.toJSON()
201
202 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
203 return sequelizeTypescript.transaction(async t => {
204 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
205
206 // Refresh video
207 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
208 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
209
210 const videoFileCreated = await videoFile.save({ transaction: t })
211
212 // Update video DB object
213 video.duration = duration
214 video.state = buildNextVideoState(video.state)
215 await video.save({ transaction: t })
216
217 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
218 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
219
220 // Now we can federate the video (reload from database, we need more attributes)
221 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
222 await federateVideoIfNeeded(videoForFederation, true, t)
223
224 // Update video import object
225 videoImportToUpdate.state = VideoImportState.SUCCESS
226 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
227 videoImportUpdated.Video = video
228
229 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
230
231 logger.info('Video %s imported.', video.uuid)
232
233 return { videoImportUpdated, video: videoForFederation }
234 }).catch(err => {
235 // Reset fields
236 if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave)
237 if (previewModel) previewModel = new ThumbnailModel(previewSave)
238
239 videoFile = new VideoFileModel(videoFileSave)
240
241 throw err
242 })
243 })
244
245 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport: videoImportUpdated, success: true })
246
247 if (video.isBlacklisted()) {
248 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
249
250 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
251 } else {
252 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
253 }
254
255 if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
256 return addMoveToObjectStorageJob(videoImportUpdated.Video)
257 }
258
259 // Create transcoding jobs?
260 if (video.state === VideoState.TO_TRANSCODE) {
261 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User)
262 }
263
264 } catch (err) {
265 try {
266 if (tempVideoPath) await remove(tempVideoPath)
267 } catch (errUnlink) {
268 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
269 }
270
271 videoImport.error = err.message
272 if (videoImport.state !== VideoImportState.REJECTED) {
273 videoImport.state = VideoImportState.FAILED
274 }
275 await videoImport.save()
276
277 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport, success: false })
278
279 throw err
280 }
281 }