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