]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/import.ts
Correctly fix subtitles import
[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'
8dc8a34e 13import { getVideoActivityPubUrl } from '../../../lib/activitypub/url'
fbad87b0
C
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'
b1770a0a 26import { createVideoMiniatureFromExisting, createVideoMiniatureFromUrl } 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
b1770a0a
K
156 let thumbnailModel: MThumbnail
157
158 // Process video thumbnail from request.files
159 thumbnailModel = await processThumbnail(req, video)
160
161 // Process video thumbnail from url if processing from request.files failed
86ad0cde 162 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
b1770a0a
K
163 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
164 }
165
166 let previewModel: MThumbnail
167
168 // Process video preview from request.files
169 previewModel = await processPreview(req, video)
170
171 // Process video preview from url if processing from request.files failed
86ad0cde 172 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
b1770a0a
K
173 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
174 }
ce33919c
C
175
176 const tags = body.tags || youtubeDLInfo.tags
177 const videoImportAttributes = {
178 targetUrl,
a84b8fa5
C
179 state: VideoImportState.PENDING,
180 userId: user.id
ce33919c 181 }
e8bafea3 182 const videoImport = await insertIntoDB({
03371ad9 183 video,
e8bafea3
C
184 thumbnailModel,
185 previewModel,
186 videoChannel: res.locals.videoChannel,
187 tags,
03371ad9
C
188 videoImportAttributes,
189 user
e8bafea3 190 })
ce33919c 191
50ad0a1c 192 // Get video subtitles
193 try {
194 const subtitles = await getYoutubeDLSubs(targetUrl)
195
652c6416
C
196 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
197
50ad0a1c 198 for (const subtitle of subtitles) {
199 const videoCaption = new VideoCaptionModel({
200 videoId: video.id,
201 language: subtitle.language
202 }) as MVideoCaptionVideo
203 videoCaption.Video = video
204
205 // Move physical file
206 await moveAndProcessCaptionFile(subtitle, videoCaption)
207
208 await sequelizeTypescript.transaction(async t => {
209 await VideoCaptionModel.insertOrReplaceLanguage(video.id, subtitle.language, null, t)
210 })
211 }
212 } catch (err) {
213 logger.warn('Cannot get video subtitles.', { err })
214 }
215
ce33919c
C
216 // Create job to import the video
217 const payload = {
218 type: 'youtube-dl' as 'youtube-dl',
219 videoImportId: videoImport.id,
b1770a0a
K
220 generateThumbnail: !thumbnailModel,
221 generatePreview: !previewModel,
d57d1d83
C
222 fileExt: youtubeDLInfo.fileExt
223 ? `.${youtubeDLInfo.fileExt}`
224 : '.mp4'
ce33919c 225 }
a1587156 226 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
ce33919c 227
993cef4b 228 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
ce33919c
C
229
230 return res.json(videoImport.toFormattedJSON()).end()
231}
232
e8bafea3 233function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) {
fbad87b0 234 const videoData = {
ce33919c 235 name: body.name || importData.name || 'Unknown name',
fbad87b0 236 remote: false,
ce33919c
C
237 category: body.category || importData.category,
238 licence: body.licence || importData.licence,
86ad0cde 239 language: body.language || importData.language,
3155c860
C
240 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
241 downloadEnabled: body.downloadEnabled !== false,
fbad87b0
C
242 waitTranscoding: body.waitTranscoding || false,
243 state: VideoState.TO_IMPORT,
ce33919c
C
244 nsfw: body.nsfw || importData.nsfw || false,
245 description: body.description || importData.description,
fbad87b0
C
246 support: body.support || null,
247 privacy: body.privacy || VideoPrivacy.PRIVATE,
248 duration: 0, // duration will be set by the import job
4e553a41 249 channelId: channelId,
8a86e5dc 250 originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt
fbad87b0
C
251 }
252 const video = new VideoModel(videoData)
253 video.url = getVideoActivityPubUrl(video)
254
ce33919c
C
255 return video
256}
257
258async function processThumbnail (req: express.Request, video: VideoModel) {
5d08a6a7 259 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
fbad87b0 260 if (thumbnailField) {
a1587156 261 const thumbnailPhysicalFile = thumbnailField[0]
ce33919c 262
65af03a2 263 return createVideoMiniatureFromExisting(thumbnailPhysicalFile.path, video, ThumbnailType.MINIATURE, false)
fbad87b0
C
264 }
265
e8bafea3 266 return undefined
ce33919c
C
267}
268
269async function processPreview (req: express.Request, video: VideoModel) {
5d08a6a7 270 const previewField = req.files ? req.files['previewfile'] : undefined
fbad87b0
C
271 if (previewField) {
272 const previewPhysicalFile = previewField[0]
ce33919c 273
65af03a2 274 return createVideoMiniatureFromExisting(previewPhysicalFile.path, video, ThumbnailType.PREVIEW, false)
fbad87b0
C
275 }
276
e8bafea3 277 return undefined
ce33919c
C
278}
279
b1770a0a
K
280async function processThumbnailFromUrl (url: string, video: VideoModel) {
281 try {
282 return createVideoMiniatureFromUrl(url, video, ThumbnailType.MINIATURE)
283 } catch (err) {
284 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
285 return undefined
286 }
287}
288
289async function processPreviewFromUrl (url: string, video: VideoModel) {
290 try {
291 return createVideoMiniatureFromUrl(url, video, ThumbnailType.PREVIEW)
292 } catch (err) {
293 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
294 return undefined
295 }
296}
297
e8bafea3 298function insertIntoDB (parameters: {
a1587156
C
299 video: MVideoThumbnailAccountDefault
300 thumbnailModel: MThumbnail
301 previewModel: MThumbnail
302 videoChannel: MChannelAccountDefault
303 tags: string[]
304 videoImportAttributes: Partial<MVideoImport>
453e83ea 305 user: MUser
1ca9f7c3 306}): Bluebird<MVideoImportFormattable> {
03371ad9 307 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
e8bafea3 308
ce33919c 309 return sequelizeTypescript.transaction(async t => {
fbad87b0
C
310 const sequelizeOptions = { transaction: t }
311
312 // Save video object in database
1ca9f7c3 313 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
ce33919c 314 videoCreated.VideoChannel = videoChannel
fbad87b0 315
3acc5084
C
316 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
317 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 318
5b77537c 319 await autoBlacklistVideoIfNeeded({
453e83ea 320 video: videoCreated,
5b77537c
C
321 user,
322 notify: false,
323 isRemote: false,
324 isNew: true,
325 transaction: t
326 })
7ccddd7b 327
fbad87b0 328 // Set tags to the video
3e17515e 329 if (tags) {
590fb506 330 const tagInstances = await TagModel.findOrCreateTags(tags, t)
fbad87b0
C
331
332 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
96ca24f0
C
333 videoCreated.Tags = tagInstances
334 } else {
335 videoCreated.Tags = []
fbad87b0
C
336 }
337
338 // Create video import object in database
ce33919c
C
339 const videoImport = await VideoImportModel.create(
340 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
341 sequelizeOptions
1ca9f7c3 342 ) as MVideoImportFormattable
fbad87b0
C
343 videoImport.Video = videoCreated
344
345 return videoImport
346 })
fbad87b0 347}