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