aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers
diff options
context:
space:
mode:
authorChocobozzz <me@florianbigard.com>2020-09-17 10:00:46 +0200
committerChocobozzz <chocobozzz@cpy.re>2020-11-09 15:33:04 +0100
commit1ef65f4c034cc53ab5d55417e52d60e1f7fc1ddb (patch)
tree8bb02f8dc2590e5071306fb311bdc53289e20336 /server/controllers
parentc6c0fa6cd8fe8f752463d8982c3dbcd448739c4e (diff)
downloadPeerTube-1ef65f4c034cc53ab5d55417e52d60e1f7fc1ddb.tar.gz
PeerTube-1ef65f4c034cc53ab5d55417e52d60e1f7fc1ddb.tar.zst
PeerTube-1ef65f4c034cc53ab5d55417e52d60e1f7fc1ddb.zip
Refactor video creation
Diffstat (limited to 'server/controllers')
-rw-r--r--server/controllers/api/videos/import.ts72
-rw-r--r--server/controllers/api/videos/index.ts78
-rw-r--r--server/controllers/api/videos/live.ts40
3 files changed, 76 insertions, 114 deletions
diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts
index 24a237304..5840cd063 100644
--- a/server/controllers/api/videos/import.ts
+++ b/server/controllers/api/videos/import.ts
@@ -1,30 +1,10 @@
1import * as Bluebird from 'bluebird'
1import * as express from 'express' 2import * as express from 'express'
3import { move, readFile } from 'fs-extra'
2import * as magnetUtil from 'magnet-uri' 4import * as magnetUtil from 'magnet-uri'
3import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
4import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
5import { MIMETYPES } from '../../../initializers/constants'
6import { getYoutubeDLInfo, YoutubeDLInfo, getYoutubeDLSubs } from '../../../helpers/youtube-dl'
7import { createReqFiles } from '../../../helpers/express-utils'
8import { logger } from '../../../helpers/logger'
9import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
10import { VideoModel } from '../../../models/video/video'
11import { VideoCaptionModel } from '../../../models/video/video-caption'
12import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils'
13import { getVideoActivityPubUrl } from '../../../lib/activitypub/url'
14import { TagModel } from '../../../models/video/tag'
15import { VideoImportModel } from '../../../models/video/video-import'
16import { JobQueue } from '../../../lib/job-queue/job-queue'
17import { join } from 'path'
18import { isArray } from '../../../helpers/custom-validators/misc'
19import * as Bluebird from 'bluebird'
20import * as parseTorrent from 'parse-torrent' 5import * as parseTorrent from 'parse-torrent'
21import { getSecureTorrentName } from '../../../helpers/utils' 6import { join } from 'path'
22import { move, readFile } from 'fs-extra' 7import { setVideoTags } from '@server/lib/video'
23import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
24import { CONFIG } from '../../../initializers/config'
25import { sequelizeTypescript } from '../../../initializers/database'
26import { createVideoMiniatureFromExisting, createVideoMiniatureFromUrl } from '../../../lib/thumbnail'
27import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
28import { 8import {
29 MChannelAccountDefault, 9 MChannelAccountDefault,
30 MThumbnail, 10 MThumbnail,
@@ -36,6 +16,26 @@ import {
36 MVideoWithBlacklistLight 16 MVideoWithBlacklistLight
37} from '@server/types/models' 17} from '@server/types/models'
38import { MVideoImport, MVideoImportFormattable } from '@server/types/models/video/video-import' 18import { MVideoImport, MVideoImportFormattable } from '@server/types/models/video/video-import'
19import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
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'
31import { getVideoActivityPubUrl } from '../../../lib/activitypub/url'
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'
39 39
40const auditLogger = auditLoggerFactory('video-imports') 40const auditLogger = auditLoggerFactory('video-imports')
41const videoImportsRouter = express.Router() 41const videoImportsRouter = express.Router()
@@ -260,7 +260,12 @@ async function processThumbnail (req: express.Request, video: VideoModel) {
260 if (thumbnailField) { 260 if (thumbnailField) {
261 const thumbnailPhysicalFile = thumbnailField[0] 261 const thumbnailPhysicalFile = thumbnailField[0]
262 262
263 return createVideoMiniatureFromExisting(thumbnailPhysicalFile.path, video, ThumbnailType.MINIATURE, false) 263 return createVideoMiniatureFromExisting({
264 inputPath: thumbnailPhysicalFile.path,
265 video,
266 type: ThumbnailType.MINIATURE,
267 automaticallyGenerated: false
268 })
264 } 269 }
265 270
266 return undefined 271 return undefined
@@ -271,7 +276,12 @@ async function processPreview (req: express.Request, video: VideoModel) {
271 if (previewField) { 276 if (previewField) {
272 const previewPhysicalFile = previewField[0] 277 const previewPhysicalFile = previewField[0]
273 278
274 return createVideoMiniatureFromExisting(previewPhysicalFile.path, video, ThumbnailType.PREVIEW, false) 279 return createVideoMiniatureFromExisting({
280 inputPath: previewPhysicalFile.path,
281 video,
282 type: ThumbnailType.PREVIEW,
283 automaticallyGenerated: false
284 })
275 } 285 }
276 286
277 return undefined 287 return undefined
@@ -325,15 +335,7 @@ function insertIntoDB (parameters: {
325 transaction: t 335 transaction: t
326 }) 336 })
327 337
328 // Set tags to the video 338 await setVideoTags({ video: videoCreated, tags, transaction: t })
329 if (tags) {
330 const tagInstances = await TagModel.findOrCreateTags(tags, t)
331
332 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
333 videoCreated.Tags = tagInstances
334 } else {
335 videoCreated.Tags = []
336 }
337 339
338 // Create video import object in database 340 // Create video import object in database
339 const videoImport = await VideoImportModel.create( 341 const videoImport = await VideoImportModel.create(
diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts
index 94f0361ee..1539afc35 100644
--- a/server/controllers/api/videos/index.ts
+++ b/server/controllers/api/videos/index.ts
@@ -6,11 +6,11 @@ import { addOptimizeOrMergeAudioJob } from '@server/helpers/video'
6import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' 6import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
7import { changeVideoChannelShare } from '@server/lib/activitypub/share' 7import { changeVideoChannelShare } from '@server/lib/activitypub/share'
8import { getVideoActivityPubUrl } from '@server/lib/activitypub/url' 8import { getVideoActivityPubUrl } from '@server/lib/activitypub/url'
9import { buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
9import { getVideoFilePath } from '@server/lib/video-paths' 10import { getVideoFilePath } from '@server/lib/video-paths'
10import { getServerActor } from '@server/models/application/application' 11import { getServerActor } from '@server/models/application/application'
11import { MVideoDetails, MVideoFullLight } from '@server/types/models' 12import { MVideoDetails, MVideoFullLight } from '@server/types/models'
12import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared' 13import { VideoCreate, VideoState, VideoUpdate } from '../../../../shared'
13import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
14import { VideoFilter } from '../../../../shared/models/videos/video-query.type' 14import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
15import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' 15import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
16import { resetSequelizeInstance } from '../../../helpers/database-utils' 16import { resetSequelizeInstance } from '../../../helpers/database-utils'
@@ -34,7 +34,7 @@ import { JobQueue } from '../../../lib/job-queue'
34import { Notifier } from '../../../lib/notifier' 34import { Notifier } from '../../../lib/notifier'
35import { Hooks } from '../../../lib/plugins/hooks' 35import { Hooks } from '../../../lib/plugins/hooks'
36import { Redis } from '../../../lib/redis' 36import { Redis } from '../../../lib/redis'
37import { createVideoMiniatureFromExisting, generateVideoMiniature } from '../../../lib/thumbnail' 37import { generateVideoMiniature } from '../../../lib/thumbnail'
38import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' 38import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
39import { 39import {
40 asyncMiddleware, 40 asyncMiddleware,
@@ -186,25 +186,9 @@ async function addVideo (req: express.Request, res: express.Response) {
186 const videoPhysicalFile = req.files['videofile'][0] 186 const videoPhysicalFile = req.files['videofile'][0]
187 const videoInfo: VideoCreate = req.body 187 const videoInfo: VideoCreate = req.body
188 188
189 // Prepare data so we don't block the transaction 189 const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id)
190 const videoData = { 190 videoData.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
191 name: videoInfo.name, 191 videoData.duration = videoPhysicalFile['duration'] // duration was added by a previous middleware
192 remote: false,
193 category: videoInfo.category,
194 licence: videoInfo.licence,
195 language: videoInfo.language,
196 commentsEnabled: videoInfo.commentsEnabled !== false, // If the value is not "false", the default is "true"
197 downloadEnabled: videoInfo.downloadEnabled !== false,
198 waitTranscoding: videoInfo.waitTranscoding || false,
199 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
200 nsfw: videoInfo.nsfw || false,
201 description: videoInfo.description,
202 support: videoInfo.support,
203 privacy: videoInfo.privacy || VideoPrivacy.PRIVATE,
204 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
205 channelId: res.locals.videoChannel.id,
206 originallyPublishedAt: videoInfo.originallyPublishedAt
207 }
208 192
209 const video = new VideoModel(videoData) as MVideoDetails 193 const video = new VideoModel(videoData) as MVideoDetails
210 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object 194 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
@@ -230,17 +214,11 @@ async function addVideo (req: express.Request, res: express.Response) {
230 videoPhysicalFile.filename = getVideoFilePath(video, videoFile) 214 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
231 videoPhysicalFile.path = destination 215 videoPhysicalFile.path = destination
232 216
233 // Process thumbnail or create it from the video 217 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
234 const thumbnailField = req.files['thumbnailfile'] 218 video,
235 const thumbnailModel = thumbnailField 219 files: req.files,
236 ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE, false) 220 fallback: type => generateVideoMiniature(video, videoFile, type)
237 : await generateVideoMiniature(video, videoFile, ThumbnailType.MINIATURE) 221 })
238
239 // Process preview or create it from the video
240 const previewField = req.files['previewfile']
241 const previewModel = previewField
242 ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW, false)
243 : await generateVideoMiniature(video, videoFile, ThumbnailType.PREVIEW)
244 222
245 // Create the torrent file 223 // Create the torrent file
246 await createTorrentAndSetInfoHash(video, videoFile) 224 await createTorrentAndSetInfoHash(video, videoFile)
@@ -261,13 +239,7 @@ async function addVideo (req: express.Request, res: express.Response) {
261 239
262 video.VideoFiles = [ videoFile ] 240 video.VideoFiles = [ videoFile ]
263 241
264 // Create tags 242 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
265 if (videoInfo.tags !== undefined) {
266 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
267
268 await video.$set('Tags', tagInstances, sequelizeOptions)
269 video.Tags = tagInstances
270 }
271 243
272 // Schedule an update in the future? 244 // Schedule an update in the future?
273 if (videoInfo.scheduleUpdate) { 245 if (videoInfo.scheduleUpdate) {
@@ -318,14 +290,12 @@ async function updateVideo (req: express.Request, res: express.Response) {
318 const wasConfidentialVideo = videoInstance.isConfidential() 290 const wasConfidentialVideo = videoInstance.isConfidential()
319 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation() 291 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
320 292
321 // Process thumbnail or create it from the video 293 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
322 const thumbnailModel = req.files?.['thumbnailfile'] 294 video: videoInstance,
323 ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE, false) 295 files: req.files,
324 : undefined 296 fallback: () => Promise.resolve(undefined),
325 297 automaticallyGenerated: false
326 const previewModel = req.files?.['previewfile'] 298 })
327 ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW, false)
328 : undefined
329 299
330 try { 300 try {
331 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => { 301 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
@@ -366,12 +336,12 @@ async function updateVideo (req: express.Request, res: express.Response) {
366 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t) 336 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
367 337
368 // Video tags update? 338 // Video tags update?
369 if (videoInfoToUpdate.tags !== undefined) { 339 await setVideoTags({
370 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t) 340 video: videoInstanceUpdated,
371 341 tags: videoInfoToUpdate.tags,
372 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions) 342 transaction: t,
373 videoInstanceUpdated.Tags = tagInstances 343 defaultValue: videoInstanceUpdated.Tags
374 } 344 })
375 345
376 // Video channel update? 346 // Video channel update?
377 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) { 347 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
diff --git a/server/controllers/api/videos/live.ts b/server/controllers/api/videos/live.ts
index d08ef9869..97b135f96 100644
--- a/server/controllers/api/videos/live.ts
+++ b/server/controllers/api/videos/live.ts
@@ -4,18 +4,16 @@ import { createReqFiles } from '@server/helpers/express-utils'
4import { CONFIG } from '@server/initializers/config' 4import { CONFIG } from '@server/initializers/config'
5import { ASSETS_PATH, MIMETYPES } from '@server/initializers/constants' 5import { ASSETS_PATH, MIMETYPES } from '@server/initializers/constants'
6import { getVideoActivityPubUrl } from '@server/lib/activitypub/url' 6import { getVideoActivityPubUrl } from '@server/lib/activitypub/url'
7import { buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
7import { videoLiveAddValidator, videoLiveGetValidator } from '@server/middlewares/validators/videos/video-live' 8import { videoLiveAddValidator, videoLiveGetValidator } from '@server/middlewares/validators/videos/video-live'
8import { VideoLiveModel } from '@server/models/video/video-live' 9import { VideoLiveModel } from '@server/models/video/video-live'
9import { MVideoDetails, MVideoFullLight } from '@server/types/models' 10import { MVideoDetails, MVideoFullLight } from '@server/types/models'
10import { VideoCreate, VideoPrivacy, VideoState } from '../../../../shared' 11import { VideoCreate, VideoState } from '../../../../shared'
11import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
12import { logger } from '../../../helpers/logger' 12import { logger } from '../../../helpers/logger'
13import { sequelizeTypescript } from '../../../initializers/database' 13import { sequelizeTypescript } from '../../../initializers/database'
14import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail' 14import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail'
15import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate } from '../../../middlewares' 15import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate } from '../../../middlewares'
16import { TagModel } from '../../../models/video/tag'
17import { VideoModel } from '../../../models/video/video' 16import { VideoModel } from '../../../models/video/video'
18import { buildLocalVideoFromCreate } from '@server/lib/video'
19 17
20const liveRouter = express.Router() 18const liveRouter = express.Router()
21 19
@@ -59,26 +57,24 @@ async function addLiveVideo (req: express.Request, res: express.Response) {
59 const videoInfo: VideoCreate = req.body 57 const videoInfo: VideoCreate = req.body
60 58
61 // Prepare data so we don't block the transaction 59 // Prepare data so we don't block the transaction
62 const videoData = buildLocalVideoFromCreate(videoInfo, res.locals.videoChannel.id) 60 const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id)
63 videoData.isLive = true 61 videoData.isLive = true
64 62 videoData.state = VideoState.WAITING_FOR_LIVE
65 const videoLive = new VideoLiveModel() 63 videoData.duration = 0
66 videoLive.streamKey = uuidv4()
67 64
68 const video = new VideoModel(videoData) as MVideoDetails 65 const video = new VideoModel(videoData) as MVideoDetails
69 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object 66 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
70 67
71 // Process thumbnail or create it from the video 68 const videoLive = new VideoLiveModel()
72 const thumbnailField = req.files ? req.files['thumbnailfile'] : null 69 videoLive.streamKey = uuidv4()
73 const thumbnailModel = thumbnailField
74 ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE, false)
75 : await createVideoMiniatureFromExisting(ASSETS_PATH.DEFAULT_LIVE_BACKGROUND, video, ThumbnailType.MINIATURE, true)
76 70
77 // Process preview or create it from the video 71 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
78 const previewField = req.files ? req.files['previewfile'] : null 72 video,
79 const previewModel = previewField 73 files: req.files,
80 ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW, false) 74 fallback: type => {
81 : await createVideoMiniatureFromExisting(ASSETS_PATH.DEFAULT_LIVE_BACKGROUND, video, ThumbnailType.PREVIEW, true) 75 return createVideoMiniatureFromExisting({ inputPath: ASSETS_PATH.DEFAULT_LIVE_BACKGROUND, video, type, automaticallyGenerated: true })
76 }
77 })
82 78
83 const { videoCreated } = await sequelizeTypescript.transaction(async t => { 79 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
84 const sequelizeOptions = { transaction: t } 80 const sequelizeOptions = { transaction: t }
@@ -94,13 +90,7 @@ async function addLiveVideo (req: express.Request, res: express.Response) {
94 videoLive.videoId = videoCreated.id 90 videoLive.videoId = videoCreated.id
95 await videoLive.save(sequelizeOptions) 91 await videoLive.save(sequelizeOptions)
96 92
97 // Create tags 93 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
98 if (videoInfo.tags !== undefined) {
99 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
100
101 await video.$set('Tags', tagInstances, sequelizeOptions)
102 video.Tags = tagInstances
103 }
104 94
105 logger.info('Video live %s with uuid %s created.', videoInfo.name, videoCreated.uuid) 95 logger.info('Video live %s with uuid %s created.', videoInfo.name, videoCreated.uuid)
106 96