]>
Commit | Line | Data |
---|---|---|
1 | import * as Bull from 'bull' | |
2 | import { move, remove, stat } from 'fs-extra' | |
3 | import { getLowercaseExtension } from '@server/helpers/core-utils' | |
4 | import { retryTransactionWrapper } from '@server/helpers/database-utils' | |
5 | import { YoutubeDL } 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 } from '../../../../shared/models/videos' | |
25 | import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type' | |
26 | import { 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 | ||
40 | async function processVideoImport (job: Bull.Job) { | |
41 | const payload = job.data as VideoImportPayload | |
42 | ||
43 | if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload) | |
44 | if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload) | |
45 | } | |
46 | ||
47 | // --------------------------------------------------------------------------- | |
48 | ||
49 | export { | |
50 | processVideoImport | |
51 | } | |
52 | ||
53 | // --------------------------------------------------------------------------- | |
54 | ||
55 | async 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) | |
59 | ||
60 | const options = { | |
61 | type: payload.type, | |
62 | videoImportId: payload.videoImportId | |
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 | type: payload.type, | |
77 | videoImportId: videoImport.id | |
78 | } | |
79 | ||
80 | const youtubeDL = new YoutubeDL(videoImport.targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod')) | |
81 | ||
82 | return processFile( | |
83 | () => youtubeDL.downloadYoutubeDLVideo(payload.fileExt, VIDEO_IMPORT_TIMEOUT), | |
84 | videoImport, | |
85 | options | |
86 | ) | |
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 | type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType | |
100 | videoImportId: number | |
101 | } | |
102 | async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) { | |
103 | let tempVideoPath: string | |
104 | let videoFile: VideoFileModel | |
105 | ||
106 | try { | |
107 | // Download video from youtubeDL | |
108 | tempVideoPath = await downloader() | |
109 | ||
110 | // Get information about this video | |
111 | const stats = await stat(tempVideoPath) | |
112 | const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size) | |
113 | if (isAble === false) { | |
114 | throw new Error('The user video quota is exceeded with this video to import.') | |
115 | } | |
116 | ||
117 | const { resolution } = await getVideoFileResolution(tempVideoPath) | |
118 | const fps = await getVideoFileFPS(tempVideoPath) | |
119 | const duration = await getDurationFromVideoFile(tempVideoPath) | |
120 | ||
121 | // Prepare video file object for creation in database | |
122 | const fileExt = getLowercaseExtension(tempVideoPath) | |
123 | const videoFileData = { | |
124 | extname: fileExt, | |
125 | resolution, | |
126 | size: stats.size, | |
127 | filename: generateWebTorrentVideoFilename(resolution, fileExt), | |
128 | fps, | |
129 | videoId: videoImport.videoId | |
130 | } | |
131 | videoFile = new VideoFileModel(videoFileData) | |
132 | ||
133 | const hookName = options.type === 'youtube-dl' | |
134 | ? 'filter:api.video.post-import-url.accept.result' | |
135 | : 'filter:api.video.post-import-torrent.accept.result' | |
136 | ||
137 | // Check we accept this video | |
138 | const acceptParameters = { | |
139 | videoImport, | |
140 | video: videoImport.Video, | |
141 | videoFilePath: tempVideoPath, | |
142 | videoFile, | |
143 | user: videoImport.User | |
144 | } | |
145 | const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName) | |
146 | ||
147 | if (acceptedResult.accepted !== true) { | |
148 | logger.info('Refused imported video.', { acceptedResult, acceptParameters }) | |
149 | ||
150 | videoImport.state = VideoImportState.REJECTED | |
151 | await videoImport.save() | |
152 | ||
153 | throw new Error(acceptedResult.errorMessage) | |
154 | } | |
155 | ||
156 | // Video is accepted, resuming preparation | |
157 | const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] }) | |
158 | // To clean files if the import fails | |
159 | const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles }) | |
160 | ||
161 | // Move file | |
162 | const videoDestFile = VideoPathManager.Instance.getFSVideoFileOutputPath(videoImportWithFiles.Video, videoFile) | |
163 | await move(tempVideoPath, videoDestFile) | |
164 | tempVideoPath = null // This path is not used anymore | |
165 | ||
166 | // Generate miniature if the import did not created it | |
167 | let thumbnailModel: MThumbnail | |
168 | let thumbnailSave: object | |
169 | if (!videoImportWithFiles.Video.getMiniature()) { | |
170 | thumbnailModel = await generateVideoMiniature({ | |
171 | video: videoImportWithFiles.Video, | |
172 | videoFile, | |
173 | type: ThumbnailType.MINIATURE | |
174 | }) | |
175 | thumbnailSave = thumbnailModel.toJSON() | |
176 | } | |
177 | ||
178 | // Generate preview if the import did not created it | |
179 | let previewModel: MThumbnail | |
180 | let previewSave: object | |
181 | if (!videoImportWithFiles.Video.getPreview()) { | |
182 | previewModel = await generateVideoMiniature({ | |
183 | video: videoImportWithFiles.Video, | |
184 | videoFile, | |
185 | type: ThumbnailType.PREVIEW | |
186 | }) | |
187 | previewSave = previewModel.toJSON() | |
188 | } | |
189 | ||
190 | // Create torrent | |
191 | await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile) | |
192 | ||
193 | const videoFileSave = videoFile.toJSON() | |
194 | ||
195 | const { videoImportUpdated, video } = await retryTransactionWrapper(() => { | |
196 | return sequelizeTypescript.transaction(async t => { | |
197 | const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo | |
198 | ||
199 | // Refresh video | |
200 | const video = await VideoModel.load(videoImportToUpdate.videoId, t) | |
201 | if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.') | |
202 | ||
203 | const videoFileCreated = await videoFile.save({ transaction: t }) | |
204 | ||
205 | // Update video DB object | |
206 | video.duration = duration | |
207 | video.state = buildNextVideoState(video.state) | |
208 | await video.save({ transaction: t }) | |
209 | ||
210 | if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t) | |
211 | if (previewModel) await video.addAndSaveThumbnail(previewModel, t) | |
212 | ||
213 | // Now we can federate the video (reload from database, we need more attributes) | |
214 | const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t) | |
215 | await federateVideoIfNeeded(videoForFederation, true, t) | |
216 | ||
217 | // Update video import object | |
218 | videoImportToUpdate.state = VideoImportState.SUCCESS | |
219 | const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo | |
220 | videoImportUpdated.Video = video | |
221 | ||
222 | videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] }) | |
223 | ||
224 | logger.info('Video %s imported.', video.uuid) | |
225 | ||
226 | return { videoImportUpdated, video: videoForFederation } | |
227 | }).catch(err => { | |
228 | // Reset fields | |
229 | if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave) | |
230 | if (previewModel) previewModel = new ThumbnailModel(previewSave) | |
231 | ||
232 | videoFile = new VideoFileModel(videoFileSave) | |
233 | ||
234 | throw err | |
235 | }) | |
236 | }) | |
237 | ||
238 | Notifier.Instance.notifyOnFinishedVideoImport({ videoImport: videoImportUpdated, success: true }) | |
239 | ||
240 | if (video.isBlacklisted()) { | |
241 | const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video }) | |
242 | ||
243 | Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist) | |
244 | } else { | |
245 | Notifier.Instance.notifyOnNewVideoIfNeeded(video) | |
246 | } | |
247 | ||
248 | if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) { | |
249 | return addMoveToObjectStorageJob(videoImportUpdated.Video) | |
250 | } | |
251 | ||
252 | // Create transcoding jobs? | |
253 | if (video.state === VideoState.TO_TRANSCODE) { | |
254 | await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User) | |
255 | } | |
256 | ||
257 | } catch (err) { | |
258 | try { | |
259 | if (tempVideoPath) await remove(tempVideoPath) | |
260 | } catch (errUnlink) { | |
261 | logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink }) | |
262 | } | |
263 | ||
264 | videoImport.error = err.message | |
265 | if (videoImport.state !== VideoImportState.REJECTED) { | |
266 | videoImport.state = VideoImportState.FAILED | |
267 | } | |
268 | await videoImport.save() | |
269 | ||
270 | Notifier.Instance.notifyOnFinishedVideoImport({ videoImport, success: false }) | |
271 | ||
272 | throw err | |
273 | } | |
274 | } |