]>
Commit | Line | Data |
---|---|---|
1ef65f4c | 1 | import * as Bluebird from 'bluebird' |
fbad87b0 | 2 | import * as express from 'express' |
1ef65f4c | 3 | import { move, readFile } from 'fs-extra' |
990b6a0b | 4 | import * as magnetUtil from 'magnet-uri' |
990b6a0b | 5 | import * as parseTorrent from 'parse-torrent' |
1ef65f4c C |
6 | import { join } from 'path' |
7 | import { setVideoTags } from '@server/lib/video' | |
453e83ea | 8 | import { |
0283eaac | 9 | MChannelAccountDefault, |
453e83ea C |
10 | MThumbnail, |
11 | MUser, | |
1ca9f7c3 | 12 | MVideoAccountDefault, |
50ad0a1c | 13 | MVideoCaptionVideo, |
96ca24f0 | 14 | MVideoTag, |
453e83ea C |
15 | MVideoThumbnailAccountDefault, |
16 | MVideoWithBlacklistLight | |
26d6bf65 C |
17 | } from '@server/types/models' |
18 | import { MVideoImport, MVideoImportFormattable } from '@server/types/models/video/video-import' | |
1ef65f4c C |
19 | import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared' |
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' | |
2d53be02 | 39 | import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' |
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 | |
50ad0a1c | 143 | // Get video infos |
fbad87b0 C |
144 | let youtubeDLInfo: YoutubeDLInfo |
145 | try { | |
146 | youtubeDLInfo = await getYoutubeDLInfo(targetUrl) | |
147 | } catch (err) { | |
148 | logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err }) | |
149 | ||
2d53be02 | 150 | return res.status(HttpStatusCode.BAD_REQUEST_400).json({ |
fbad87b0 C |
151 | error: 'Cannot fetch remote information of this URL.' |
152 | }).end() | |
153 | } | |
154 | ||
e8bafea3 | 155 | const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo) |
ce33919c | 156 | |
b1770a0a K |
157 | let thumbnailModel: MThumbnail |
158 | ||
159 | // Process video thumbnail from request.files | |
160 | thumbnailModel = await processThumbnail(req, video) | |
161 | ||
162 | // Process video thumbnail from url if processing from request.files failed | |
86ad0cde | 163 | if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) { |
b1770a0a K |
164 | thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video) |
165 | } | |
166 | ||
167 | let previewModel: MThumbnail | |
168 | ||
169 | // Process video preview from request.files | |
170 | previewModel = await processPreview(req, video) | |
171 | ||
172 | // Process video preview from url if processing from request.files failed | |
86ad0cde | 173 | if (!previewModel && youtubeDLInfo.thumbnailUrl) { |
b1770a0a K |
174 | previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video) |
175 | } | |
ce33919c C |
176 | |
177 | const tags = body.tags || youtubeDLInfo.tags | |
178 | const videoImportAttributes = { | |
179 | targetUrl, | |
a84b8fa5 C |
180 | state: VideoImportState.PENDING, |
181 | userId: user.id | |
ce33919c | 182 | } |
e8bafea3 | 183 | const videoImport = await insertIntoDB({ |
03371ad9 | 184 | video, |
e8bafea3 C |
185 | thumbnailModel, |
186 | previewModel, | |
187 | videoChannel: res.locals.videoChannel, | |
188 | tags, | |
03371ad9 C |
189 | videoImportAttributes, |
190 | user | |
e8bafea3 | 191 | }) |
ce33919c | 192 | |
50ad0a1c | 193 | // Get video subtitles |
194 | try { | |
195 | const subtitles = await getYoutubeDLSubs(targetUrl) | |
196 | ||
652c6416 C |
197 | logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) |
198 | ||
50ad0a1c | 199 | for (const subtitle of subtitles) { |
200 | const videoCaption = new VideoCaptionModel({ | |
201 | videoId: video.id, | |
202 | language: subtitle.language | |
203 | }) as MVideoCaptionVideo | |
204 | videoCaption.Video = video | |
205 | ||
206 | // Move physical file | |
207 | await moveAndProcessCaptionFile(subtitle, videoCaption) | |
208 | ||
209 | await sequelizeTypescript.transaction(async t => { | |
210 | await VideoCaptionModel.insertOrReplaceLanguage(video.id, subtitle.language, null, t) | |
211 | }) | |
212 | } | |
213 | } catch (err) { | |
214 | logger.warn('Cannot get video subtitles.', { err }) | |
215 | } | |
216 | ||
ce33919c C |
217 | // Create job to import the video |
218 | const payload = { | |
219 | type: 'youtube-dl' as 'youtube-dl', | |
220 | videoImportId: videoImport.id, | |
b1770a0a K |
221 | generateThumbnail: !thumbnailModel, |
222 | generatePreview: !previewModel, | |
d57d1d83 C |
223 | fileExt: youtubeDLInfo.fileExt |
224 | ? `.${youtubeDLInfo.fileExt}` | |
225 | : '.mp4' | |
ce33919c | 226 | } |
a1587156 | 227 | await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload }) |
ce33919c | 228 | |
993cef4b | 229 | auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) |
ce33919c C |
230 | |
231 | return res.json(videoImport.toFormattedJSON()).end() | |
232 | } | |
233 | ||
e8bafea3 | 234 | function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) { |
fbad87b0 | 235 | const videoData = { |
ce33919c | 236 | name: body.name || importData.name || 'Unknown name', |
fbad87b0 | 237 | remote: false, |
ce33919c C |
238 | category: body.category || importData.category, |
239 | licence: body.licence || importData.licence, | |
86ad0cde | 240 | language: body.language || importData.language, |
3155c860 C |
241 | commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true" |
242 | downloadEnabled: body.downloadEnabled !== false, | |
fbad87b0 C |
243 | waitTranscoding: body.waitTranscoding || false, |
244 | state: VideoState.TO_IMPORT, | |
ce33919c C |
245 | nsfw: body.nsfw || importData.nsfw || false, |
246 | description: body.description || importData.description, | |
fbad87b0 C |
247 | support: body.support || null, |
248 | privacy: body.privacy || VideoPrivacy.PRIVATE, | |
249 | duration: 0, // duration will be set by the import job | |
4e553a41 | 250 | channelId: channelId, |
8a86e5dc | 251 | originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt |
fbad87b0 C |
252 | } |
253 | const video = new VideoModel(videoData) | |
de94ac86 | 254 | video.url = getLocalVideoActivityPubUrl(video) |
fbad87b0 | 255 | |
ce33919c C |
256 | return video |
257 | } | |
258 | ||
259 | async function processThumbnail (req: express.Request, video: VideoModel) { | |
5d08a6a7 | 260 | const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined |
fbad87b0 | 261 | if (thumbnailField) { |
a1587156 | 262 | const thumbnailPhysicalFile = thumbnailField[0] |
ce33919c | 263 | |
1ef65f4c C |
264 | return createVideoMiniatureFromExisting({ |
265 | inputPath: thumbnailPhysicalFile.path, | |
266 | video, | |
267 | type: ThumbnailType.MINIATURE, | |
268 | automaticallyGenerated: false | |
269 | }) | |
fbad87b0 C |
270 | } |
271 | ||
e8bafea3 | 272 | return undefined |
ce33919c C |
273 | } |
274 | ||
275 | async function processPreview (req: express.Request, video: VideoModel) { | |
5d08a6a7 | 276 | const previewField = req.files ? req.files['previewfile'] : undefined |
fbad87b0 C |
277 | if (previewField) { |
278 | const previewPhysicalFile = previewField[0] | |
ce33919c | 279 | |
1ef65f4c C |
280 | return createVideoMiniatureFromExisting({ |
281 | inputPath: previewPhysicalFile.path, | |
282 | video, | |
283 | type: ThumbnailType.PREVIEW, | |
284 | automaticallyGenerated: false | |
285 | }) | |
fbad87b0 C |
286 | } |
287 | ||
e8bafea3 | 288 | return undefined |
ce33919c C |
289 | } |
290 | ||
b1770a0a K |
291 | async function processThumbnailFromUrl (url: string, video: VideoModel) { |
292 | try { | |
293 | return createVideoMiniatureFromUrl(url, video, ThumbnailType.MINIATURE) | |
294 | } catch (err) { | |
295 | logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err }) | |
296 | return undefined | |
297 | } | |
298 | } | |
299 | ||
300 | async function processPreviewFromUrl (url: string, video: VideoModel) { | |
301 | try { | |
302 | return createVideoMiniatureFromUrl(url, video, ThumbnailType.PREVIEW) | |
303 | } catch (err) { | |
304 | logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err }) | |
305 | return undefined | |
306 | } | |
307 | } | |
308 | ||
e8bafea3 | 309 | function insertIntoDB (parameters: { |
a1587156 C |
310 | video: MVideoThumbnailAccountDefault |
311 | thumbnailModel: MThumbnail | |
312 | previewModel: MThumbnail | |
313 | videoChannel: MChannelAccountDefault | |
314 | tags: string[] | |
315 | videoImportAttributes: Partial<MVideoImport> | |
453e83ea | 316 | user: MUser |
1ca9f7c3 | 317 | }): Bluebird<MVideoImportFormattable> { |
03371ad9 | 318 | const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters |
e8bafea3 | 319 | |
ce33919c | 320 | return sequelizeTypescript.transaction(async t => { |
fbad87b0 C |
321 | const sequelizeOptions = { transaction: t } |
322 | ||
323 | // Save video object in database | |
1ca9f7c3 | 324 | const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag) |
ce33919c | 325 | videoCreated.VideoChannel = videoChannel |
fbad87b0 | 326 | |
3acc5084 C |
327 | if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t) |
328 | if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t) | |
e8bafea3 | 329 | |
5b77537c | 330 | await autoBlacklistVideoIfNeeded({ |
453e83ea | 331 | video: videoCreated, |
5b77537c C |
332 | user, |
333 | notify: false, | |
334 | isRemote: false, | |
335 | isNew: true, | |
336 | transaction: t | |
337 | }) | |
7ccddd7b | 338 | |
1ef65f4c | 339 | await setVideoTags({ video: videoCreated, tags, transaction: t }) |
fbad87b0 C |
340 | |
341 | // Create video import object in database | |
ce33919c C |
342 | const videoImport = await VideoImportModel.create( |
343 | Object.assign({ videoId: videoCreated.id }, videoImportAttributes), | |
344 | sequelizeOptions | |
1ca9f7c3 | 345 | ) as MVideoImportFormattable |
fbad87b0 C |
346 | videoImport.Video = videoCreated |
347 | ||
348 | return videoImport | |
349 | }) | |
fbad87b0 | 350 | } |