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