]>
Commit | Line | Data |
---|---|---|
1 | import express from 'express' | |
2 | import { move, readFile } from 'fs-extra' | |
3 | import { decode } from 'magnet-uri' | |
4 | import parseTorrent, { Instance } from 'parse-torrent' | |
5 | import { join } from 'path' | |
6 | import { isVideoFileExtnameValid } from '@server/helpers/custom-validators/videos' | |
7 | import { Hooks } from '@server/lib/plugins/hooks' | |
8 | import { ServerConfigManager } from '@server/lib/server-config-manager' | |
9 | import { setVideoTags } from '@server/lib/video' | |
10 | import { FilteredModelAttributes } from '@server/types' | |
11 | import { | |
12 | MChannelAccountDefault, | |
13 | MThumbnail, | |
14 | MUser, | |
15 | MVideoAccountDefault, | |
16 | MVideoCaption, | |
17 | MVideoTag, | |
18 | MVideoThumbnail, | |
19 | MVideoWithBlacklistLight | |
20 | } from '@server/types/models' | |
21 | import { MVideoImportFormattable } from '@server/types/models/video/video-import' | |
22 | import { ServerErrorCode, ThumbnailType, VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '@shared/models' | |
23 | import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger' | |
24 | import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils' | |
25 | import { isArray } from '../../../helpers/custom-validators/misc' | |
26 | import { cleanUpReqFiles, createReqFiles } from '../../../helpers/express-utils' | |
27 | import { logger } from '../../../helpers/logger' | |
28 | import { getSecureTorrentName } from '../../../helpers/utils' | |
29 | import { YoutubeDLInfo, YoutubeDLWrapper } from '../../../helpers/youtube-dl' | |
30 | import { CONFIG } from '../../../initializers/config' | |
31 | import { MIMETYPES } from '../../../initializers/constants' | |
32 | import { sequelizeTypescript } from '../../../initializers/database' | |
33 | import { getLocalVideoActivityPubUrl } from '../../../lib/activitypub/url' | |
34 | import { JobQueue } from '../../../lib/job-queue/job-queue' | |
35 | import { updateVideoMiniatureFromExisting, updateVideoMiniatureFromUrl } from '../../../lib/thumbnail' | |
36 | import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' | |
37 | import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares' | |
38 | import { VideoModel } from '../../../models/video/video' | |
39 | import { VideoCaptionModel } from '../../../models/video/video-caption' | |
40 | import { VideoImportModel } from '../../../models/video/video-import' | |
41 | ||
42 | const auditLogger = auditLoggerFactory('video-imports') | |
43 | const videoImportsRouter = express.Router() | |
44 | ||
45 | const reqVideoFileImport = createReqFiles( | |
46 | [ 'thumbnailfile', 'previewfile', 'torrentfile' ], | |
47 | Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT), | |
48 | { | |
49 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, | |
50 | previewfile: CONFIG.STORAGE.TMP_DIR, | |
51 | torrentfile: CONFIG.STORAGE.TMP_DIR | |
52 | } | |
53 | ) | |
54 | ||
55 | videoImportsRouter.post('/imports', | |
56 | authenticate, | |
57 | reqVideoFileImport, | |
58 | asyncMiddleware(videoImportAddValidator), | |
59 | asyncRetryTransactionMiddleware(addVideoImport) | |
60 | ) | |
61 | ||
62 | // --------------------------------------------------------------------------- | |
63 | ||
64 | export { | |
65 | videoImportsRouter | |
66 | } | |
67 | ||
68 | // --------------------------------------------------------------------------- | |
69 | ||
70 | function addVideoImport (req: express.Request, res: express.Response) { | |
71 | if (req.body.targetUrl) return addYoutubeDLImport(req, res) | |
72 | ||
73 | const file = req.files?.['torrentfile']?.[0] | |
74 | if (req.body.magnetUri || file) return addTorrentImport(req, res, file) | |
75 | } | |
76 | ||
77 | async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) { | |
78 | const body: VideoImportCreate = req.body | |
79 | const user = res.locals.oauth.token.User | |
80 | ||
81 | let videoName: string | |
82 | let torrentName: string | |
83 | let magnetUri: string | |
84 | ||
85 | if (torrentfile) { | |
86 | const result = await processTorrentOrAbortRequest(req, res, torrentfile) | |
87 | if (!result) return | |
88 | ||
89 | videoName = result.name | |
90 | torrentName = result.torrentName | |
91 | } else { | |
92 | const result = processMagnetURI(body) | |
93 | magnetUri = result.magnetUri | |
94 | videoName = result.name | |
95 | } | |
96 | ||
97 | const video = await buildVideo(res.locals.videoChannel.id, body, { name: videoName }) | |
98 | ||
99 | const thumbnailModel = await processThumbnail(req, video) | |
100 | const previewModel = await processPreview(req, video) | |
101 | ||
102 | const videoImport = await insertIntoDB({ | |
103 | video, | |
104 | thumbnailModel, | |
105 | previewModel, | |
106 | videoChannel: res.locals.videoChannel, | |
107 | tags: body.tags || undefined, | |
108 | user, | |
109 | videoImportAttributes: { | |
110 | magnetUri, | |
111 | torrentName, | |
112 | state: VideoImportState.PENDING, | |
113 | userId: user.id | |
114 | } | |
115 | }) | |
116 | ||
117 | // Create job to import the video | |
118 | const payload = { | |
119 | type: torrentfile | |
120 | ? 'torrent-file' as 'torrent-file' | |
121 | : 'magnet-uri' as 'magnet-uri', | |
122 | videoImportId: videoImport.id, | |
123 | magnetUri | |
124 | } | |
125 | await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload }) | |
126 | ||
127 | auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) | |
128 | ||
129 | return res.json(videoImport.toFormattedJSON()).end() | |
130 | } | |
131 | ||
132 | async function addYoutubeDLImport (req: express.Request, res: express.Response) { | |
133 | const body: VideoImportCreate = req.body | |
134 | const targetUrl = body.targetUrl | |
135 | const user = res.locals.oauth.token.User | |
136 | ||
137 | const youtubeDL = new YoutubeDLWrapper(targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod')) | |
138 | ||
139 | // Get video infos | |
140 | let youtubeDLInfo: YoutubeDLInfo | |
141 | try { | |
142 | youtubeDLInfo = await youtubeDL.getInfoForDownload() | |
143 | } catch (err) { | |
144 | logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err }) | |
145 | ||
146 | return res.fail({ | |
147 | message: 'Cannot fetch remote information of this URL.', | |
148 | data: { | |
149 | targetUrl | |
150 | } | |
151 | }) | |
152 | } | |
153 | ||
154 | const video = await buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo) | |
155 | ||
156 | // Process video thumbnail from request.files | |
157 | let thumbnailModel = await processThumbnail(req, video) | |
158 | ||
159 | // Process video thumbnail from url if processing from request.files failed | |
160 | if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) { | |
161 | try { | |
162 | thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video) | |
163 | } catch (err) { | |
164 | logger.warn('Cannot process thumbnail %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err }) | |
165 | } | |
166 | } | |
167 | ||
168 | // Process video preview from request.files | |
169 | let previewModel = await processPreview(req, video) | |
170 | ||
171 | // Process video preview from url if processing from request.files failed | |
172 | if (!previewModel && youtubeDLInfo.thumbnailUrl) { | |
173 | try { | |
174 | previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video) | |
175 | } catch (err) { | |
176 | logger.warn('Cannot process preview %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err }) | |
177 | } | |
178 | } | |
179 | ||
180 | const videoImport = await insertIntoDB({ | |
181 | video, | |
182 | thumbnailModel, | |
183 | previewModel, | |
184 | videoChannel: res.locals.videoChannel, | |
185 | tags: body.tags || youtubeDLInfo.tags, | |
186 | user, | |
187 | videoImportAttributes: { | |
188 | targetUrl, | |
189 | state: VideoImportState.PENDING, | |
190 | userId: user.id | |
191 | } | |
192 | }) | |
193 | ||
194 | // Get video subtitles | |
195 | await processYoutubeSubtitles(youtubeDL, targetUrl, video.id) | |
196 | ||
197 | let fileExt = `.${youtubeDLInfo.ext}` | |
198 | if (!isVideoFileExtnameValid(fileExt)) fileExt = '.mp4' | |
199 | ||
200 | // Create job to import the video | |
201 | const payload = { | |
202 | type: 'youtube-dl' as 'youtube-dl', | |
203 | videoImportId: videoImport.id, | |
204 | fileExt | |
205 | } | |
206 | await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload }) | |
207 | ||
208 | auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) | |
209 | ||
210 | return res.json(videoImport.toFormattedJSON()).end() | |
211 | } | |
212 | ||
213 | async function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): Promise<MVideoThumbnail> { | |
214 | let videoData = { | |
215 | name: body.name || importData.name || 'Unknown name', | |
216 | remote: false, | |
217 | category: body.category || importData.category, | |
218 | licence: body.licence ?? importData.licence ?? CONFIG.DEFAULTS.PUBLISH.LICENCE, | |
219 | language: body.language || importData.language, | |
220 | commentsEnabled: body.commentsEnabled ?? CONFIG.DEFAULTS.PUBLISH.COMMENTS_ENABLED, | |
221 | downloadEnabled: body.downloadEnabled ?? CONFIG.DEFAULTS.PUBLISH.DOWNLOAD_ENABLED, | |
222 | waitTranscoding: body.waitTranscoding || false, | |
223 | state: VideoState.TO_IMPORT, | |
224 | nsfw: body.nsfw || importData.nsfw || false, | |
225 | description: body.description || importData.description, | |
226 | support: body.support || null, | |
227 | privacy: body.privacy || VideoPrivacy.PRIVATE, | |
228 | duration: 0, // duration will be set by the import job | |
229 | channelId: channelId, | |
230 | originallyPublishedAt: body.originallyPublishedAt | |
231 | ? new Date(body.originallyPublishedAt) | |
232 | : importData.originallyPublishedAt | |
233 | } | |
234 | ||
235 | videoData = await Hooks.wrapObject( | |
236 | videoData, | |
237 | body.targetUrl | |
238 | ? 'filter:api.video.import-url.video-attribute.result' | |
239 | : 'filter:api.video.import-torrent.video-attribute.result' | |
240 | ) | |
241 | ||
242 | const video = new VideoModel(videoData) | |
243 | video.url = getLocalVideoActivityPubUrl(video) | |
244 | ||
245 | return video | |
246 | } | |
247 | ||
248 | async function processThumbnail (req: express.Request, video: MVideoThumbnail) { | |
249 | const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined | |
250 | if (thumbnailField) { | |
251 | const thumbnailPhysicalFile = thumbnailField[0] | |
252 | ||
253 | return updateVideoMiniatureFromExisting({ | |
254 | inputPath: thumbnailPhysicalFile.path, | |
255 | video, | |
256 | type: ThumbnailType.MINIATURE, | |
257 | automaticallyGenerated: false | |
258 | }) | |
259 | } | |
260 | ||
261 | return undefined | |
262 | } | |
263 | ||
264 | async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> { | |
265 | const previewField = req.files ? req.files['previewfile'] : undefined | |
266 | if (previewField) { | |
267 | const previewPhysicalFile = previewField[0] | |
268 | ||
269 | return updateVideoMiniatureFromExisting({ | |
270 | inputPath: previewPhysicalFile.path, | |
271 | video, | |
272 | type: ThumbnailType.PREVIEW, | |
273 | automaticallyGenerated: false | |
274 | }) | |
275 | } | |
276 | ||
277 | return undefined | |
278 | } | |
279 | ||
280 | async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) { | |
281 | try { | |
282 | return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE }) | |
283 | } catch (err) { | |
284 | logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err }) | |
285 | return undefined | |
286 | } | |
287 | } | |
288 | ||
289 | async function processPreviewFromUrl (url: string, video: MVideoThumbnail) { | |
290 | try { | |
291 | return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW }) | |
292 | } catch (err) { | |
293 | logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err }) | |
294 | return undefined | |
295 | } | |
296 | } | |
297 | ||
298 | async function insertIntoDB (parameters: { | |
299 | video: MVideoThumbnail | |
300 | thumbnailModel: MThumbnail | |
301 | previewModel: MThumbnail | |
302 | videoChannel: MChannelAccountDefault | |
303 | tags: string[] | |
304 | videoImportAttributes: FilteredModelAttributes<VideoImportModel> | |
305 | user: MUser | |
306 | }): Promise<MVideoImportFormattable> { | |
307 | const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters | |
308 | ||
309 | const videoImport = await sequelizeTypescript.transaction(async t => { | |
310 | const sequelizeOptions = { transaction: t } | |
311 | ||
312 | // Save video object in database | |
313 | const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag) | |
314 | videoCreated.VideoChannel = videoChannel | |
315 | ||
316 | if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t) | |
317 | if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t) | |
318 | ||
319 | await autoBlacklistVideoIfNeeded({ | |
320 | video: videoCreated, | |
321 | user, | |
322 | notify: false, | |
323 | isRemote: false, | |
324 | isNew: true, | |
325 | transaction: t | |
326 | }) | |
327 | ||
328 | await setVideoTags({ video: videoCreated, tags, transaction: t }) | |
329 | ||
330 | // Create video import object in database | |
331 | const videoImport = await VideoImportModel.create( | |
332 | Object.assign({ videoId: videoCreated.id }, videoImportAttributes), | |
333 | sequelizeOptions | |
334 | ) as MVideoImportFormattable | |
335 | videoImport.Video = videoCreated | |
336 | ||
337 | return videoImport | |
338 | }) | |
339 | ||
340 | return videoImport | |
341 | } | |
342 | ||
343 | async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) { | |
344 | const torrentName = torrentfile.originalname | |
345 | ||
346 | // Rename the torrent to a secured name | |
347 | const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName)) | |
348 | await move(torrentfile.path, newTorrentPath, { overwrite: true }) | |
349 | torrentfile.path = newTorrentPath | |
350 | ||
351 | const buf = await readFile(torrentfile.path) | |
352 | const parsedTorrent = parseTorrent(buf) as Instance | |
353 | ||
354 | if (parsedTorrent.files.length !== 1) { | |
355 | cleanUpReqFiles(req) | |
356 | ||
357 | res.fail({ | |
358 | type: ServerErrorCode.INCORRECT_FILES_IN_TORRENT, | |
359 | message: 'Torrents with only 1 file are supported.' | |
360 | }) | |
361 | return undefined | |
362 | } | |
363 | ||
364 | return { | |
365 | name: extractNameFromArray(parsedTorrent.name), | |
366 | torrentName | |
367 | } | |
368 | } | |
369 | ||
370 | function processMagnetURI (body: VideoImportCreate) { | |
371 | const magnetUri = body.magnetUri | |
372 | const parsed = decode(magnetUri) | |
373 | ||
374 | return { | |
375 | name: extractNameFromArray(parsed.name), | |
376 | magnetUri | |
377 | } | |
378 | } | |
379 | ||
380 | function extractNameFromArray (name: string | string[]) { | |
381 | return isArray(name) ? name[0] : name | |
382 | } | |
383 | ||
384 | async function processYoutubeSubtitles (youtubeDL: YoutubeDLWrapper, targetUrl: string, videoId: number) { | |
385 | try { | |
386 | const subtitles = await youtubeDL.getSubtitles() | |
387 | ||
388 | logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) | |
389 | ||
390 | for (const subtitle of subtitles) { | |
391 | const videoCaption = new VideoCaptionModel({ | |
392 | videoId, | |
393 | language: subtitle.language, | |
394 | filename: VideoCaptionModel.generateCaptionName(subtitle.language) | |
395 | }) as MVideoCaption | |
396 | ||
397 | // Move physical file | |
398 | await moveAndProcessCaptionFile(subtitle, videoCaption) | |
399 | ||
400 | await sequelizeTypescript.transaction(async t => { | |
401 | await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t) | |
402 | }) | |
403 | } | |
404 | } catch (err) { | |
405 | logger.warn('Cannot get video subtitles.', { err }) | |
406 | } | |
407 | } |