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