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