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