]>
Commit | Line | Data |
---|---|---|
1 | import { Job } from 'bull' | |
2 | import { move, remove, stat } from 'fs-extra' | |
3 | import { getLowercaseExtension } from '@shared/core-utils' | |
4 | import { retryTransactionWrapper } from '@server/helpers/database-utils' | |
5 | import { YoutubeDLWrapper } from '@server/helpers/youtube-dl' | |
6 | import { isPostImportVideoAccepted } from '@server/lib/moderation' | |
7 | import { generateWebTorrentVideoFilename } from '@server/lib/paths' | |
8 | import { Hooks } from '@server/lib/plugins/hooks' | |
9 | import { ServerConfigManager } from '@server/lib/server-config-manager' | |
10 | import { isAbleToUploadVideo } from '@server/lib/user' | |
11 | import { addMoveToObjectStorageJob, addOptimizeOrMergeAudioJob } from '@server/lib/video' | |
12 | import { VideoPathManager } from '@server/lib/video-path-manager' | |
13 | import { buildNextVideoState } from '@server/lib/video-state' | |
14 | import { ThumbnailModel } from '@server/models/video/thumbnail' | |
15 | import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import' | |
16 | import { | |
17 | VideoImportPayload, | |
18 | VideoImportTorrentPayload, | |
19 | VideoImportTorrentPayloadType, | |
20 | VideoImportYoutubeDLPayload, | |
21 | VideoImportYoutubeDLPayloadType, | |
22 | VideoState | |
23 | } from '../../../../shared' | |
24 | import { VideoImportState, VideoResolution } from '../../../../shared/models/videos' | |
25 | import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type' | |
26 | import { ffprobePromise, getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils' | |
27 | import { logger } from '../../../helpers/logger' | |
28 | import { getSecureTorrentName } from '../../../helpers/utils' | |
29 | import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent' | |
30 | import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants' | |
31 | import { sequelizeTypescript } from '../../../initializers/database' | |
32 | import { VideoModel } from '../../../models/video/video' | |
33 | import { VideoFileModel } from '../../../models/video/video-file' | |
34 | import { VideoImportModel } from '../../../models/video/video-import' | |
35 | import { MThumbnail } from '../../../types/models/video/thumbnail' | |
36 | import { federateVideoIfNeeded } from '../../activitypub/videos' | |
37 | import { Notifier } from '../../notifier' | |
38 | import { generateVideoMiniature } from '../../thumbnail' | |
39 | import { isAudioFile } from '@shared/extra-utils' | |
40 | ||
41 | async function processVideoImport (job: 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: 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 | type: payload.type, | |
63 | videoImportId: payload.videoImportId | |
64 | } | |
65 | const target = { | |
66 | torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined, | |
67 | uri: videoImport.magnetUri | |
68 | } | |
69 | return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options) | |
70 | } | |
71 | ||
72 | async function processYoutubeDLImport (job: Job, payload: VideoImportYoutubeDLPayload) { | |
73 | logger.info('Processing youtubeDL video import in job %d.', job.id) | |
74 | ||
75 | const videoImport = await getVideoImportOrDie(payload.videoImportId) | |
76 | const options = { | |
77 | type: payload.type, | |
78 | videoImportId: videoImport.id | |
79 | } | |
80 | ||
81 | const youtubeDL = new YoutubeDLWrapper(videoImport.targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod')) | |
82 | ||
83 | return processFile( | |
84 | () => youtubeDL.downloadVideo(payload.fileExt, VIDEO_IMPORT_TIMEOUT), | |
85 | videoImport, | |
86 | options | |
87 | ) | |
88 | } | |
89 | ||
90 | async function getVideoImportOrDie (videoImportId: number) { | |
91 | const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId) | |
92 | if (!videoImport || !videoImport.Video) { | |
93 | throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.') | |
94 | } | |
95 | ||
96 | return videoImport | |
97 | } | |
98 | ||
99 | type ProcessFileOptions = { | |
100 | type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType | |
101 | videoImportId: number | |
102 | } | |
103 | async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) { | |
104 | let tempVideoPath: string | |
105 | let videoFile: VideoFileModel | |
106 | ||
107 | try { | |
108 | // Download video from youtubeDL | |
109 | tempVideoPath = await downloader() | |
110 | ||
111 | // Get information about this video | |
112 | const stats = await stat(tempVideoPath) | |
113 | const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size) | |
114 | if (isAble === false) { | |
115 | throw new Error('The user video quota is exceeded with this video to import.') | |
116 | } | |
117 | ||
118 | const probe = await ffprobePromise(tempVideoPath) | |
119 | ||
120 | const { resolution } = await isAudioFile(tempVideoPath, probe) | |
121 | ? { resolution: VideoResolution.H_NOVIDEO } | |
122 | : await getVideoFileResolution(tempVideoPath) | |
123 | ||
124 | const fps = await getVideoFileFPS(tempVideoPath, probe) | |
125 | const duration = await getDurationFromVideoFile(tempVideoPath, probe) | |
126 | ||
127 | // Prepare video file object for creation in database | |
128 | const fileExt = getLowercaseExtension(tempVideoPath) | |
129 | const videoFileData = { | |
130 | extname: fileExt, | |
131 | resolution, | |
132 | size: stats.size, | |
133 | filename: generateWebTorrentVideoFilename(resolution, fileExt), | |
134 | fps, | |
135 | videoId: videoImport.videoId | |
136 | } | |
137 | videoFile = new VideoFileModel(videoFileData) | |
138 | ||
139 | const hookName = options.type === 'youtube-dl' | |
140 | ? 'filter:api.video.post-import-url.accept.result' | |
141 | : 'filter:api.video.post-import-torrent.accept.result' | |
142 | ||
143 | // Check we accept this video | |
144 | const acceptParameters = { | |
145 | videoImport, | |
146 | video: videoImport.Video, | |
147 | videoFilePath: tempVideoPath, | |
148 | videoFile, | |
149 | user: videoImport.User | |
150 | } | |
151 | const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName) | |
152 | ||
153 | if (acceptedResult.accepted !== true) { | |
154 | logger.info('Refused imported video.', { acceptedResult, acceptParameters }) | |
155 | ||
156 | videoImport.state = VideoImportState.REJECTED | |
157 | await videoImport.save() | |
158 | ||
159 | throw new Error(acceptedResult.errorMessage) | |
160 | } | |
161 | ||
162 | // Video is accepted, resuming preparation | |
163 | const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] }) | |
164 | // To clean files if the import fails | |
165 | const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles }) | |
166 | ||
167 | // Move file | |
168 | const videoDestFile = VideoPathManager.Instance.getFSVideoFileOutputPath(videoImportWithFiles.Video, videoFile) | |
169 | await move(tempVideoPath, videoDestFile) | |
170 | tempVideoPath = null // This path is not used anymore | |
171 | ||
172 | // Generate miniature if the import did not created it | |
173 | let thumbnailModel: MThumbnail | |
174 | let thumbnailSave: object | |
175 | if (!videoImportWithFiles.Video.getMiniature()) { | |
176 | thumbnailModel = await generateVideoMiniature({ | |
177 | video: videoImportWithFiles.Video, | |
178 | videoFile, | |
179 | type: ThumbnailType.MINIATURE | |
180 | }) | |
181 | thumbnailSave = thumbnailModel.toJSON() | |
182 | } | |
183 | ||
184 | // Generate preview if the import did not created it | |
185 | let previewModel: MThumbnail | |
186 | let previewSave: object | |
187 | if (!videoImportWithFiles.Video.getPreview()) { | |
188 | previewModel = await generateVideoMiniature({ | |
189 | video: videoImportWithFiles.Video, | |
190 | videoFile, | |
191 | type: ThumbnailType.PREVIEW | |
192 | }) | |
193 | previewSave = previewModel.toJSON() | |
194 | } | |
195 | ||
196 | // Create torrent | |
197 | await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile) | |
198 | ||
199 | const videoFileSave = videoFile.toJSON() | |
200 | ||
201 | const { videoImportUpdated, video } = await retryTransactionWrapper(() => { | |
202 | return sequelizeTypescript.transaction(async t => { | |
203 | const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo | |
204 | ||
205 | // Refresh video | |
206 | const video = await VideoModel.load(videoImportToUpdate.videoId, t) | |
207 | if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.') | |
208 | ||
209 | const videoFileCreated = await videoFile.save({ transaction: t }) | |
210 | ||
211 | // Update video DB object | |
212 | video.duration = duration | |
213 | video.state = buildNextVideoState(video.state) | |
214 | await video.save({ transaction: t }) | |
215 | ||
216 | if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t) | |
217 | if (previewModel) await video.addAndSaveThumbnail(previewModel, t) | |
218 | ||
219 | // Now we can federate the video (reload from database, we need more attributes) | |
220 | const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t) | |
221 | await federateVideoIfNeeded(videoForFederation, true, t) | |
222 | ||
223 | // Update video import object | |
224 | videoImportToUpdate.state = VideoImportState.SUCCESS | |
225 | const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo | |
226 | videoImportUpdated.Video = video | |
227 | ||
228 | videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] }) | |
229 | ||
230 | logger.info('Video %s imported.', video.uuid) | |
231 | ||
232 | return { videoImportUpdated, video: videoForFederation } | |
233 | }).catch(err => { | |
234 | // Reset fields | |
235 | if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave) | |
236 | if (previewModel) previewModel = new ThumbnailModel(previewSave) | |
237 | ||
238 | videoFile = new VideoFileModel(videoFileSave) | |
239 | ||
240 | throw err | |
241 | }) | |
242 | }) | |
243 | ||
244 | Notifier.Instance.notifyOnFinishedVideoImport({ videoImport: videoImportUpdated, success: true }) | |
245 | ||
246 | if (video.isBlacklisted()) { | |
247 | const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video }) | |
248 | ||
249 | Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist) | |
250 | } else { | |
251 | Notifier.Instance.notifyOnNewVideoIfNeeded(video) | |
252 | } | |
253 | ||
254 | if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) { | |
255 | return addMoveToObjectStorageJob(videoImportUpdated.Video) | |
256 | } | |
257 | ||
258 | // Create transcoding jobs? | |
259 | if (video.state === VideoState.TO_TRANSCODE) { | |
260 | await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User) | |
261 | } | |
262 | ||
263 | } catch (err) { | |
264 | try { | |
265 | if (tempVideoPath) await remove(tempVideoPath) | |
266 | } catch (errUnlink) { | |
267 | logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink }) | |
268 | } | |
269 | ||
270 | videoImport.error = err.message | |
271 | if (videoImport.state !== VideoImportState.REJECTED) { | |
272 | videoImport.state = VideoImportState.FAILED | |
273 | } | |
274 | await videoImport.save() | |
275 | ||
276 | Notifier.Instance.notifyOnFinishedVideoImport({ videoImport, success: false }) | |
277 | ||
278 | throw err | |
279 | } | |
280 | } |