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