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