]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/handlers/video-import.ts
Guess if we need to generate the thumbnail for imports
[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 { 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 videoFileData = {
120 extname: extname(tempVideoPath),
121 resolution: videoFileResolution,
122 size: stats.size,
123 fps,
124 videoId: videoImport.videoId
125 }
126 videoFile = new VideoFileModel(videoFileData)
127
128 const hookName = options.type === 'youtube-dl'
129 ? 'filter:api.video.post-import-url.accept.result'
130 : 'filter:api.video.post-import-torrent.accept.result'
131
132 // Check we accept this video
133 const acceptParameters = {
134 videoImport,
135 video: videoImport.Video,
136 videoFilePath: tempVideoPath,
137 videoFile,
138 user: videoImport.User
139 }
140 const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName)
141
142 if (acceptedResult.accepted !== true) {
143 logger.info('Refused imported video.', { acceptedResult, acceptParameters })
144
145 videoImport.state = VideoImportState.REJECTED
146 await videoImport.save()
147
148 throw new Error(acceptedResult.errorMessage)
149 }
150
151 // Video is accepted, resuming preparation
152 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
153 // To clean files if the import fails
154 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
155
156 // Move file
157 videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile)
158 await move(tempVideoPath, videoDestFile)
159 tempVideoPath = null // This path is not used anymore
160
161 // Generate miniature if the import did not created it
162 let thumbnailModel: MThumbnail
163 let thumbnailSave: object
164 if (!videoImportWithFiles.Video.getMiniature()) {
165 thumbnailModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.MINIATURE)
166 thumbnailSave = thumbnailModel.toJSON()
167 }
168
169 // Generate preview if the import did not created it
170 let previewModel: MThumbnail
171 let previewSave: object
172 if (!videoImportWithFiles.Video.getPreview()) {
173 previewModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.PREVIEW)
174 previewSave = previewModel.toJSON()
175 }
176
177 // Create torrent
178 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
179
180 const videoFileSave = videoFile.toJSON()
181
182 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
183 return sequelizeTypescript.transaction(async t => {
184 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
185
186 // Refresh video
187 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
188 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
189
190 const videoFileCreated = await videoFile.save({ transaction: t })
191
192 // Update video DB object
193 video.duration = duration
194 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
195 await video.save({ transaction: t })
196
197 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
198 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
199
200 // Now we can federate the video (reload from database, we need more attributes)
201 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
202 await federateVideoIfNeeded(videoForFederation, true, t)
203
204 // Update video import object
205 videoImportToUpdate.state = VideoImportState.SUCCESS
206 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
207 videoImportUpdated.Video = video
208
209 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
210
211 logger.info('Video %s imported.', video.uuid)
212
213 return { videoImportUpdated, video: videoForFederation }
214 }).catch(err => {
215 // Reset fields
216 if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave)
217 if (previewModel) previewModel = new ThumbnailModel(previewSave)
218
219 videoFile = new VideoFileModel(videoFileSave)
220
221 throw err
222 })
223 })
224
225 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
226
227 if (video.isBlacklisted()) {
228 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
229
230 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
231 } else {
232 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
233 }
234
235 // Create transcoding jobs?
236 if (video.state === VideoState.TO_TRANSCODE) {
237 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User)
238 }
239
240 } catch (err) {
241 try {
242 if (tempVideoPath) await remove(tempVideoPath)
243 } catch (errUnlink) {
244 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
245 }
246
247 videoImport.error = err.message
248 if (videoImport.state !== VideoImportState.REJECTED) {
249 videoImport.state = VideoImportState.FAILED
250 }
251 await videoImport.save()
252
253 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)
254
255 throw err
256 }
257 }