]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/import.ts
Increase API rate limit
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / import.ts
CommitLineData
fbad87b0 1import * as express from 'express'
990b6a0b 2import * as magnetUtil from 'magnet-uri'
993cef4b 3import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
7e5f9f00 4import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
e8bafea3 5import { MIMETYPES } from '../../../initializers/constants'
50ad0a1c 6import { getYoutubeDLInfo, YoutubeDLInfo, getYoutubeDLSubs } from '../../../helpers/youtube-dl'
fbad87b0
C
7import { createReqFiles } from '../../../helpers/express-utils'
8import { logger } from '../../../helpers/logger'
9import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
10import { VideoModel } from '../../../models/video/video'
50ad0a1c 11import { VideoCaptionModel } from '../../../models/video/video-caption'
12import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils'
fbad87b0
C
13import { getVideoActivityPubUrl } from '../../../lib/activitypub'
14import { TagModel } from '../../../models/video/tag'
15import { VideoImportModel } from '../../../models/video/video-import'
16import { JobQueue } from '../../../lib/job-queue/job-queue'
fbad87b0 17import { join } from 'path'
ce33919c 18import { isArray } from '../../../helpers/custom-validators/misc'
ce33919c 19import * as Bluebird from 'bluebird'
990b6a0b 20import * as parseTorrent from 'parse-torrent'
990b6a0b 21import { getSecureTorrentName } from '../../../helpers/utils'
6dd9de95 22import { move, readFile } from 'fs-extra'
7ccddd7b 23import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
6dd9de95 24import { CONFIG } from '../../../initializers/config'
74dc3bca 25import { sequelizeTypescript } from '../../../initializers/database'
3acc5084 26import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail'
e8bafea3 27import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
453e83ea 28import {
0283eaac 29 MChannelAccountDefault,
453e83ea
C
30 MThumbnail,
31 MUser,
1ca9f7c3 32 MVideoAccountDefault,
50ad0a1c 33 MVideoCaptionVideo,
96ca24f0 34 MVideoTag,
453e83ea
C
35 MVideoThumbnailAccountDefault,
36 MVideoWithBlacklistLight
37} from '@server/typings/models'
1ca9f7c3 38import { MVideoImport, MVideoImportFormattable } from '@server/typings/models/video/video-import'
fbad87b0
C
39
40const auditLogger = auditLoggerFactory('video-imports')
41const videoImportsRouter = express.Router()
42
43const reqVideoFileImport = createReqFiles(
990b6a0b 44 [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
14e2014a 45 Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
fbad87b0 46 {
6040f87d
C
47 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
48 previewfile: CONFIG.STORAGE.TMP_DIR,
49 torrentfile: CONFIG.STORAGE.TMP_DIR
fbad87b0
C
50 }
51)
52
53videoImportsRouter.post('/imports',
54 authenticate,
55 reqVideoFileImport,
56 asyncMiddleware(videoImportAddValidator),
57 asyncRetryTransactionMiddleware(addVideoImport)
58)
59
fbad87b0
C
60// ---------------------------------------------------------------------------
61
62export {
63 videoImportsRouter
64}
65
66// ---------------------------------------------------------------------------
67
ce33919c
C
68function addVideoImport (req: express.Request, res: express.Response) {
69 if (req.body.targetUrl) return addYoutubeDLImport(req, res)
70
a84b8fa5 71 const file = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined
990b6a0b 72 if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
ce33919c
C
73}
74
990b6a0b 75async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
ce33919c 76 const body: VideoImportCreate = req.body
a84b8fa5 77 const user = res.locals.oauth.token.User
ce33919c 78
990b6a0b
C
79 let videoName: string
80 let torrentName: string
81 let magnetUri: string
82
83 if (torrentfile) {
84 torrentName = torrentfile.originalname
85
86 // Rename the torrent to a secured name
87 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
f481c4f9 88 await move(torrentfile.path, newTorrentPath)
990b6a0b
C
89 torrentfile.path = newTorrentPath
90
62689b94 91 const buf = await readFile(torrentfile.path)
990b6a0b
C
92 const parsedTorrent = parseTorrent(buf)
93
a1587156 94 videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name as string
990b6a0b
C
95 } else {
96 magnetUri = body.magnetUri
97
98 const parsed = magnetUtil.decode(magnetUri)
a1587156 99 videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string
990b6a0b 100 }
ce33919c 101
e8bafea3 102 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
ce33919c 103
e8bafea3
C
104 const thumbnailModel = await processThumbnail(req, video)
105 const previewModel = await processPreview(req, video)
ce33919c 106
3e17515e 107 const tags = body.tags || undefined
ce33919c
C
108 const videoImportAttributes = {
109 magnetUri,
990b6a0b 110 torrentName,
a84b8fa5
C
111 state: VideoImportState.PENDING,
112 userId: user.id
ce33919c 113 }
e8bafea3
C
114 const videoImport = await insertIntoDB({
115 video,
116 thumbnailModel,
117 previewModel,
118 videoChannel: res.locals.videoChannel,
119 tags,
03371ad9
C
120 videoImportAttributes,
121 user
e8bafea3 122 })
ce33919c
C
123
124 // Create job to import the video
125 const payload = {
990b6a0b 126 type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
ce33919c
C
127 videoImportId: videoImport.id,
128 magnetUri
129 }
a1587156 130 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
ce33919c 131
993cef4b 132 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
ce33919c
C
133
134 return res.json(videoImport.toFormattedJSON()).end()
135}
136
137async function addYoutubeDLImport (req: express.Request, res: express.Response) {
fbad87b0
C
138 const body: VideoImportCreate = req.body
139 const targetUrl = body.targetUrl
a84b8fa5 140 const user = res.locals.oauth.token.User
fbad87b0 141
50ad0a1c 142 // Get video infos
fbad87b0
C
143 let youtubeDLInfo: YoutubeDLInfo
144 try {
145 youtubeDLInfo = await getYoutubeDLInfo(targetUrl)
146 } catch (err) {
147 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
148
149 return res.status(400).json({
150 error: 'Cannot fetch remote information of this URL.'
151 }).end()
152 }
153
e8bafea3 154 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
ce33919c 155
e8bafea3
C
156 const thumbnailModel = await processThumbnail(req, video)
157 const previewModel = await processPreview(req, video)
ce33919c
C
158
159 const tags = body.tags || youtubeDLInfo.tags
160 const videoImportAttributes = {
161 targetUrl,
a84b8fa5
C
162 state: VideoImportState.PENDING,
163 userId: user.id
ce33919c 164 }
e8bafea3 165 const videoImport = await insertIntoDB({
03371ad9 166 video,
e8bafea3
C
167 thumbnailModel,
168 previewModel,
169 videoChannel: res.locals.videoChannel,
170 tags,
03371ad9
C
171 videoImportAttributes,
172 user
e8bafea3 173 })
ce33919c 174
50ad0a1c 175 // Get video subtitles
176 try {
177 const subtitles = await getYoutubeDLSubs(targetUrl)
178
652c6416
C
179 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
180
50ad0a1c 181 for (const subtitle of subtitles) {
182 const videoCaption = new VideoCaptionModel({
183 videoId: video.id,
184 language: subtitle.language
185 }) as MVideoCaptionVideo
186 videoCaption.Video = video
187
188 // Move physical file
189 await moveAndProcessCaptionFile(subtitle, videoCaption)
190
191 await sequelizeTypescript.transaction(async t => {
192 await VideoCaptionModel.insertOrReplaceLanguage(video.id, subtitle.language, null, t)
193 })
194 }
195 } catch (err) {
196 logger.warn('Cannot get video subtitles.', { err })
197 }
198
ce33919c
C
199 // Create job to import the video
200 const payload = {
201 type: 'youtube-dl' as 'youtube-dl',
202 videoImportId: videoImport.id,
203 thumbnailUrl: youtubeDLInfo.thumbnailUrl,
e8bafea3 204 downloadThumbnail: !thumbnailModel,
d57d1d83
C
205 downloadPreview: !previewModel,
206 fileExt: youtubeDLInfo.fileExt
207 ? `.${youtubeDLInfo.fileExt}`
208 : '.mp4'
ce33919c 209 }
a1587156 210 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
ce33919c 211
993cef4b 212 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
ce33919c
C
213
214 return res.json(videoImport.toFormattedJSON()).end()
215}
216
e8bafea3 217function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) {
fbad87b0 218 const videoData = {
ce33919c 219 name: body.name || importData.name || 'Unknown name',
fbad87b0 220 remote: false,
ce33919c
C
221 category: body.category || importData.category,
222 licence: body.licence || importData.licence,
590fb506 223 language: body.language || undefined,
3155c860
C
224 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
225 downloadEnabled: body.downloadEnabled !== false,
fbad87b0
C
226 waitTranscoding: body.waitTranscoding || false,
227 state: VideoState.TO_IMPORT,
ce33919c
C
228 nsfw: body.nsfw || importData.nsfw || false,
229 description: body.description || importData.description,
fbad87b0
C
230 support: body.support || null,
231 privacy: body.privacy || VideoPrivacy.PRIVATE,
232 duration: 0, // duration will be set by the import job
4e553a41
AM
233 channelId: channelId,
234 originallyPublishedAt: importData.originallyPublishedAt
fbad87b0
C
235 }
236 const video = new VideoModel(videoData)
237 video.url = getVideoActivityPubUrl(video)
238
ce33919c
C
239 return video
240}
241
242async function processThumbnail (req: express.Request, video: VideoModel) {
5d08a6a7 243 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
fbad87b0 244 if (thumbnailField) {
a1587156 245 const thumbnailPhysicalFile = thumbnailField[0]
ce33919c 246
65af03a2 247 return createVideoMiniatureFromExisting(thumbnailPhysicalFile.path, video, ThumbnailType.MINIATURE, false)
fbad87b0
C
248 }
249
e8bafea3 250 return undefined
ce33919c
C
251}
252
253async function processPreview (req: express.Request, video: VideoModel) {
5d08a6a7 254 const previewField = req.files ? req.files['previewfile'] : undefined
fbad87b0
C
255 if (previewField) {
256 const previewPhysicalFile = previewField[0]
ce33919c 257
65af03a2 258 return createVideoMiniatureFromExisting(previewPhysicalFile.path, video, ThumbnailType.PREVIEW, false)
fbad87b0
C
259 }
260
e8bafea3 261 return undefined
ce33919c
C
262}
263
e8bafea3 264function insertIntoDB (parameters: {
a1587156
C
265 video: MVideoThumbnailAccountDefault
266 thumbnailModel: MThumbnail
267 previewModel: MThumbnail
268 videoChannel: MChannelAccountDefault
269 tags: string[]
270 videoImportAttributes: Partial<MVideoImport>
453e83ea 271 user: MUser
1ca9f7c3 272}): Bluebird<MVideoImportFormattable> {
03371ad9 273 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
e8bafea3 274
ce33919c 275 return sequelizeTypescript.transaction(async t => {
fbad87b0
C
276 const sequelizeOptions = { transaction: t }
277
278 // Save video object in database
1ca9f7c3 279 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
ce33919c 280 videoCreated.VideoChannel = videoChannel
fbad87b0 281
3acc5084
C
282 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
283 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 284
5b77537c 285 await autoBlacklistVideoIfNeeded({
453e83ea 286 video: videoCreated,
5b77537c
C
287 user,
288 notify: false,
289 isRemote: false,
290 isNew: true,
291 transaction: t
292 })
7ccddd7b 293
fbad87b0 294 // Set tags to the video
3e17515e 295 if (tags) {
590fb506 296 const tagInstances = await TagModel.findOrCreateTags(tags, t)
fbad87b0
C
297
298 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
96ca24f0
C
299 videoCreated.Tags = tagInstances
300 } else {
301 videoCreated.Tags = []
fbad87b0
C
302 }
303
304 // Create video import object in database
ce33919c
C
305 const videoImport = await VideoImportModel.create(
306 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
307 sequelizeOptions
1ca9f7c3 308 ) as MVideoImportFormattable
fbad87b0
C
309 videoImport.Video = videoCreated
310
311 return videoImport
312 })
fbad87b0 313}