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