]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/handlers/video-import.ts
Merge branch 'feature/audio-upload' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-import.ts
1 import * as Bull from 'bull'
2 import { logger } from '../../../helpers/logger'
3 import { downloadYoutubeDLVideo } from '../../../helpers/youtube-dl'
4 import { VideoImportModel } from '../../../models/video/video-import'
5 import { VideoImportState } from '../../../../shared/models/videos'
6 import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
7 import { extname, join } from 'path'
8 import { VideoFileModel } from '../../../models/video/video-file'
9 import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
10 import { VideoState } from '../../../../shared'
11 import { JobQueue } from '../index'
12 import { federateVideoIfNeeded } from '../../activitypub'
13 import { VideoModel } from '../../../models/video/video'
14 import { downloadWebTorrentVideo } from '../../../helpers/webtorrent'
15 import { getSecureTorrentName } from '../../../helpers/utils'
16 import { move, remove, stat } from 'fs-extra'
17 import { Notifier } from '../../notifier'
18 import { CONFIG } from '../../../initializers/config'
19 import { sequelizeTypescript } from '../../../initializers/database'
20 import { ThumbnailModel } from '../../../models/video/thumbnail'
21 import { createVideoMiniatureFromUrl, generateVideoMiniature } from '../../thumbnail'
22 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
23
24 type VideoImportYoutubeDLPayload = {
25 type: 'youtube-dl'
26 videoImportId: number
27
28 thumbnailUrl: string
29 downloadThumbnail: boolean
30 downloadPreview: boolean
31 }
32
33 type VideoImportTorrentPayload = {
34 type: 'magnet-uri' | 'torrent-file'
35 videoImportId: number
36 }
37
38 export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
39
40 async function processVideoImport (job: Bull.Job) {
41 const payload = job.data as VideoImportPayload
42
43 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
44 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
45 }
46
47 // ---------------------------------------------------------------------------
48
49 export {
50 processVideoImport
51 }
52
53 // ---------------------------------------------------------------------------
54
55 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
56 logger.info('Processing torrent video import in job %d.', job.id)
57
58 const videoImport = await getVideoImportOrDie(payload.videoImportId)
59
60 const options = {
61 videoImportId: payload.videoImportId,
62
63 downloadThumbnail: false,
64 downloadPreview: false,
65
66 generateThumbnail: true,
67 generatePreview: true
68 }
69 const target = {
70 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
71 magnetUri: videoImport.magnetUri
72 }
73 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
74 }
75
76 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
77 logger.info('Processing youtubeDL video import in job %d.', job.id)
78
79 const videoImport = await getVideoImportOrDie(payload.videoImportId)
80 const options = {
81 videoImportId: videoImport.id,
82
83 downloadThumbnail: payload.downloadThumbnail,
84 downloadPreview: payload.downloadPreview,
85 thumbnailUrl: payload.thumbnailUrl,
86
87 generateThumbnail: false,
88 generatePreview: false
89 }
90
91 return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl, VIDEO_IMPORT_TIMEOUT), videoImport, options)
92 }
93
94 async function getVideoImportOrDie (videoImportId: number) {
95 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
96 if (!videoImport || !videoImport.Video) {
97 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
98 }
99
100 return videoImport
101 }
102
103 type ProcessFileOptions = {
104 videoImportId: number
105
106 downloadThumbnail: boolean
107 downloadPreview: boolean
108 thumbnailUrl?: string
109
110 generateThumbnail: boolean
111 generatePreview: boolean
112 }
113 async function processFile (downloader: () => Promise<string>, videoImport: VideoImportModel, options: ProcessFileOptions) {
114 let tempVideoPath: string
115 let videoDestFile: string
116 let videoFile: VideoFileModel
117
118 try {
119 // Download video from youtubeDL
120 tempVideoPath = await downloader()
121
122 // Get information about this video
123 const stats = await stat(tempVideoPath)
124 const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
125 if (isAble === false) {
126 throw new Error('The user video quota is exceeded with this video to import.')
127 }
128
129 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
130 const fps = await getVideoFileFPS(tempVideoPath)
131 const duration = await getDurationFromVideoFile(tempVideoPath)
132
133 // Create video file object in database
134 const videoFileData = {
135 extname: extname(tempVideoPath),
136 resolution: videoFileResolution,
137 size: stats.size,
138 fps,
139 videoId: videoImport.videoId
140 }
141 videoFile = new VideoFileModel(videoFileData)
142 // To clean files if the import fails
143 videoImport.Video.VideoFiles = [ videoFile ]
144
145 // Move file
146 videoDestFile = join(CONFIG.STORAGE.VIDEOS_DIR, videoImport.Video.getVideoFilename(videoFile))
147 await move(tempVideoPath, videoDestFile)
148 tempVideoPath = null // This path is not used anymore
149
150 // Process thumbnail
151 let thumbnailModel: ThumbnailModel
152 if (options.downloadThumbnail && options.thumbnailUrl) {
153 thumbnailModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImport.Video, ThumbnailType.MINIATURE)
154 } else if (options.generateThumbnail || options.downloadThumbnail) {
155 thumbnailModel = await generateVideoMiniature(videoImport.Video, videoFile, ThumbnailType.MINIATURE)
156 }
157
158 // Process preview
159 let previewModel: ThumbnailModel
160 if (options.downloadPreview && options.thumbnailUrl) {
161 previewModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImport.Video, ThumbnailType.PREVIEW)
162 } else if (options.generatePreview || options.downloadPreview) {
163 previewModel = await generateVideoMiniature(videoImport.Video, videoFile, ThumbnailType.PREVIEW)
164 }
165
166 // Create torrent
167 await videoImport.Video.createTorrentAndSetInfoHash(videoFile)
168
169 const videoImportUpdated: VideoImportModel = await sequelizeTypescript.transaction(async t => {
170 // Refresh video
171 const video = await VideoModel.load(videoImport.videoId, t)
172 if (!video) throw new Error('Video linked to import ' + videoImport.videoId + ' does not exist anymore.')
173 videoImport.Video = video
174
175 const videoFileCreated = await videoFile.save({ transaction: t })
176 video.VideoFiles = [ videoFileCreated ]
177
178 // Update video DB object
179 video.duration = duration
180 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
181 await video.save({ transaction: t })
182
183 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
184 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
185
186 // Now we can federate the video (reload from database, we need more attributes)
187 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
188 await federateVideoIfNeeded(videoForFederation, true, t)
189
190 // Update video import object
191 videoImport.state = VideoImportState.SUCCESS
192 const videoImportUpdated = await videoImport.save({ transaction: t })
193
194 logger.info('Video %s imported.', video.uuid)
195
196 videoImportUpdated.Video = videoForFederation
197 return videoImportUpdated
198 })
199
200 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
201
202 if (videoImportUpdated.Video.VideoBlacklist) {
203 Notifier.Instance.notifyOnVideoAutoBlacklist(videoImportUpdated.Video)
204 } else {
205 Notifier.Instance.notifyOnNewVideo(videoImportUpdated.Video)
206 }
207
208 // Create transcoding jobs?
209 if (videoImportUpdated.Video.state === VideoState.TO_TRANSCODE) {
210 // Put uuid because we don't have id auto incremented for now
211 const dataInput = {
212 type: 'optimize' as 'optimize',
213 videoUUID: videoImportUpdated.Video.uuid,
214 isNewVideo: true
215 }
216
217 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
218 }
219
220 } catch (err) {
221 try {
222 if (tempVideoPath) await remove(tempVideoPath)
223 } catch (errUnlink) {
224 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
225 }
226
227 videoImport.error = err.message
228 videoImport.state = VideoImportState.FAILED
229 await videoImport.save()
230
231 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)
232
233 throw err
234 }
235 }