]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/import.ts
advertise live streaming as a feature in readme
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / import.ts
CommitLineData
fbad87b0 1import * as express from 'express'
1ef65f4c 2import { move, readFile } from 'fs-extra'
990b6a0b 3import * as magnetUtil from 'magnet-uri'
990b6a0b 4import * as parseTorrent from 'parse-torrent'
1ef65f4c
C
5import { join } from 'path'
6import { setVideoTags } from '@server/lib/video'
453e83ea 7import {
0283eaac 8 MChannelAccountDefault,
453e83ea
C
9 MThumbnail,
10 MUser,
1ca9f7c3 11 MVideoAccountDefault,
50ad0a1c 12 MVideoCaptionVideo,
96ca24f0 13 MVideoTag,
453e83ea
C
14 MVideoThumbnailAccountDefault,
15 MVideoWithBlacklistLight
26d6bf65
C
16} from '@server/types/models'
17import { MVideoImport, MVideoImportFormattable } from '@server/types/models/video/video-import'
1ef65f4c 18import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
b49f22d8 19import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
1ef65f4c
C
20import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
21import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
22import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils'
23import { isArray } from '../../../helpers/custom-validators/misc'
24import { createReqFiles } from '../../../helpers/express-utils'
25import { logger } from '../../../helpers/logger'
26import { getSecureTorrentName } from '../../../helpers/utils'
27import { getYoutubeDLInfo, getYoutubeDLSubs, YoutubeDLInfo } from '../../../helpers/youtube-dl'
28import { CONFIG } from '../../../initializers/config'
29import { MIMETYPES } from '../../../initializers/constants'
30import { sequelizeTypescript } from '../../../initializers/database'
de94ac86 31import { getLocalVideoActivityPubUrl } from '../../../lib/activitypub/url'
1ef65f4c
C
32import { JobQueue } from '../../../lib/job-queue/job-queue'
33import { createVideoMiniatureFromExisting, createVideoMiniatureFromUrl } from '../../../lib/thumbnail'
34import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
35import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
36import { VideoModel } from '../../../models/video/video'
37import { VideoCaptionModel } from '../../../models/video/video-caption'
38import { VideoImportModel } from '../../../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
faa9d434 71 const file = req.files?.['torrentfile']?.[0]
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
454c20fa
RK
149 return res.status(HttpStatusCode.BAD_REQUEST_400)
150 .json({
151 error: 'Cannot fetch remote information of this URL.'
152 })
fbad87b0
C
153 }
154
e8bafea3 155 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
ce33919c 156
b1770a0a
K
157 let thumbnailModel: MThumbnail
158
159 // Process video thumbnail from request.files
160 thumbnailModel = await processThumbnail(req, video)
161
162 // Process video thumbnail from url if processing from request.files failed
86ad0cde 163 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
b1770a0a
K
164 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
165 }
166
167 let previewModel: MThumbnail
168
169 // Process video preview from request.files
170 previewModel = await processPreview(req, video)
171
172 // Process video preview from url if processing from request.files failed
86ad0cde 173 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
b1770a0a
K
174 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
175 }
ce33919c
C
176
177 const tags = body.tags || youtubeDLInfo.tags
178 const videoImportAttributes = {
179 targetUrl,
a84b8fa5
C
180 state: VideoImportState.PENDING,
181 userId: user.id
ce33919c 182 }
e8bafea3 183 const videoImport = await insertIntoDB({
03371ad9 184 video,
e8bafea3
C
185 thumbnailModel,
186 previewModel,
187 videoChannel: res.locals.videoChannel,
188 tags,
03371ad9
C
189 videoImportAttributes,
190 user
e8bafea3 191 })
ce33919c 192
50ad0a1c 193 // Get video subtitles
194 try {
195 const subtitles = await getYoutubeDLSubs(targetUrl)
196
652c6416
C
197 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
198
50ad0a1c 199 for (const subtitle of subtitles) {
200 const videoCaption = new VideoCaptionModel({
201 videoId: video.id,
202 language: subtitle.language
203 }) as MVideoCaptionVideo
204 videoCaption.Video = video
205
206 // Move physical file
207 await moveAndProcessCaptionFile(subtitle, videoCaption)
208
209 await sequelizeTypescript.transaction(async t => {
210 await VideoCaptionModel.insertOrReplaceLanguage(video.id, subtitle.language, null, t)
211 })
212 }
213 } catch (err) {
214 logger.warn('Cannot get video subtitles.', { err })
215 }
216
ce33919c
C
217 // Create job to import the video
218 const payload = {
219 type: 'youtube-dl' as 'youtube-dl',
220 videoImportId: videoImport.id,
b1770a0a
K
221 generateThumbnail: !thumbnailModel,
222 generatePreview: !previewModel,
805b8619 223 fileExt: `.${youtubeDLInfo.ext || 'mp4'}`
ce33919c 224 }
a1587156 225 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
ce33919c 226
993cef4b 227 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
ce33919c
C
228
229 return res.json(videoImport.toFormattedJSON()).end()
230}
231
e8bafea3 232function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) {
fbad87b0 233 const videoData = {
ce33919c 234 name: body.name || importData.name || 'Unknown name',
fbad87b0 235 remote: false,
ce33919c
C
236 category: body.category || importData.category,
237 licence: body.licence || importData.licence,
86ad0cde 238 language: body.language || importData.language,
3155c860
C
239 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
240 downloadEnabled: body.downloadEnabled !== false,
fbad87b0
C
241 waitTranscoding: body.waitTranscoding || false,
242 state: VideoState.TO_IMPORT,
ce33919c
C
243 nsfw: body.nsfw || importData.nsfw || false,
244 description: body.description || importData.description,
fbad87b0
C
245 support: body.support || null,
246 privacy: body.privacy || VideoPrivacy.PRIVATE,
247 duration: 0, // duration will be set by the import job
4e553a41 248 channelId: channelId,
8a86e5dc 249 originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt
fbad87b0
C
250 }
251 const video = new VideoModel(videoData)
de94ac86 252 video.url = getLocalVideoActivityPubUrl(video)
fbad87b0 253
ce33919c
C
254 return video
255}
256
257async function processThumbnail (req: express.Request, video: VideoModel) {
5d08a6a7 258 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
fbad87b0 259 if (thumbnailField) {
a1587156 260 const thumbnailPhysicalFile = thumbnailField[0]
ce33919c 261
1ef65f4c
C
262 return createVideoMiniatureFromExisting({
263 inputPath: thumbnailPhysicalFile.path,
264 video,
265 type: ThumbnailType.MINIATURE,
266 automaticallyGenerated: false
267 })
fbad87b0
C
268 }
269
e8bafea3 270 return undefined
ce33919c
C
271}
272
273async function processPreview (req: express.Request, video: VideoModel) {
5d08a6a7 274 const previewField = req.files ? req.files['previewfile'] : undefined
fbad87b0
C
275 if (previewField) {
276 const previewPhysicalFile = previewField[0]
ce33919c 277
1ef65f4c
C
278 return createVideoMiniatureFromExisting({
279 inputPath: previewPhysicalFile.path,
280 video,
281 type: ThumbnailType.PREVIEW,
282 automaticallyGenerated: false
283 })
fbad87b0
C
284 }
285
e8bafea3 286 return undefined
ce33919c
C
287}
288
b1770a0a
K
289async function processThumbnailFromUrl (url: string, video: VideoModel) {
290 try {
291 return createVideoMiniatureFromUrl(url, video, ThumbnailType.MINIATURE)
292 } catch (err) {
293 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
294 return undefined
295 }
296}
297
298async function processPreviewFromUrl (url: string, video: VideoModel) {
299 try {
300 return createVideoMiniatureFromUrl(url, video, ThumbnailType.PREVIEW)
301 } catch (err) {
302 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
303 return undefined
304 }
305}
306
e8bafea3 307function insertIntoDB (parameters: {
a1587156
C
308 video: MVideoThumbnailAccountDefault
309 thumbnailModel: MThumbnail
310 previewModel: MThumbnail
311 videoChannel: MChannelAccountDefault
312 tags: string[]
313 videoImportAttributes: Partial<MVideoImport>
453e83ea 314 user: MUser
b49f22d8 315}): Promise<MVideoImportFormattable> {
03371ad9 316 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
e8bafea3 317
ce33919c 318 return sequelizeTypescript.transaction(async t => {
fbad87b0
C
319 const sequelizeOptions = { transaction: t }
320
321 // Save video object in database
1ca9f7c3 322 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
ce33919c 323 videoCreated.VideoChannel = videoChannel
fbad87b0 324
3acc5084
C
325 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
326 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 327
5b77537c 328 await autoBlacklistVideoIfNeeded({
453e83ea 329 video: videoCreated,
5b77537c
C
330 user,
331 notify: false,
332 isRemote: false,
333 isNew: true,
334 transaction: t
335 })
7ccddd7b 336
1ef65f4c 337 await setVideoTags({ video: videoCreated, tags, transaction: t })
fbad87b0
C
338
339 // Create video import object in database
ce33919c
C
340 const videoImport = await VideoImportModel.create(
341 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
342 sequelizeOptions
1ca9f7c3 343 ) as MVideoImportFormattable
fbad87b0
C
344 videoImport.Video = videoCreated
345
346 return videoImport
347 })
fbad87b0 348}