]>
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' | |
31 | import { getVideoActivityPubUrl } from '../../../lib/activitypub/url' | |
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 | ||
149 | return res.status(400).json({ | |
150 | error: 'Cannot fetch remote information of this URL.' | |
151 | }).end() | |
152 | } | |
153 | ||
e8bafea3 | 154 | const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo) |
ce33919c | 155 | |
b1770a0a K |
156 | let thumbnailModel: MThumbnail |
157 | ||
158 | // Process video thumbnail from request.files | |
159 | thumbnailModel = await processThumbnail(req, video) | |
160 | ||
161 | // Process video thumbnail from url if processing from request.files failed | |
86ad0cde | 162 | if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) { |
b1770a0a K |
163 | thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video) |
164 | } | |
165 | ||
166 | let previewModel: MThumbnail | |
167 | ||
168 | // Process video preview from request.files | |
169 | previewModel = await processPreview(req, video) | |
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 { | |
194 | const subtitles = await getYoutubeDLSubs(targetUrl) | |
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, | |
201 | language: subtitle.language | |
202 | }) as MVideoCaptionVideo | |
203 | videoCaption.Video = video | |
204 | ||
205 | // Move physical file | |
206 | await moveAndProcessCaptionFile(subtitle, videoCaption) | |
207 | ||
208 | await sequelizeTypescript.transaction(async t => { | |
209 | await VideoCaptionModel.insertOrReplaceLanguage(video.id, subtitle.language, null, t) | |
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, | |
b1770a0a K |
220 | generateThumbnail: !thumbnailModel, |
221 | generatePreview: !previewModel, | |
d57d1d83 C |
222 | fileExt: youtubeDLInfo.fileExt |
223 | ? `.${youtubeDLInfo.fileExt}` | |
224 | : '.mp4' | |
ce33919c | 225 | } |
a1587156 | 226 | await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload }) |
ce33919c | 227 | |
993cef4b | 228 | auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) |
ce33919c C |
229 | |
230 | return res.json(videoImport.toFormattedJSON()).end() | |
231 | } | |
232 | ||
e8bafea3 | 233 | function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) { |
fbad87b0 | 234 | const videoData = { |
ce33919c | 235 | name: body.name || importData.name || 'Unknown name', |
fbad87b0 | 236 | remote: false, |
ce33919c C |
237 | category: body.category || importData.category, |
238 | licence: body.licence || importData.licence, | |
86ad0cde | 239 | language: body.language || importData.language, |
3155c860 C |
240 | commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true" |
241 | downloadEnabled: body.downloadEnabled !== false, | |
fbad87b0 C |
242 | waitTranscoding: body.waitTranscoding || false, |
243 | state: VideoState.TO_IMPORT, | |
ce33919c C |
244 | nsfw: body.nsfw || importData.nsfw || false, |
245 | description: body.description || importData.description, | |
fbad87b0 C |
246 | support: body.support || null, |
247 | privacy: body.privacy || VideoPrivacy.PRIVATE, | |
248 | duration: 0, // duration will be set by the import job | |
4e553a41 | 249 | channelId: channelId, |
8a86e5dc | 250 | originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt |
fbad87b0 C |
251 | } |
252 | const video = new VideoModel(videoData) | |
253 | video.url = getVideoActivityPubUrl(video) | |
254 | ||
ce33919c C |
255 | return video |
256 | } | |
257 | ||
258 | async function processThumbnail (req: express.Request, video: VideoModel) { | |
5d08a6a7 | 259 | const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined |
fbad87b0 | 260 | if (thumbnailField) { |
a1587156 | 261 | const thumbnailPhysicalFile = thumbnailField[0] |
ce33919c | 262 | |
1ef65f4c C |
263 | return createVideoMiniatureFromExisting({ |
264 | inputPath: thumbnailPhysicalFile.path, | |
265 | video, | |
266 | type: ThumbnailType.MINIATURE, | |
267 | automaticallyGenerated: false | |
268 | }) | |
fbad87b0 C |
269 | } |
270 | ||
e8bafea3 | 271 | return undefined |
ce33919c C |
272 | } |
273 | ||
274 | async function processPreview (req: express.Request, video: VideoModel) { | |
5d08a6a7 | 275 | const previewField = req.files ? req.files['previewfile'] : undefined |
fbad87b0 C |
276 | if (previewField) { |
277 | const previewPhysicalFile = previewField[0] | |
ce33919c | 278 | |
1ef65f4c C |
279 | return createVideoMiniatureFromExisting({ |
280 | inputPath: previewPhysicalFile.path, | |
281 | video, | |
282 | type: ThumbnailType.PREVIEW, | |
283 | automaticallyGenerated: false | |
284 | }) | |
fbad87b0 C |
285 | } |
286 | ||
e8bafea3 | 287 | return undefined |
ce33919c C |
288 | } |
289 | ||
b1770a0a K |
290 | async function processThumbnailFromUrl (url: string, video: VideoModel) { |
291 | try { | |
292 | return createVideoMiniatureFromUrl(url, video, ThumbnailType.MINIATURE) | |
293 | } catch (err) { | |
294 | logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err }) | |
295 | return undefined | |
296 | } | |
297 | } | |
298 | ||
299 | async function processPreviewFromUrl (url: string, video: VideoModel) { | |
300 | try { | |
301 | return createVideoMiniatureFromUrl(url, video, ThumbnailType.PREVIEW) | |
302 | } catch (err) { | |
303 | logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err }) | |
304 | return undefined | |
305 | } | |
306 | } | |
307 | ||
e8bafea3 | 308 | function insertIntoDB (parameters: { |
a1587156 C |
309 | video: MVideoThumbnailAccountDefault |
310 | thumbnailModel: MThumbnail | |
311 | previewModel: MThumbnail | |
312 | videoChannel: MChannelAccountDefault | |
313 | tags: string[] | |
314 | videoImportAttributes: Partial<MVideoImport> | |
453e83ea | 315 | user: MUser |
1ca9f7c3 | 316 | }): Bluebird<MVideoImportFormattable> { |
03371ad9 | 317 | const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters |
e8bafea3 | 318 | |
ce33919c | 319 | return sequelizeTypescript.transaction(async t => { |
fbad87b0 C |
320 | const sequelizeOptions = { transaction: t } |
321 | ||
322 | // Save video object in database | |
1ca9f7c3 | 323 | const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag) |
ce33919c | 324 | videoCreated.VideoChannel = videoChannel |
fbad87b0 | 325 | |
3acc5084 C |
326 | if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t) |
327 | if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t) | |
e8bafea3 | 328 | |
5b77537c | 329 | await autoBlacklistVideoIfNeeded({ |
453e83ea | 330 | video: videoCreated, |
5b77537c C |
331 | user, |
332 | notify: false, | |
333 | isRemote: false, | |
334 | isNew: true, | |
335 | transaction: t | |
336 | }) | |
7ccddd7b | 337 | |
1ef65f4c | 338 | await setVideoTags({ video: videoCreated, tags, transaction: t }) |
fbad87b0 C |
339 | |
340 | // Create video import object in database | |
ce33919c C |
341 | const videoImport = await VideoImportModel.create( |
342 | Object.assign({ videoId: videoCreated.id }, videoImportAttributes), | |
343 | sequelizeOptions | |
1ca9f7c3 | 344 | ) as MVideoImportFormattable |
fbad87b0 C |
345 | videoImport.Video = videoCreated |
346 | ||
347 | return videoImport | |
348 | }) | |
fbad87b0 | 349 | } |