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