]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-import.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-import.ts
CommitLineData
5a921e7b 1import { Job } from 'bullmq'
2158ac90 2import { move, remove, stat } from 'fs-extra'
44d1f7f2 3import { retryTransactionWrapper } from '@server/helpers/database-utils'
62549e6c 4import { YoutubeDLWrapper } from '@server/helpers/youtube-dl'
5e2afe42 5import { CONFIG } from '@server/initializers/config'
2158ac90 6import { isPostImportVideoAccepted } from '@server/lib/moderation'
0305db28 7import { generateWebTorrentVideoFilename } from '@server/lib/paths'
2158ac90 8import { Hooks } from '@server/lib/plugins/hooks'
2539932e 9import { ServerConfigManager } from '@server/lib/server-config-manager'
0c9668f7 10import { createOptimizeOrMergeAudioJobs } from '@server/lib/transcoding/create-transcoding-job'
fb719404 11import { isAbleToUploadVideo } from '@server/lib/user'
0c9668f7 12import { buildMoveToObjectStorageJob } from '@server/lib/video'
0305db28
JB
13import { VideoPathManager } from '@server/lib/video-path-manager'
14import { buildNextVideoState } from '@server/lib/video-state'
44d1f7f2 15import { ThumbnailModel } from '@server/models/video/thumbnail'
6740b642
C
16import { MUserId, MVideoFile, MVideoFullLight } from '@server/types/models'
17import { MVideoImport, MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import'
d17c7b4e 18import { getLowercaseExtension } from '@shared/core-utils'
0c9668f7 19import { ffprobePromise, getVideoStreamDimensionsInfo, getVideoStreamDuration, getVideoStreamFPS, isAudioFile } from '@shared/ffmpeg'
2158ac90 20import {
d17c7b4e 21 ThumbnailType,
2158ac90 22 VideoImportPayload,
2a491182 23 VideoImportPreventExceptionResult,
d17c7b4e 24 VideoImportState,
2158ac90
RK
25 VideoImportTorrentPayload,
26 VideoImportTorrentPayloadType,
27 VideoImportYoutubeDLPayload,
28 VideoImportYoutubeDLPayloadType,
d17c7b4e 29 VideoResolution,
2158ac90 30 VideoState
d17c7b4e 31} from '@shared/models'
2158ac90 32import { logger } from '../../../helpers/logger'
990b6a0b 33import { getSecureTorrentName } from '../../../helpers/utils'
2158ac90 34import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
7630e1c8 35import { JOB_TTL } from '../../../initializers/constants'
74dc3bca 36import { sequelizeTypescript } from '../../../initializers/database'
2158ac90
RK
37import { VideoModel } from '../../../models/video/video'
38import { VideoFileModel } from '../../../models/video/video-file'
39import { VideoImportModel } from '../../../models/video/video-import'
2158ac90
RK
40import { federateVideoIfNeeded } from '../../activitypub/videos'
41import { Notifier } from '../../notifier'
42import { generateVideoMiniature } from '../../thumbnail'
bd911b54 43import { JobQueue } from '../job-queue'
ce33919c 44
2a491182 45async function processVideoImport (job: Job): Promise<VideoImportPreventExceptionResult> {
fbad87b0 46 const payload = job.data as VideoImportPayload
fbad87b0 47
d511df28 48 const videoImport = await getVideoImportOrDie(payload)
419b520c
C
49 if (videoImport.state === VideoImportState.CANCELLED) {
50 logger.info('Do not process import since it has been cancelled', { payload })
2a491182 51 return { resultType: 'success' }
419b520c
C
52 }
53
54 videoImport.state = VideoImportState.PROCESSING
55 await videoImport.save()
56
2a491182
F
57 try {
58 if (payload.type === 'youtube-dl') await processYoutubeDLImport(job, videoImport, payload)
59 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') await processTorrentImport(job, videoImport, payload)
60
61 return { resultType: 'success' }
62 } catch (err) {
63 if (!payload.preventException) throw err
64
65 logger.warn('Catch error in video import to send value to parent job.', { payload, err })
66 return { resultType: 'error' }
67 }
ce33919c
C
68}
69
70// ---------------------------------------------------------------------------
71
72export {
73 processVideoImport
74}
75
76// ---------------------------------------------------------------------------
77
419b520c 78async function processTorrentImport (job: Job, videoImport: MVideoImportDefault, payload: VideoImportTorrentPayload) {
bd911b54 79 logger.info('Processing torrent video import in job %s.', job.id)
ce33919c 80
419b520c 81 const options = { type: payload.type, videoImportId: payload.videoImportId }
990b6a0b 82
990b6a0b
C
83 const target = {
84 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
02b286f8 85 uri: videoImport.magnetUri
990b6a0b 86 }
7630e1c8 87 return processFile(() => downloadWebTorrentVideo(target, JOB_TTL['video-import']), videoImport, options)
ce33919c
C
88}
89
419b520c 90async function processYoutubeDLImport (job: Job, videoImport: MVideoImportDefault, payload: VideoImportYoutubeDLPayload) {
bd911b54 91 logger.info('Processing youtubeDL video import in job %s.', job.id)
ce33919c 92
419b520c 93 const options = { type: payload.type, videoImportId: videoImport.id }
ce33919c 94
5e2afe42
C
95 const youtubeDL = new YoutubeDLWrapper(
96 videoImport.targetUrl,
97 ServerConfigManager.Instance.getEnabledResolutions('vod'),
98 CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
99 )
1bcb03a1 100
454c20fa 101 return processFile(
7630e1c8 102 () => youtubeDL.downloadVideo(payload.fileExt, JOB_TTL['video-import']),
454c20fa
RK
103 videoImport,
104 options
105 )
ce33919c
C
106}
107
d511df28
C
108async function getVideoImportOrDie (payload: VideoImportPayload) {
109 const videoImport = await VideoImportModel.loadAndPopulateVideo(payload.videoImportId)
99b75748 110 if (!videoImport?.Video) {
d511df28 111 throw new Error(`Cannot import video ${payload.videoImportId}: the video import or video linked to this import does not exist anymore.`)
516df59b 112 }
fbad87b0 113
ce33919c
C
114 return videoImport
115}
116
117type ProcessFileOptions = {
2158ac90 118 type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
ce33919c 119 videoImportId: number
ce33919c 120}
0283eaac 121async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
fbad87b0 122 let tempVideoPath: string
516df59b 123 let videoFile: VideoFileModel
6040f87d 124
fbad87b0
C
125 try {
126 // Download video from youtubeDL
ce33919c 127 tempVideoPath = await downloader()
fbad87b0
C
128
129 // Get information about this video
62689b94 130 const stats = await stat(tempVideoPath)
fb719404 131 const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size)
a84b8fa5
C
132 if (isAble === false) {
133 throw new Error('The user video quota is exceeded with this video to import.')
134 }
135
482b2623
C
136 const probe = await ffprobePromise(tempVideoPath)
137
138 const { resolution } = await isAudioFile(tempVideoPath, probe)
5354af75 139 ? { resolution: VideoResolution.H_NOVIDEO }
0c9668f7 140 : await getVideoStreamDimensionsInfo(tempVideoPath, probe)
482b2623 141
c729caf6
C
142 const fps = await getVideoStreamFPS(tempVideoPath, probe)
143 const duration = await getVideoStreamDuration(tempVideoPath, probe)
fbad87b0 144
2158ac90 145 // Prepare video file object for creation in database
ea54cd04 146 const fileExt = getLowercaseExtension(tempVideoPath)
fbad87b0 147 const videoFileData = {
90a8bd30 148 extname: fileExt,
679c12e6 149 resolution,
3e17515e 150 size: stats.size,
679c12e6 151 filename: generateWebTorrentVideoFilename(resolution, fileExt),
fbad87b0
C
152 fps,
153 videoId: videoImport.videoId
154 }
516df59b 155 videoFile = new VideoFileModel(videoFileData)
0283eaac 156
2158ac90
RK
157 const hookName = options.type === 'youtube-dl'
158 ? 'filter:api.video.post-import-url.accept.result'
159 : 'filter:api.video.post-import-torrent.accept.result'
160
161 // Check we accept this video
162 const acceptParameters = {
163 videoImport,
164 video: videoImport.Video,
165 videoFilePath: tempVideoPath,
166 videoFile,
167 user: videoImport.User
168 }
169 const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName)
170
171 if (acceptedResult.accepted !== true) {
172 logger.info('Refused imported video.', { acceptedResult, acceptParameters })
173
174 videoImport.state = VideoImportState.REJECTED
175 await videoImport.save()
176
177 throw new Error(acceptedResult.errorMessage)
178 }
179
180 // Video is accepted, resuming preparation
6740b642 181 const videoFileLockReleaser = await VideoPathManager.Instance.lockFiles(videoImport.Video.uuid)
fbad87b0 182
6740b642
C
183 try {
184 const videoImportWithFiles = await refreshVideoImportFromDB(videoImport, videoFile)
fbad87b0 185
6740b642
C
186 // Move file
187 const videoDestFile = VideoPathManager.Instance.getFSVideoFileOutputPath(videoImportWithFiles.Video, videoFile)
188 await move(tempVideoPath, videoDestFile)
fbad87b0 189
6740b642 190 tempVideoPath = null // This path is not used anymore
453e83ea 191
6740b642
C
192 let {
193 miniatureModel: thumbnailModel,
194 miniatureJSONSave: thumbnailSave
195 } = await generateMiniature(videoImportWithFiles, videoFile, ThumbnailType.MINIATURE)
516df59b 196
6740b642
C
197 let {
198 miniatureModel: previewModel,
199 miniatureJSONSave: previewSave
200 } = await generateMiniature(videoImportWithFiles, videoFile, ThumbnailType.PREVIEW)
fbad87b0 201
6740b642
C
202 // Create torrent
203 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
fbad87b0 204
6740b642 205 const videoFileSave = videoFile.toJSON()
e8bafea3 206
6740b642
C
207 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
208 return sequelizeTypescript.transaction(async t => {
209 // Refresh video
210 const video = await VideoModel.load(videoImportWithFiles.videoId, t)
211 if (!video) throw new Error('Video linked to import ' + videoImportWithFiles.videoId + ' does not exist anymore.')
fbad87b0 212
6740b642 213 await videoFile.save({ transaction: t })
fbad87b0 214
6740b642
C
215 // Update video DB object
216 video.duration = duration
217 video.state = buildNextVideoState(video.state)
218 await video.save({ transaction: t })
fbad87b0 219
6740b642
C
220 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
221 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
44d1f7f2 222
6740b642
C
223 // Now we can federate the video (reload from database, we need more attributes)
224 const videoForFederation = await VideoModel.loadFull(video.uuid, t)
225 await federateVideoIfNeeded(videoForFederation, true, t)
44d1f7f2 226
6740b642
C
227 // Update video import object
228 videoImportWithFiles.state = VideoImportState.SUCCESS
229 const videoImportUpdated = await videoImportWithFiles.save({ transaction: t }) as MVideoImport
44d1f7f2 230
6740b642 231 logger.info('Video %s imported.', video.uuid)
44d1f7f2 232
6740b642
C
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)
fbad87b0 238
6740b642 239 videoFile = new VideoFileModel(videoFileSave)
e8d246d5 240
6740b642
C
241 throw err
242 })
243 })
8424c402 244
9a3db678 245 await afterImportSuccess({ videoImport: videoImportUpdated, video, videoFile, user: videoImport.User, videoFileAlreadyLocked: true })
6740b642
C
246 } finally {
247 videoFileLockReleaser()
7ccddd7b 248 }
6740b642
C
249 } catch (err) {
250 await onImportError(err, tempVideoPath, videoImport)
7ccddd7b 251
6740b642
C
252 throw err
253 }
254}
0305db28 255
6740b642
C
256async function refreshVideoImportFromDB (videoImport: MVideoImportDefault, videoFile: MVideoFile): Promise<MVideoImportDefaultFiles> {
257 // Refresh video, privacy may have changed
258 const video = await videoImport.Video.reload()
259 const videoWithFiles = Object.assign(video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
fbad87b0 260
6740b642
C
261 return Object.assign(videoImport, { Video: videoWithFiles })
262}
fbad87b0 263
6740b642
C
264async function generateMiniature (videoImportWithFiles: MVideoImportDefaultFiles, videoFile: MVideoFile, thumbnailType: ThumbnailType) {
265 // Generate miniature if the import did not created it
266 const needsMiniature = thumbnailType === ThumbnailType.MINIATURE
267 ? !videoImportWithFiles.Video.getMiniature()
268 : !videoImportWithFiles.Video.getPreview()
269
270 if (!needsMiniature) {
271 return {
272 miniatureModel: null,
273 miniatureJSONSave: null
2158ac90 274 }
6740b642 275 }
fbad87b0 276
6740b642
C
277 const miniatureModel = await generateVideoMiniature({
278 video: videoImportWithFiles.Video,
279 videoFile,
5fc4a182 280 type: thumbnailType
6740b642
C
281 })
282 const miniatureJSONSave = miniatureModel.toJSON()
dc133480 283
6740b642
C
284 return {
285 miniatureModel,
286 miniatureJSONSave
287 }
288}
289
290async function afterImportSuccess (options: {
291 videoImport: MVideoImport
292 video: MVideoFullLight
293 videoFile: MVideoFile
294 user: MUserId
9a3db678 295 videoFileAlreadyLocked: boolean
6740b642 296}) {
9a3db678 297 const { video, videoFile, videoImport, user, videoFileAlreadyLocked } = options
6740b642
C
298
299 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport: Object.assign(videoImport, { Video: video }), success: true })
300
301 if (video.isBlacklisted()) {
302 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
303
304 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
305 } else {
306 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
fbad87b0 307 }
6740b642
C
308
309 if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
310 await JobQueue.Instance.createJob(
311 await buildMoveToObjectStorageJob({ video, previousVideoState: VideoState.TO_IMPORT })
312 )
313 return
314 }
315
316 if (video.state === VideoState.TO_TRANSCODE) { // Create transcoding jobs?
9a3db678 317 await createOptimizeOrMergeAudioJobs({ video, videoFile, isNewVideo: true, user, videoFileAlreadyLocked })
6740b642
C
318 }
319}
320
321async function onImportError (err: Error, tempVideoPath: string, videoImport: MVideoImportVideo) {
322 try {
323 if (tempVideoPath) await remove(tempVideoPath)
324 } catch (errUnlink) {
325 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
326 }
327
328 videoImport.error = err.message
329 if (videoImport.state !== VideoImportState.REJECTED) {
330 videoImport.state = VideoImportState.FAILED
331 }
332 await videoImport.save()
333
334 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport, success: false })
fbad87b0 335}