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