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