]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/import.ts
Add peertube import test
[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 { isVideoFileExtnameValid } from '@server/helpers/custom-validators/videos'
7 import { ServerConfigManager } from '@server/lib/server-config-manager'
8 import { setVideoTags } from '@server/lib/video'
9 import { FilteredModelAttributes } from '@server/types'
10 import {
11 MChannelAccountDefault,
12 MThumbnail,
13 MUser,
14 MVideoAccountDefault,
15 MVideoCaption,
16 MVideoTag,
17 MVideoThumbnail,
18 MVideoWithBlacklistLight
19 } from '@server/types/models'
20 import { MVideoImportFormattable } from '@server/types/models/video/video-import'
21 import { ServerErrorCode, VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
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 { updateVideoMiniatureFromExisting, updateVideoMiniatureFromUrl } 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.fail({
147 message: 'Cannot fetch remote information of this URL.',
148 data: {
149 targetUrl
150 }
151 })
152 }
153
154 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
155
156 // Process video thumbnail from request.files
157 let thumbnailModel = await processThumbnail(req, video)
158
159 // Process video thumbnail from url if processing from request.files failed
160 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
161 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
162 }
163
164 // Process video preview from request.files
165 let previewModel = await processPreview(req, video)
166
167 // Process video preview from url if processing from request.files failed
168 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
169 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
170 }
171
172 const videoImport = await insertIntoDB({
173 video,
174 thumbnailModel,
175 previewModel,
176 videoChannel: res.locals.videoChannel,
177 tags: body.tags || youtubeDLInfo.tags,
178 user,
179 videoImportAttributes: {
180 targetUrl,
181 state: VideoImportState.PENDING,
182 userId: user.id
183 }
184 })
185
186 // Get video subtitles
187 await processYoutubeSubtitles(youtubeDL, targetUrl, video.id)
188
189 let fileExt = `.${youtubeDLInfo.ext}`
190 if (!isVideoFileExtnameValid(fileExt)) fileExt = '.mp4'
191
192 // Create job to import the video
193 const payload = {
194 type: 'youtube-dl' as 'youtube-dl',
195 videoImportId: videoImport.id,
196 fileExt
197 }
198 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
199
200 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
201
202 return res.json(videoImport.toFormattedJSON()).end()
203 }
204
205 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): MVideoThumbnail {
206 const videoData = {
207 name: body.name || importData.name || 'Unknown name',
208 remote: false,
209 category: body.category || importData.category,
210 licence: body.licence || importData.licence,
211 language: body.language || importData.language,
212 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
213 downloadEnabled: body.downloadEnabled !== false,
214 waitTranscoding: body.waitTranscoding || false,
215 state: VideoState.TO_IMPORT,
216 nsfw: body.nsfw || importData.nsfw || false,
217 description: body.description || importData.description,
218 support: body.support || null,
219 privacy: body.privacy || VideoPrivacy.PRIVATE,
220 duration: 0, // duration will be set by the import job
221 channelId: channelId,
222 originallyPublishedAt: body.originallyPublishedAt
223 ? new Date(body.originallyPublishedAt)
224 : importData.originallyPublishedAt
225 }
226 const video = new VideoModel(videoData)
227 video.url = getLocalVideoActivityPubUrl(video)
228
229 return video
230 }
231
232 async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
233 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
234 if (thumbnailField) {
235 const thumbnailPhysicalFile = thumbnailField[0]
236
237 return updateVideoMiniatureFromExisting({
238 inputPath: thumbnailPhysicalFile.path,
239 video,
240 type: ThumbnailType.MINIATURE,
241 automaticallyGenerated: false
242 })
243 }
244
245 return undefined
246 }
247
248 async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
249 const previewField = req.files ? req.files['previewfile'] : undefined
250 if (previewField) {
251 const previewPhysicalFile = previewField[0]
252
253 return updateVideoMiniatureFromExisting({
254 inputPath: previewPhysicalFile.path,
255 video,
256 type: ThumbnailType.PREVIEW,
257 automaticallyGenerated: false
258 })
259 }
260
261 return undefined
262 }
263
264 async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
265 try {
266 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
267 } catch (err) {
268 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
269 return undefined
270 }
271 }
272
273 async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
274 try {
275 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
276 } catch (err) {
277 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
278 return undefined
279 }
280 }
281
282 async function insertIntoDB (parameters: {
283 video: MVideoThumbnail
284 thumbnailModel: MThumbnail
285 previewModel: MThumbnail
286 videoChannel: MChannelAccountDefault
287 tags: string[]
288 videoImportAttributes: FilteredModelAttributes<VideoImportModel>
289 user: MUser
290 }): Promise<MVideoImportFormattable> {
291 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
292
293 const videoImport = await sequelizeTypescript.transaction(async t => {
294 const sequelizeOptions = { transaction: t }
295
296 // Save video object in database
297 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
298 videoCreated.VideoChannel = videoChannel
299
300 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
301 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
302
303 await autoBlacklistVideoIfNeeded({
304 video: videoCreated,
305 user,
306 notify: false,
307 isRemote: false,
308 isNew: true,
309 transaction: t
310 })
311
312 await setVideoTags({ video: videoCreated, tags, transaction: t })
313
314 // Create video import object in database
315 const videoImport = await VideoImportModel.create(
316 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
317 sequelizeOptions
318 ) as MVideoImportFormattable
319 videoImport.Video = videoCreated
320
321 return videoImport
322 })
323
324 return videoImport
325 }
326
327 async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
328 const torrentName = torrentfile.originalname
329
330 // Rename the torrent to a secured name
331 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
332 await move(torrentfile.path, newTorrentPath, { overwrite: true })
333 torrentfile.path = newTorrentPath
334
335 const buf = await readFile(torrentfile.path)
336 const parsedTorrent = parseTorrent(buf) as Instance
337
338 if (parsedTorrent.files.length !== 1) {
339 cleanUpReqFiles(req)
340
341 res.fail({
342 type: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
343 message: 'Torrents with only 1 file are supported.'
344 })
345 return undefined
346 }
347
348 return {
349 name: extractNameFromArray(parsedTorrent.name),
350 torrentName
351 }
352 }
353
354 function processMagnetURI (body: VideoImportCreate) {
355 const magnetUri = body.magnetUri
356 const parsed = decode(magnetUri)
357
358 return {
359 name: extractNameFromArray(parsed.name),
360 magnetUri
361 }
362 }
363
364 function extractNameFromArray (name: string | string[]) {
365 return isArray(name) ? name[0] : name
366 }
367
368 async function processYoutubeSubtitles (youtubeDL: YoutubeDL, targetUrl: string, videoId: number) {
369 try {
370 const subtitles = await youtubeDL.getYoutubeDLSubs()
371
372 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
373
374 for (const subtitle of subtitles) {
375 const videoCaption = new VideoCaptionModel({
376 videoId,
377 language: subtitle.language,
378 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
379 }) as MVideoCaption
380
381 // Move physical file
382 await moveAndProcessCaptionFile(subtitle, videoCaption)
383
384 await sequelizeTypescript.transaction(async t => {
385 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
386 })
387 }
388 } catch (err) {
389 logger.warn('Cannot get video subtitles.', { err })
390 }
391 }