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