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