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