]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/import.ts
Add peertube import test
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / import.ts
CommitLineData
41fb13c3 1import express from 'express'
1ef65f4c 2import { move, readFile } from 'fs-extra'
41fb13c3
C
3import { decode } from 'magnet-uri'
4import parseTorrent, { Instance } from 'parse-torrent'
1ef65f4c 5import { join } from 'path'
e3c9ea72 6import { isVideoFileExtnameValid } from '@server/helpers/custom-validators/videos'
2539932e 7import { ServerConfigManager } from '@server/lib/server-config-manager'
1ef65f4c 8import { setVideoTags } from '@server/lib/video'
16c016e8 9import { FilteredModelAttributes } from '@server/types'
453e83ea 10import {
0283eaac 11 MChannelAccountDefault,
453e83ea
C
12 MThumbnail,
13 MUser,
1ca9f7c3 14 MVideoAccountDefault,
6302d599 15 MVideoCaption,
96ca24f0 16 MVideoTag,
6302d599 17 MVideoThumbnail,
453e83ea 18 MVideoWithBlacklistLight
26d6bf65 19} from '@server/types/models'
16c016e8 20import { MVideoImportFormattable } from '@server/types/models/video/video-import'
32985a0a 21import { ServerErrorCode, VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
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 34import { JobQueue } from '../../../lib/job-queue/job-queue'
91f8f8db 35import { updateVideoMiniatureFromExisting, updateVideoMiniatureFromUrl } from '../../../lib/thumbnail'
1ef65f4c
C
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
76148b27
RK
146 return res.fail({
147 message: 'Cannot fetch remote information of this URL.',
148 data: {
149 targetUrl
150 }
151 })
fbad87b0
C
152 }
153
e8bafea3 154 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
ce33919c 155
b1770a0a 156 // Process video thumbnail from request.files
6302d599 157 let thumbnailModel = await processThumbnail(req, video)
b1770a0a
K
158
159 // Process video thumbnail from url if processing from request.files failed
86ad0cde 160 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
b1770a0a
K
161 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
162 }
163
b1770a0a 164 // Process video preview from request.files
6302d599 165 let previewModel = await processPreview(req, video)
b1770a0a
K
166
167 // Process video preview from url if processing from request.files failed
86ad0cde 168 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
b1770a0a
K
169 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
170 }
ce33919c 171
e8bafea3 172 const videoImport = await insertIntoDB({
03371ad9 173 video,
e8bafea3
C
174 thumbnailModel,
175 previewModel,
176 videoChannel: res.locals.videoChannel,
c158a5fa
C
177 tags: body.tags || youtubeDLInfo.tags,
178 user,
179 videoImportAttributes: {
180 targetUrl,
181 state: VideoImportState.PENDING,
182 userId: user.id
183 }
e8bafea3 184 })
ce33919c 185
50ad0a1c 186 // Get video subtitles
c158a5fa 187 await processYoutubeSubtitles(youtubeDL, targetUrl, video.id)
50ad0a1c 188
e3c9ea72
C
189 let fileExt = `.${youtubeDLInfo.ext}`
190 if (!isVideoFileExtnameValid(fileExt)) fileExt = '.mp4'
191
ce33919c
C
192 // Create job to import the video
193 const payload = {
194 type: 'youtube-dl' as 'youtube-dl',
195 videoImportId: videoImport.id,
e3c9ea72 196 fileExt
ce33919c 197 }
a1587156 198 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
ce33919c 199
993cef4b 200 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
ce33919c
C
201
202 return res.json(videoImport.toFormattedJSON()).end()
203}
204
6302d599 205function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): MVideoThumbnail {
fbad87b0 206 const videoData = {
ce33919c 207 name: body.name || importData.name || 'Unknown name',
fbad87b0 208 remote: false,
ce33919c
C
209 category: body.category || importData.category,
210 licence: body.licence || importData.licence,
86ad0cde 211 language: body.language || importData.language,
3155c860
C
212 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
213 downloadEnabled: body.downloadEnabled !== false,
fbad87b0
C
214 waitTranscoding: body.waitTranscoding || false,
215 state: VideoState.TO_IMPORT,
ce33919c
C
216 nsfw: body.nsfw || importData.nsfw || false,
217 description: body.description || importData.description,
fbad87b0
C
218 support: body.support || null,
219 privacy: body.privacy || VideoPrivacy.PRIVATE,
220 duration: 0, // duration will be set by the import job
4e553a41 221 channelId: channelId,
16c016e8
C
222 originallyPublishedAt: body.originallyPublishedAt
223 ? new Date(body.originallyPublishedAt)
224 : importData.originallyPublishedAt
fbad87b0
C
225 }
226 const video = new VideoModel(videoData)
de94ac86 227 video.url = getLocalVideoActivityPubUrl(video)
fbad87b0 228
ce33919c
C
229 return video
230}
231
6302d599 232async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
5d08a6a7 233 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
fbad87b0 234 if (thumbnailField) {
a1587156 235 const thumbnailPhysicalFile = thumbnailField[0]
ce33919c 236
91f8f8db 237 return updateVideoMiniatureFromExisting({
1ef65f4c
C
238 inputPath: thumbnailPhysicalFile.path,
239 video,
240 type: ThumbnailType.MINIATURE,
241 automaticallyGenerated: false
242 })
fbad87b0
C
243 }
244
e8bafea3 245 return undefined
ce33919c
C
246}
247
6302d599 248async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
5d08a6a7 249 const previewField = req.files ? req.files['previewfile'] : undefined
fbad87b0
C
250 if (previewField) {
251 const previewPhysicalFile = previewField[0]
ce33919c 252
91f8f8db 253 return updateVideoMiniatureFromExisting({
1ef65f4c
C
254 inputPath: previewPhysicalFile.path,
255 video,
256 type: ThumbnailType.PREVIEW,
257 automaticallyGenerated: false
258 })
fbad87b0
C
259 }
260
e8bafea3 261 return undefined
ce33919c
C
262}
263
6302d599 264async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
b1770a0a 265 try {
91f8f8db 266 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
b1770a0a
K
267 } catch (err) {
268 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
269 return undefined
270 }
271}
272
6302d599 273async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
b1770a0a 274 try {
91f8f8db 275 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
b1770a0a
K
276 } catch (err) {
277 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
278 return undefined
279 }
280}
281
a35a2279 282async function insertIntoDB (parameters: {
6302d599 283 video: MVideoThumbnail
a1587156
C
284 thumbnailModel: MThumbnail
285 previewModel: MThumbnail
286 videoChannel: MChannelAccountDefault
287 tags: string[]
16c016e8 288 videoImportAttributes: FilteredModelAttributes<VideoImportModel>
453e83ea 289 user: MUser
b49f22d8 290}): Promise<MVideoImportFormattable> {
03371ad9 291 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
e8bafea3 292
a35a2279 293 const videoImport = await sequelizeTypescript.transaction(async t => {
fbad87b0
C
294 const sequelizeOptions = { transaction: t }
295
296 // Save video object in database
1ca9f7c3 297 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
ce33919c 298 videoCreated.VideoChannel = videoChannel
fbad87b0 299
3acc5084
C
300 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
301 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 302
5b77537c 303 await autoBlacklistVideoIfNeeded({
453e83ea 304 video: videoCreated,
5b77537c
C
305 user,
306 notify: false,
307 isRemote: false,
308 isNew: true,
309 transaction: t
310 })
7ccddd7b 311
1ef65f4c 312 await setVideoTags({ video: videoCreated, tags, transaction: t })
fbad87b0
C
313
314 // Create video import object in database
ce33919c
C
315 const videoImport = await VideoImportModel.create(
316 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
317 sequelizeOptions
1ca9f7c3 318 ) as MVideoImportFormattable
fbad87b0
C
319 videoImport.Video = videoCreated
320
321 return videoImport
322 })
a35a2279
C
323
324 return videoImport
fbad87b0 325}
c158a5fa
C
326
327async 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)
41fb13c3 336 const parsedTorrent = parseTorrent(buf) as Instance
c158a5fa
C
337
338 if (parsedTorrent.files.length !== 1) {
339 cleanUpReqFiles(req)
340
76148b27 341 res.fail({
3866ea02 342 type: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
76148b27
RK
343 message: 'Torrents with only 1 file are supported.'
344 })
c158a5fa
C
345 return undefined
346 }
347
348 return {
349 name: extractNameFromArray(parsedTorrent.name),
350 torrentName
351 }
352}
353
354function processMagnetURI (body: VideoImportCreate) {
355 const magnetUri = body.magnetUri
41fb13c3 356 const parsed = decode(magnetUri)
c158a5fa
C
357
358 return {
359 name: extractNameFromArray(parsed.name),
360 magnetUri
361 }
362}
363
364function extractNameFromArray (name: string | string[]) {
365 return isArray(name) ? name[0] : name
366}
367
368async 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}