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