]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/import.ts
More robust youtube-dl thumbnail import
[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) {
f82416cc
C
161 try {
162 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
163 } catch (err) {
164 logger.warn('Cannot process thumbnail %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err })
165 }
b1770a0a
K
166 }
167
b1770a0a 168 // Process video preview from request.files
6302d599 169 let previewModel = await processPreview(req, video)
b1770a0a
K
170
171 // Process video preview from url if processing from request.files failed
86ad0cde 172 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
f82416cc
C
173 try {
174 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
175 } catch (err) {
176 logger.warn('Cannot process preview %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err })
177 }
b1770a0a 178 }
ce33919c 179
e8bafea3 180 const videoImport = await insertIntoDB({
03371ad9 181 video,
e8bafea3
C
182 thumbnailModel,
183 previewModel,
184 videoChannel: res.locals.videoChannel,
c158a5fa
C
185 tags: body.tags || youtubeDLInfo.tags,
186 user,
187 videoImportAttributes: {
188 targetUrl,
189 state: VideoImportState.PENDING,
190 userId: user.id
191 }
e8bafea3 192 })
ce33919c 193
50ad0a1c 194 // Get video subtitles
c158a5fa 195 await processYoutubeSubtitles(youtubeDL, targetUrl, video.id)
50ad0a1c 196
e3c9ea72
C
197 let fileExt = `.${youtubeDLInfo.ext}`
198 if (!isVideoFileExtnameValid(fileExt)) fileExt = '.mp4'
199
ce33919c
C
200 // Create job to import the video
201 const payload = {
202 type: 'youtube-dl' as 'youtube-dl',
203 videoImportId: videoImport.id,
e3c9ea72 204 fileExt
ce33919c 205 }
a1587156 206 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
ce33919c 207
993cef4b 208 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
ce33919c
C
209
210 return res.json(videoImport.toFormattedJSON()).end()
211}
212
6302d599 213function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): MVideoThumbnail {
fbad87b0 214 const videoData = {
ce33919c 215 name: body.name || importData.name || 'Unknown name',
fbad87b0 216 remote: false,
ce33919c
C
217 category: body.category || importData.category,
218 licence: body.licence || importData.licence,
86ad0cde 219 language: body.language || importData.language,
3155c860
C
220 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
221 downloadEnabled: body.downloadEnabled !== false,
fbad87b0
C
222 waitTranscoding: body.waitTranscoding || false,
223 state: VideoState.TO_IMPORT,
ce33919c
C
224 nsfw: body.nsfw || importData.nsfw || false,
225 description: body.description || importData.description,
fbad87b0
C
226 support: body.support || null,
227 privacy: body.privacy || VideoPrivacy.PRIVATE,
228 duration: 0, // duration will be set by the import job
4e553a41 229 channelId: channelId,
16c016e8
C
230 originallyPublishedAt: body.originallyPublishedAt
231 ? new Date(body.originallyPublishedAt)
232 : importData.originallyPublishedAt
fbad87b0
C
233 }
234 const video = new VideoModel(videoData)
de94ac86 235 video.url = getLocalVideoActivityPubUrl(video)
fbad87b0 236
ce33919c
C
237 return video
238}
239
6302d599 240async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
5d08a6a7 241 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
fbad87b0 242 if (thumbnailField) {
a1587156 243 const thumbnailPhysicalFile = thumbnailField[0]
ce33919c 244
91f8f8db 245 return updateVideoMiniatureFromExisting({
1ef65f4c
C
246 inputPath: thumbnailPhysicalFile.path,
247 video,
248 type: ThumbnailType.MINIATURE,
249 automaticallyGenerated: false
250 })
fbad87b0
C
251 }
252
e8bafea3 253 return undefined
ce33919c
C
254}
255
6302d599 256async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
5d08a6a7 257 const previewField = req.files ? req.files['previewfile'] : undefined
fbad87b0
C
258 if (previewField) {
259 const previewPhysicalFile = previewField[0]
ce33919c 260
91f8f8db 261 return updateVideoMiniatureFromExisting({
1ef65f4c
C
262 inputPath: previewPhysicalFile.path,
263 video,
264 type: ThumbnailType.PREVIEW,
265 automaticallyGenerated: false
266 })
fbad87b0
C
267 }
268
e8bafea3 269 return undefined
ce33919c
C
270}
271
6302d599 272async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
b1770a0a 273 try {
91f8f8db 274 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
b1770a0a
K
275 } catch (err) {
276 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
277 return undefined
278 }
279}
280
6302d599 281async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
b1770a0a 282 try {
91f8f8db 283 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
b1770a0a
K
284 } catch (err) {
285 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
286 return undefined
287 }
288}
289
a35a2279 290async function insertIntoDB (parameters: {
6302d599 291 video: MVideoThumbnail
a1587156
C
292 thumbnailModel: MThumbnail
293 previewModel: MThumbnail
294 videoChannel: MChannelAccountDefault
295 tags: string[]
16c016e8 296 videoImportAttributes: FilteredModelAttributes<VideoImportModel>
453e83ea 297 user: MUser
b49f22d8 298}): Promise<MVideoImportFormattable> {
03371ad9 299 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
e8bafea3 300
a35a2279 301 const videoImport = await sequelizeTypescript.transaction(async t => {
fbad87b0
C
302 const sequelizeOptions = { transaction: t }
303
304 // Save video object in database
1ca9f7c3 305 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
ce33919c 306 videoCreated.VideoChannel = videoChannel
fbad87b0 307
3acc5084
C
308 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
309 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 310
5b77537c 311 await autoBlacklistVideoIfNeeded({
453e83ea 312 video: videoCreated,
5b77537c
C
313 user,
314 notify: false,
315 isRemote: false,
316 isNew: true,
317 transaction: t
318 })
7ccddd7b 319
1ef65f4c 320 await setVideoTags({ video: videoCreated, tags, transaction: t })
fbad87b0
C
321
322 // Create video import object in database
ce33919c
C
323 const videoImport = await VideoImportModel.create(
324 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
325 sequelizeOptions
1ca9f7c3 326 ) as MVideoImportFormattable
fbad87b0
C
327 videoImport.Video = videoCreated
328
329 return videoImport
330 })
a35a2279
C
331
332 return videoImport
fbad87b0 333}
c158a5fa
C
334
335async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
336 const torrentName = torrentfile.originalname
337
338 // Rename the torrent to a secured name
339 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
340 await move(torrentfile.path, newTorrentPath, { overwrite: true })
341 torrentfile.path = newTorrentPath
342
343 const buf = await readFile(torrentfile.path)
41fb13c3 344 const parsedTorrent = parseTorrent(buf) as Instance
c158a5fa
C
345
346 if (parsedTorrent.files.length !== 1) {
347 cleanUpReqFiles(req)
348
76148b27 349 res.fail({
3866ea02 350 type: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
76148b27
RK
351 message: 'Torrents with only 1 file are supported.'
352 })
c158a5fa
C
353 return undefined
354 }
355
356 return {
357 name: extractNameFromArray(parsedTorrent.name),
358 torrentName
359 }
360}
361
362function processMagnetURI (body: VideoImportCreate) {
363 const magnetUri = body.magnetUri
41fb13c3 364 const parsed = decode(magnetUri)
c158a5fa
C
365
366 return {
367 name: extractNameFromArray(parsed.name),
368 magnetUri
369 }
370}
371
372function extractNameFromArray (name: string | string[]) {
373 return isArray(name) ? name[0] : name
374}
375
376async function processYoutubeSubtitles (youtubeDL: YoutubeDL, targetUrl: string, videoId: number) {
377 try {
378 const subtitles = await youtubeDL.getYoutubeDLSubs()
379
380 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
381
382 for (const subtitle of subtitles) {
383 const videoCaption = new VideoCaptionModel({
384 videoId,
385 language: subtitle.language,
386 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
387 }) as MVideoCaption
388
389 // Move physical file
390 await moveAndProcessCaptionFile(subtitle, videoCaption)
391
392 await sequelizeTypescript.transaction(async t => {
393 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
394 })
395 }
396 } catch (err) {
397 logger.warn('Cannot get video subtitles.', { err })
398 }
399}