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