]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-import.ts
Cleanup
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-import.ts
CommitLineData
fbad87b0 1import * as Bull from 'bull'
2158ac90
RK
2import { move, remove, stat } from 'fs-extra'
3import { extname } from 'path'
44d1f7f2 4import { retryTransactionWrapper } from '@server/helpers/database-utils'
2158ac90
RK
5import { isPostImportVideoAccepted } from '@server/lib/moderation'
6import { Hooks } from '@server/lib/plugins/hooks'
fb719404 7import { isAbleToUploadVideo } from '@server/lib/user'
77d7e851 8import { addOptimizeOrMergeAudioJob } from '@server/lib/video'
90a8bd30 9import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
44d1f7f2 10import { ThumbnailModel } from '@server/models/video/thumbnail'
26d6bf65 11import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import'
2158ac90
RK
12import {
13 VideoImportPayload,
14 VideoImportTorrentPayload,
15 VideoImportTorrentPayloadType,
16 VideoImportYoutubeDLPayload,
17 VideoImportYoutubeDLPayloadType,
18 VideoState
19} from '../../../../shared'
fbad87b0 20import { VideoImportState } from '../../../../shared/models/videos'
2158ac90 21import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
daf6e480 22import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
2158ac90 23import { logger } from '../../../helpers/logger'
990b6a0b 24import { getSecureTorrentName } from '../../../helpers/utils'
2158ac90
RK
25import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
26import { downloadYoutubeDLVideo } from '../../../helpers/youtube-dl'
6dd9de95 27import { CONFIG } from '../../../initializers/config'
2158ac90 28import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
74dc3bca 29import { sequelizeTypescript } from '../../../initializers/database'
2158ac90
RK
30import { VideoModel } from '../../../models/video/video'
31import { VideoFileModel } from '../../../models/video/video-file'
32import { VideoImportModel } from '../../../models/video/video-import'
26d6bf65 33import { MThumbnail } from '../../../types/models/video/thumbnail'
2158ac90
RK
34import { federateVideoIfNeeded } from '../../activitypub/videos'
35import { Notifier } from '../../notifier'
36import { generateVideoMiniature } from '../../thumbnail'
ce33919c 37
fbad87b0
C
38async function processVideoImport (job: Bull.Job) {
39 const payload = job.data as VideoImportPayload
fbad87b0 40
ce33919c 41 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
990b6a0b 42 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
ce33919c
C
43}
44
45// ---------------------------------------------------------------------------
46
47export {
48 processVideoImport
49}
50
51// ---------------------------------------------------------------------------
52
53async 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)
990b6a0b 57
ce33919c 58 const options = {
2158ac90 59 type: payload.type,
e3b4c084 60 videoImportId: payload.videoImportId
ce33919c 61 }
990b6a0b
C
62 const target = {
63 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
64 magnetUri: videoImport.magnetUri
65 }
cf9166cf 66 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
ce33919c
C
67}
68
69async 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 = {
2158ac90 74 type: payload.type,
e3b4c084 75 videoImportId: videoImport.id
ce33919c
C
76 }
77
454c20fa 78 return processFile(
805b8619 79 () => downloadYoutubeDLVideo(videoImport.targetUrl, payload.fileExt, VIDEO_IMPORT_TIMEOUT),
454c20fa
RK
80 videoImport,
81 options
82 )
ce33919c
C
83}
84
85async function getVideoImportOrDie (videoImportId: number) {
86 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
516df59b
C
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 }
fbad87b0 90
ce33919c
C
91 return videoImport
92}
93
94type ProcessFileOptions = {
2158ac90 95 type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
ce33919c 96 videoImportId: number
ce33919c 97}
0283eaac 98async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
fbad87b0 99 let tempVideoPath: string
516df59b
C
100 let videoDestFile: string
101 let videoFile: VideoFileModel
6040f87d 102
fbad87b0
C
103 try {
104 // Download video from youtubeDL
ce33919c 105 tempVideoPath = await downloader()
fbad87b0
C
106
107 // Get information about this video
62689b94 108 const stats = await stat(tempVideoPath)
fb719404 109 const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size)
a84b8fa5
C
110 if (isAble === false) {
111 throw new Error('The user video quota is exceeded with this video to import.')
112 }
113
fbad87b0 114 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
d7f83948 115 const fps = await getVideoFileFPS(tempVideoPath)
fbad87b0
C
116 const duration = await getDurationFromVideoFile(tempVideoPath)
117
2158ac90 118 // Prepare video file object for creation in database
90a8bd30 119 const fileExt = extname(tempVideoPath)
fbad87b0 120 const videoFileData = {
90a8bd30 121 extname: fileExt,
fbad87b0 122 resolution: videoFileResolution,
3e17515e 123 size: stats.size,
90a8bd30 124 filename: generateVideoFilename(videoImport.Video, false, videoFileResolution, fileExt),
fbad87b0
C
125 fps,
126 videoId: videoImport.videoId
127 }
516df59b 128 videoFile = new VideoFileModel(videoFileData)
0283eaac 129
2158ac90
RK
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
d7a25329 154 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
58d515e3 155 // To clean files if the import fails
0283eaac 156 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
fbad87b0
C
157
158 // Move file
d7a25329 159 videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile)
f481c4f9 160 await move(tempVideoPath, videoDestFile)
516df59b 161 tempVideoPath = null // This path is not used anymore
fbad87b0 162
e3b4c084 163 // Generate miniature if the import did not created it
453e83ea 164 let thumbnailModel: MThumbnail
44d1f7f2 165 let thumbnailSave: object
e3b4c084 166 if (!videoImportWithFiles.Video.getMiniature()) {
a35a2279
C
167 thumbnailModel = await generateVideoMiniature({
168 video: videoImportWithFiles.Video,
169 videoFile,
170 type: ThumbnailType.MINIATURE
171 })
44d1f7f2 172 thumbnailSave = thumbnailModel.toJSON()
fbad87b0
C
173 }
174
e3b4c084 175 // Generate preview if the import did not created it
453e83ea 176 let previewModel: MThumbnail
44d1f7f2 177 let previewSave: object
e3b4c084 178 if (!videoImportWithFiles.Video.getPreview()) {
a35a2279
C
179 previewModel = await generateVideoMiniature({
180 video: videoImportWithFiles.Video,
181 videoFile,
182 type: ThumbnailType.PREVIEW
183 })
44d1f7f2 184 previewSave = previewModel.toJSON()
fbad87b0
C
185 }
186
187 // Create torrent
8efc27bf 188 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
fbad87b0 189
44d1f7f2 190 const videoFileSave = videoFile.toJSON()
453e83ea 191
44d1f7f2
C
192 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
193 return sequelizeTypescript.transaction(async t => {
194 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
516df59b 195
44d1f7f2
C
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.')
fbad87b0 199
44d1f7f2 200 const videoFileCreated = await videoFile.save({ transaction: t })
fbad87b0 201
44d1f7f2
C
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 })
e8bafea3 206
44d1f7f2
C
207 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
208 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
fbad87b0 209
44d1f7f2
C
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)
fbad87b0 213
44d1f7f2
C
214 // Update video import object
215 videoImportToUpdate.state = VideoImportState.SUCCESS
216 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
217 videoImportUpdated.Video = video
fbad87b0 218
44d1f7f2
C
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 })
fbad87b0
C
233 })
234
dc133480 235 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
e8d246d5 236
453e83ea 237 if (video.isBlacklisted()) {
8424c402
C
238 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
239
240 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
7ccddd7b 241 } else {
453e83ea 242 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
7ccddd7b
JM
243 }
244
fbad87b0 245 // Create transcoding jobs?
453e83ea 246 if (video.state === VideoState.TO_TRANSCODE) {
77d7e851 247 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User)
fbad87b0
C
248 }
249
250 } catch (err) {
251 try {
e95e0463 252 if (tempVideoPath) await remove(tempVideoPath)
fbad87b0 253 } catch (errUnlink) {
516df59b 254 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
fbad87b0
C
255 }
256
d7f83948 257 videoImport.error = err.message
2158ac90
RK
258 if (videoImport.state !== VideoImportState.REJECTED) {
259 videoImport.state = VideoImportState.FAILED
260 }
fbad87b0
C
261 await videoImport.save()
262
dc133480
C
263 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)
264
fbad87b0
C
265 throw err
266 }
267}