]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-import.ts
Add server plugin filter hooks for import with torrent and url (#2621)
[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'
4import { addOptimizeOrMergeAudioJob } from '@server/helpers/video'
5import { isPostImportVideoAccepted } from '@server/lib/moderation'
6import { Hooks } from '@server/lib/plugins/hooks'
7import { getVideoFilePath } from '@server/lib/video-paths'
8import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/typings/models/video/video-import'
9import {
10 VideoImportPayload,
11 VideoImportTorrentPayload,
12 VideoImportTorrentPayloadType,
13 VideoImportYoutubeDLPayload,
14 VideoImportYoutubeDLPayloadType,
15 VideoState
16} from '../../../../shared'
fbad87b0 17import { VideoImportState } from '../../../../shared/models/videos'
2158ac90 18import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
fbad87b0 19import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
2158ac90 20import { logger } from '../../../helpers/logger'
990b6a0b 21import { getSecureTorrentName } from '../../../helpers/utils'
2158ac90
RK
22import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
23import { downloadYoutubeDLVideo } from '../../../helpers/youtube-dl'
6dd9de95 24import { CONFIG } from '../../../initializers/config'
2158ac90 25import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
74dc3bca 26import { sequelizeTypescript } from '../../../initializers/database'
2158ac90
RK
27import { VideoModel } from '../../../models/video/video'
28import { VideoFileModel } from '../../../models/video/video-file'
29import { VideoImportModel } from '../../../models/video/video-import'
453e83ea 30import { MThumbnail } from '../../../typings/models/video/thumbnail'
2158ac90
RK
31import { federateVideoIfNeeded } from '../../activitypub/videos'
32import { Notifier } from '../../notifier'
33import { generateVideoMiniature } from '../../thumbnail'
ce33919c 34
fbad87b0
C
35async function processVideoImport (job: Bull.Job) {
36 const payload = job.data as VideoImportPayload
fbad87b0 37
ce33919c 38 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
990b6a0b 39 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
ce33919c
C
40}
41
42// ---------------------------------------------------------------------------
43
44export {
45 processVideoImport
46}
47
48// ---------------------------------------------------------------------------
49
50async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
51 logger.info('Processing torrent video import in job %d.', job.id)
52
53 const videoImport = await getVideoImportOrDie(payload.videoImportId)
990b6a0b 54
ce33919c 55 const options = {
2158ac90 56 type: payload.type,
ce33919c
C
57 videoImportId: payload.videoImportId,
58
ce33919c
C
59 generateThumbnail: true,
60 generatePreview: true
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,
ce33919c
C
75 videoImportId: videoImport.id,
76
b1770a0a
K
77 generateThumbnail: payload.generateThumbnail,
78 generatePreview: payload.generatePreview
ce33919c
C
79 }
80
d57d1d83 81 return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl, payload.fileExt, VIDEO_IMPORT_TIMEOUT), videoImport, options)
ce33919c
C
82}
83
84async function getVideoImportOrDie (videoImportId: number) {
85 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
516df59b
C
86 if (!videoImport || !videoImport.Video) {
87 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
88 }
fbad87b0 89
ce33919c
C
90 return videoImport
91}
92
93type ProcessFileOptions = {
2158ac90 94 type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
ce33919c
C
95 videoImportId: number
96
ce33919c
C
97 generateThumbnail: boolean
98 generatePreview: boolean
99}
0283eaac 100async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
fbad87b0 101 let tempVideoPath: string
516df59b
C
102 let videoDestFile: string
103 let videoFile: VideoFileModel
6040f87d 104
fbad87b0
C
105 try {
106 // Download video from youtubeDL
ce33919c 107 tempVideoPath = await downloader()
fbad87b0
C
108
109 // Get information about this video
62689b94 110 const stats = await stat(tempVideoPath)
3e17515e 111 const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
a84b8fa5
C
112 if (isAble === false) {
113 throw new Error('The user video quota is exceeded with this video to import.')
114 }
115
fbad87b0 116 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
d7f83948 117 const fps = await getVideoFileFPS(tempVideoPath)
fbad87b0
C
118 const duration = await getDurationFromVideoFile(tempVideoPath)
119
2158ac90 120 // Prepare video file object for creation in database
fbad87b0
C
121 const videoFileData = {
122 extname: extname(tempVideoPath),
123 resolution: videoFileResolution,
3e17515e 124 size: stats.size,
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
C
162
163 // Process thumbnail
453e83ea 164 let thumbnailModel: MThumbnail
b1770a0a 165 if (options.generateThumbnail) {
0283eaac 166 thumbnailModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.MINIATURE)
fbad87b0
C
167 }
168
169 // Process preview
453e83ea 170 let previewModel: MThumbnail
b1770a0a 171 if (options.generatePreview) {
0283eaac 172 previewModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.PREVIEW)
fbad87b0
C
173 }
174
175 // Create torrent
d7a25329 176 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
fbad87b0 177
453e83ea 178 const { videoImportUpdated, video } = await sequelizeTypescript.transaction(async t => {
0283eaac 179 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
453e83ea 180
516df59b 181 // Refresh video
453e83ea
C
182 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
183 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
516df59b
C
184
185 const videoFileCreated = await videoFile.save({ transaction: t })
453e83ea 186 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
fbad87b0
C
187
188 // Update video DB object
516df59b
C
189 video.duration = duration
190 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
e8d246d5 191 await video.save({ transaction: t })
fbad87b0 192
3acc5084
C
193 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
194 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
e8bafea3 195
590fb506 196 // Now we can federate the video (reload from database, we need more attributes)
627621c1 197 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
590fb506 198 await federateVideoIfNeeded(videoForFederation, true, t)
fbad87b0
C
199
200 // Update video import object
453e83ea
C
201 videoImportToUpdate.state = VideoImportState.SUCCESS
202 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
203 videoImportUpdated.Video = video
fbad87b0 204
541006e3 205 logger.info('Video %s imported.', video.uuid)
fbad87b0 206
453e83ea 207 return { videoImportUpdated, video: videoForFederation }
fbad87b0
C
208 })
209
dc133480 210 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
e8d246d5 211
453e83ea 212 if (video.isBlacklisted()) {
8424c402
C
213 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
214
215 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
7ccddd7b 216 } else {
453e83ea 217 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
7ccddd7b
JM
218 }
219
fbad87b0 220 // Create transcoding jobs?
453e83ea 221 if (video.state === VideoState.TO_TRANSCODE) {
d57d1d83 222 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile)
fbad87b0
C
223 }
224
225 } catch (err) {
226 try {
e95e0463 227 if (tempVideoPath) await remove(tempVideoPath)
fbad87b0 228 } catch (errUnlink) {
516df59b 229 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
fbad87b0
C
230 }
231
d7f83948 232 videoImport.error = err.message
2158ac90
RK
233 if (videoImport.state !== VideoImportState.REJECTED) {
234 videoImport.state = VideoImportState.FAILED
235 }
fbad87b0
C
236 await videoImport.save()
237
dc133480
C
238 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)
239
fbad87b0
C
240 throw err
241 }
242}