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