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