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