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