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