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