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