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