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