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