]>
Commit | Line | Data |
---|---|---|
5a921e7b | 1 | import { Job } from 'bullmq' |
2158ac90 | 2 | import { move, remove, stat } from 'fs-extra' |
44d1f7f2 | 3 | import { retryTransactionWrapper } from '@server/helpers/database-utils' |
62549e6c | 4 | import { YoutubeDLWrapper } from '@server/helpers/youtube-dl' |
5e2afe42 | 5 | import { CONFIG } from '@server/initializers/config' |
2158ac90 | 6 | import { isPostImportVideoAccepted } from '@server/lib/moderation' |
0305db28 | 7 | import { generateWebTorrentVideoFilename } from '@server/lib/paths' |
2158ac90 | 8 | import { Hooks } from '@server/lib/plugins/hooks' |
2539932e | 9 | import { ServerConfigManager } from '@server/lib/server-config-manager' |
fb719404 | 10 | import { isAbleToUploadVideo } from '@server/lib/user' |
2a491182 | 11 | import { buildMoveToObjectStorageJob, buildOptimizeOrMergeAudioJob } from '@server/lib/video' |
0305db28 JB |
12 | import { VideoPathManager } from '@server/lib/video-path-manager' |
13 | import { buildNextVideoState } from '@server/lib/video-state' | |
44d1f7f2 | 14 | import { ThumbnailModel } from '@server/models/video/thumbnail' |
26d6bf65 | 15 | import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import' |
d17c7b4e C |
16 | import { getLowercaseExtension } from '@shared/core-utils' |
17 | import { isAudioFile } from '@shared/extra-utils' | |
2158ac90 | 18 | import { |
d17c7b4e | 19 | ThumbnailType, |
2158ac90 | 20 | VideoImportPayload, |
2a491182 | 21 | VideoImportPreventExceptionResult, |
d17c7b4e | 22 | VideoImportState, |
2158ac90 RK |
23 | VideoImportTorrentPayload, |
24 | VideoImportTorrentPayloadType, | |
25 | VideoImportYoutubeDLPayload, | |
26 | VideoImportYoutubeDLPayloadType, | |
d17c7b4e | 27 | VideoResolution, |
2158ac90 | 28 | VideoState |
d17c7b4e | 29 | } from '@shared/models' |
5e2afe42 | 30 | import { ffprobePromise, getVideoStreamDimensionsInfo, getVideoStreamDuration, getVideoStreamFPS } from '../../../helpers/ffmpeg' |
2158ac90 | 31 | import { logger } from '../../../helpers/logger' |
990b6a0b | 32 | import { getSecureTorrentName } from '../../../helpers/utils' |
2158ac90 | 33 | import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent' |
7630e1c8 | 34 | import { JOB_TTL } from '../../../initializers/constants' |
74dc3bca | 35 | import { sequelizeTypescript } from '../../../initializers/database' |
2158ac90 RK |
36 | import { VideoModel } from '../../../models/video/video' |
37 | import { VideoFileModel } from '../../../models/video/video-file' | |
38 | import { VideoImportModel } from '../../../models/video/video-import' | |
26d6bf65 | 39 | import { MThumbnail } from '../../../types/models/video/thumbnail' |
2158ac90 RK |
40 | import { federateVideoIfNeeded } from '../../activitypub/videos' |
41 | import { Notifier } from '../../notifier' | |
42 | import { generateVideoMiniature } from '../../thumbnail' | |
bd911b54 | 43 | import { JobQueue } from '../job-queue' |
ce33919c | 44 | |
2a491182 | 45 | async 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 | ||
72 | export { | |
73 | processVideoImport | |
74 | } | |
75 | ||
76 | // --------------------------------------------------------------------------- | |
77 | ||
419b520c | 78 | async 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 | 90 | async 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 |
108 | async function getVideoImportOrDie (payload: VideoImportPayload) { |
109 | const videoImport = await VideoImportModel.loadAndPopulateVideo(payload.videoImportId) | |
516df59b | 110 | if (!videoImport || !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 | ||
117 | type ProcessFileOptions = { | |
2158ac90 | 118 | type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType |
ce33919c | 119 | videoImportId: number |
ce33919c | 120 | } |
0283eaac | 121 | async 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 } |
c729caf6 | 140 | : await getVideoStreamDimensionsInfo(tempVideoPath) |
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 | |
d7a25329 | 181 | const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] }) |
58d515e3 | 182 | // To clean files if the import fails |
0283eaac | 183 | const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles }) |
fbad87b0 C |
184 | |
185 | // Move file | |
0305db28 | 186 | const videoDestFile = VideoPathManager.Instance.getFSVideoFileOutputPath(videoImportWithFiles.Video, videoFile) |
f481c4f9 | 187 | await move(tempVideoPath, videoDestFile) |
516df59b | 188 | tempVideoPath = null // This path is not used anymore |
fbad87b0 | 189 | |
e3b4c084 | 190 | // Generate miniature if the import did not created it |
453e83ea | 191 | let thumbnailModel: MThumbnail |
44d1f7f2 | 192 | let thumbnailSave: object |
e3b4c084 | 193 | if (!videoImportWithFiles.Video.getMiniature()) { |
a35a2279 C |
194 | thumbnailModel = await generateVideoMiniature({ |
195 | video: videoImportWithFiles.Video, | |
196 | videoFile, | |
197 | type: ThumbnailType.MINIATURE | |
198 | }) | |
44d1f7f2 | 199 | thumbnailSave = thumbnailModel.toJSON() |
fbad87b0 C |
200 | } |
201 | ||
e3b4c084 | 202 | // Generate preview if the import did not created it |
453e83ea | 203 | let previewModel: MThumbnail |
44d1f7f2 | 204 | let previewSave: object |
e3b4c084 | 205 | if (!videoImportWithFiles.Video.getPreview()) { |
a35a2279 C |
206 | previewModel = await generateVideoMiniature({ |
207 | video: videoImportWithFiles.Video, | |
208 | videoFile, | |
209 | type: ThumbnailType.PREVIEW | |
210 | }) | |
44d1f7f2 | 211 | previewSave = previewModel.toJSON() |
fbad87b0 C |
212 | } |
213 | ||
214 | // Create torrent | |
8efc27bf | 215 | await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile) |
fbad87b0 | 216 | |
44d1f7f2 | 217 | const videoFileSave = videoFile.toJSON() |
453e83ea | 218 | |
44d1f7f2 C |
219 | const { videoImportUpdated, video } = await retryTransactionWrapper(() => { |
220 | return sequelizeTypescript.transaction(async t => { | |
221 | const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo | |
516df59b | 222 | |
44d1f7f2 C |
223 | // Refresh video |
224 | const video = await VideoModel.load(videoImportToUpdate.videoId, t) | |
225 | if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.') | |
fbad87b0 | 226 | |
44d1f7f2 | 227 | const videoFileCreated = await videoFile.save({ transaction: t }) |
fbad87b0 | 228 | |
44d1f7f2 C |
229 | // Update video DB object |
230 | video.duration = duration | |
0305db28 | 231 | video.state = buildNextVideoState(video.state) |
44d1f7f2 | 232 | await video.save({ transaction: t }) |
e8bafea3 | 233 | |
44d1f7f2 C |
234 | if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t) |
235 | if (previewModel) await video.addAndSaveThumbnail(previewModel, t) | |
fbad87b0 | 236 | |
44d1f7f2 | 237 | // Now we can federate the video (reload from database, we need more attributes) |
4fae2b1f | 238 | const videoForFederation = await VideoModel.loadFull(video.uuid, t) |
44d1f7f2 | 239 | await federateVideoIfNeeded(videoForFederation, true, t) |
fbad87b0 | 240 | |
44d1f7f2 C |
241 | // Update video import object |
242 | videoImportToUpdate.state = VideoImportState.SUCCESS | |
243 | const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo | |
244 | videoImportUpdated.Video = video | |
fbad87b0 | 245 | |
44d1f7f2 C |
246 | videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] }) |
247 | ||
248 | logger.info('Video %s imported.', video.uuid) | |
249 | ||
250 | return { videoImportUpdated, video: videoForFederation } | |
251 | }).catch(err => { | |
252 | // Reset fields | |
253 | if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave) | |
254 | if (previewModel) previewModel = new ThumbnailModel(previewSave) | |
255 | ||
256 | videoFile = new VideoFileModel(videoFileSave) | |
257 | ||
258 | throw err | |
259 | }) | |
fbad87b0 C |
260 | }) |
261 | ||
d26836cd | 262 | Notifier.Instance.notifyOnFinishedVideoImport({ videoImport: videoImportUpdated, success: true }) |
e8d246d5 | 263 | |
453e83ea | 264 | if (video.isBlacklisted()) { |
8424c402 C |
265 | const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video }) |
266 | ||
267 | Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist) | |
7ccddd7b | 268 | } else { |
453e83ea | 269 | Notifier.Instance.notifyOnNewVideoIfNeeded(video) |
7ccddd7b JM |
270 | } |
271 | ||
0305db28 | 272 | if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) { |
bd911b54 C |
273 | await JobQueue.Instance.createJob( |
274 | await buildMoveToObjectStorageJob({ video: videoImportUpdated.Video, previousVideoState: VideoState.TO_IMPORT }) | |
275 | ) | |
0305db28 JB |
276 | } |
277 | ||
fbad87b0 | 278 | // Create transcoding jobs? |
453e83ea | 279 | if (video.state === VideoState.TO_TRANSCODE) { |
bd911b54 C |
280 | await JobQueue.Instance.createJob( |
281 | await buildOptimizeOrMergeAudioJob({ video: videoImportUpdated.Video, videoFile, user: videoImport.User }) | |
282 | ) | |
fbad87b0 C |
283 | } |
284 | ||
285 | } catch (err) { | |
286 | try { | |
e95e0463 | 287 | if (tempVideoPath) await remove(tempVideoPath) |
fbad87b0 | 288 | } catch (errUnlink) { |
516df59b | 289 | logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink }) |
fbad87b0 C |
290 | } |
291 | ||
d7f83948 | 292 | videoImport.error = err.message |
2158ac90 RK |
293 | if (videoImport.state !== VideoImportState.REJECTED) { |
294 | videoImport.state = VideoImportState.FAILED | |
295 | } | |
fbad87b0 C |
296 | await videoImport.save() |
297 | ||
d26836cd | 298 | Notifier.Instance.notifyOnFinishedVideoImport({ videoImport, success: false }) |
dc133480 | 299 | |
fbad87b0 C |
300 | throw err |
301 | } | |
302 | } |