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