]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Bufferize videos views in redis
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
93e1258c 2import { extname, join } from 'path'
2186386c 3import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
3a6f351b 4import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
ac81d1a0 5import { processImage } from '../../../helpers/image-utils'
da854ddd 6import { logger } from '../../../helpers/logger'
80e36cd9 7import { auditLoggerFactory, VideoAuditView } from '../../../helpers/audit-logger'
06215f15 8import { getFormattedObjects, getServerActor } from '../../../helpers/utils'
65fcc311 9import {
ac81d1a0
C
10 CONFIG,
11 IMAGE_MIMETYPE_EXT,
12 PREVIEWS_SIZE,
13 sequelizeTypescript,
14 THUMBNAILS_SIZE,
15 VIDEO_CATEGORIES,
16 VIDEO_LANGUAGES,
17 VIDEO_LICENCES,
18 VIDEO_MIMETYPE_EXT,
3fd3ab2d
C
19 VIDEO_PRIVACIES
20} from '../../../initializers'
0f320037
C
21import {
22 changeVideoChannelShare,
2186386c 23 federateVideoIfNeeded,
0f320037 24 fetchRemoteVideoDescription,
2186386c 25 getVideoActivityPubUrl
0f320037 26} from '../../../lib/activitypub'
2186386c 27import { sendCreateView } from '../../../lib/activitypub/send'
94a5ff8a 28import { JobQueue } from '../../../lib/job-queue'
b5c0e955 29import { Redis } from '../../../lib/redis'
65fcc311 30import {
ac81d1a0 31 asyncMiddleware,
90d4bb81 32 asyncRetryTransactionMiddleware,
ac81d1a0 33 authenticate,
d525fc39 34 commonVideosFiltersValidator,
0883b324 35 optionalAuthenticate,
ac81d1a0
C
36 paginationValidator,
37 setDefaultPagination,
38 setDefaultSort,
39 videosAddValidator,
40 videosGetValidator,
41 videosRemoveValidator,
ac81d1a0
C
42 videosSortValidator,
43 videosUpdateValidator
65fcc311 44} from '../../../middlewares'
3fd3ab2d
C
45import { TagModel } from '../../../models/video/tag'
46import { VideoModel } from '../../../models/video/video'
47import { VideoFileModel } from '../../../models/video/video-file'
65fcc311
C
48import { abuseVideoRouter } from './abuse'
49import { blacklistRouter } from './blacklist'
bf1f6508 50import { videoCommentRouter } from './comment'
571389d4 51import { rateVideoRouter } from './rate'
0883b324 52import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
06215f15 53import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils'
2baea0c7 54import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
40e87e9e 55import { videoCaptionsRouter } from './captions'
fbad87b0 56import { videoImportsRouter } from './import'
06215f15 57import { resetSequelizeInstance } from '../../../helpers/database-utils'
62689b94 58import { rename } from 'fs-extra'
65fcc311 59
80e36cd9 60const auditLogger = auditLoggerFactory('videos')
65fcc311 61const videosRouter = express.Router()
9f10b292 62
ac81d1a0
C
63const reqVideoFileAdd = createReqFiles(
64 [ 'videofile', 'thumbnailfile', 'previewfile' ],
65 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
66 {
67 videofile: CONFIG.STORAGE.VIDEOS_DIR,
68 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
69 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
70 }
71)
72const reqVideoFileUpdate = createReqFiles(
73 [ 'thumbnailfile', 'previewfile' ],
74 IMAGE_MIMETYPE_EXT,
75 {
76 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
77 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
78 }
79)
8c308c2b 80
65fcc311
C
81videosRouter.use('/', abuseVideoRouter)
82videosRouter.use('/', blacklistRouter)
83videosRouter.use('/', rateVideoRouter)
bf1f6508 84videosRouter.use('/', videoCommentRouter)
40e87e9e 85videosRouter.use('/', videoCaptionsRouter)
fbad87b0 86videosRouter.use('/', videoImportsRouter)
d33242b0 87
65fcc311
C
88videosRouter.get('/categories', listVideoCategories)
89videosRouter.get('/licences', listVideoLicences)
90videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 91videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 92
65fcc311
C
93videosRouter.get('/',
94 paginationValidator,
95 videosSortValidator,
1174a847 96 setDefaultSort,
f05a1c30 97 setDefaultPagination,
0883b324 98 optionalAuthenticate,
d525fc39 99 commonVideosFiltersValidator,
eb080476 100 asyncMiddleware(listVideos)
fbf1134e 101)
65fcc311
C
102videosRouter.put('/:id',
103 authenticate,
ac81d1a0 104 reqVideoFileUpdate,
a2431b7d 105 asyncMiddleware(videosUpdateValidator),
90d4bb81 106 asyncRetryTransactionMiddleware(updateVideo)
7b1f49de 107)
e95561cd 108videosRouter.post('/upload',
65fcc311 109 authenticate,
ac81d1a0 110 reqVideoFileAdd,
3fd3ab2d 111 asyncMiddleware(videosAddValidator),
90d4bb81 112 asyncRetryTransactionMiddleware(addVideo)
fbf1134e 113)
9567011b
C
114
115videosRouter.get('/:id/description',
a2431b7d 116 asyncMiddleware(videosGetValidator),
9567011b
C
117 asyncMiddleware(getVideoDescription)
118)
65fcc311 119videosRouter.get('/:id',
a2431b7d 120 asyncMiddleware(videosGetValidator),
68ce3ae0 121 getVideo
fbf1134e 122)
1f3e9fec
C
123videosRouter.post('/:id/views',
124 asyncMiddleware(videosGetValidator),
125 asyncMiddleware(viewVideo)
126)
198b205c 127
65fcc311
C
128videosRouter.delete('/:id',
129 authenticate,
a2431b7d 130 asyncMiddleware(videosRemoveValidator),
90d4bb81 131 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 132)
198b205c 133
9f10b292 134// ---------------------------------------------------------------------------
c45f7f84 135
65fcc311
C
136export {
137 videosRouter
138}
c45f7f84 139
9f10b292 140// ---------------------------------------------------------------------------
c45f7f84 141
556ddc31 142function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 143 res.json(VIDEO_CATEGORIES)
6e07c3de
C
144}
145
556ddc31 146function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 147 res.json(VIDEO_LICENCES)
6f0c39e2
C
148}
149
556ddc31 150function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 151 res.json(VIDEO_LANGUAGES)
3092476e
C
152}
153
fd45e8f4
C
154function listVideoPrivacies (req: express.Request, res: express.Response) {
155 res.json(VIDEO_PRIVACIES)
156}
157
90d4bb81
C
158async function addVideo (req: express.Request, res: express.Response) {
159 const videoPhysicalFile = req.files['videofile'][0]
556ddc31 160 const videoInfo: VideoCreate = req.body
9f10b292 161
e11f68a3
C
162 // Prepare data so we don't block the transaction
163 const videoData = {
164 name: videoInfo.name,
165 remote: false,
e11f68a3
C
166 category: videoInfo.category,
167 licence: videoInfo.licence,
168 language: videoInfo.language,
2186386c
C
169 commentsEnabled: videoInfo.commentsEnabled || false,
170 waitTranscoding: videoInfo.waitTranscoding || false,
171 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
172 nsfw: videoInfo.nsfw || false,
e11f68a3 173 description: videoInfo.description,
2422c46b 174 support: videoInfo.support,
e11f68a3
C
175 privacy: videoInfo.privacy,
176 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
177 channelId: res.locals.videoChannel.id
178 }
3fd3ab2d 179 const video = new VideoModel(videoData)
2186386c 180 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
eb080476 181
2186386c 182 // Build the file object
056aa7f2 183 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
3a6f351b
C
184 const fps = await getVideoFileFPS(videoPhysicalFile.path)
185
e11f68a3
C
186 const videoFileData = {
187 extname: extname(videoPhysicalFile.filename),
056aa7f2 188 resolution: videoFileResolution,
3a6f351b
C
189 size: videoPhysicalFile.size,
190 fps
e11f68a3 191 }
3fd3ab2d 192 const videoFile = new VideoFileModel(videoFileData)
2186386c
C
193
194 // Move physical file
e11f68a3 195 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
e11f68a3 196 const destination = join(videoDir, video.getVideoFilename(videoFile))
62689b94 197 await rename(videoPhysicalFile.path, destination)
e3a682a8
C
198 // This is important in case if there is another attempt in the retry process
199 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
82815eb6 200 videoPhysicalFile.path = destination
ac81d1a0
C
201
202 // Process thumbnail or create it from the video
203 const thumbnailField = req.files['thumbnailfile']
204 if (thumbnailField) {
205 const thumbnailPhysicalFile = thumbnailField[0]
206 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
207 } else {
208 await video.createThumbnail(videoFile)
209 }
93e1258c 210
ac81d1a0
C
211 // Process preview or create it from the video
212 const previewField = req.files['previewfile']
213 if (previewField) {
214 const previewPhysicalFile = previewField[0]
215 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
216 } else {
217 await video.createPreview(videoFile)
218 }
eb080476 219
2186386c 220 // Create the torrent file
ac81d1a0 221 await video.createTorrentAndSetInfoHash(videoFile)
eb080476 222
94a5ff8a 223 const videoCreated = await sequelizeTypescript.transaction(async t => {
e11f68a3 224 const sequelizeOptions = { transaction: t }
eb080476 225
eb080476
C
226 const videoCreated = await video.save(sequelizeOptions)
227 // Do not forget to add video channel information to the created video
228 videoCreated.VideoChannel = res.locals.videoChannel
7920c273 229
eb080476 230 videoFile.videoId = video.id
eb080476 231 await videoFile.save(sequelizeOptions)
e11f68a3
C
232
233 video.VideoFiles = [ videoFile ]
93e1258c 234
2baea0c7 235 // Create tags
2efd32f6 236 if (videoInfo.tags !== undefined) {
3fd3ab2d 237 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
eb080476 238
3fd3ab2d 239 await video.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
240 video.Tags = tagInstances
241 }
242
2baea0c7
C
243 // Schedule an update in the future?
244 if (videoInfo.scheduleUpdate) {
245 await ScheduleVideoUpdateModel.create({
246 videoId: video.id,
247 updateAt: videoInfo.scheduleUpdate.updateAt,
248 privacy: videoInfo.scheduleUpdate.privacy || null
249 }, { transaction: t })
250 }
251
2186386c 252 await federateVideoIfNeeded(video, true, t)
eb080476 253
80e36cd9 254 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
cadb46d8
C
255 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
256
257 return videoCreated
258 })
94a5ff8a 259
2186386c 260 if (video.state === VideoState.TO_TRANSCODE) {
94a5ff8a
C
261 // Put uuid because we don't have id auto incremented for now
262 const dataInput = {
0c948c16
C
263 videoUUID: videoCreated.uuid,
264 isNewVideo: true
94a5ff8a
C
265 }
266
267 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
268 }
269
90d4bb81
C
270 return res.json({
271 video: {
272 id: videoCreated.id,
273 uuid: videoCreated.uuid
274 }
275 }).end()
ed04d94f
C
276}
277
eb080476 278async function updateVideo (req: express.Request, res: express.Response) {
3fd3ab2d 279 const videoInstance: VideoModel = res.locals.video
7f4e7c36 280 const videoFieldsSave = videoInstance.toJSON()
80e36cd9 281 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
556ddc31 282 const videoInfoToUpdate: VideoUpdate = req.body
fd45e8f4 283 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
7b1f49de 284
ac81d1a0
C
285 // Process thumbnail or create it from the video
286 if (req.files && req.files['thumbnailfile']) {
287 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
288 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
289 }
290
291 // Process preview or create it from the video
292 if (req.files && req.files['previewfile']) {
293 const previewPhysicalFile = req.files['previewfile'][0]
294 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
295 }
296
eb080476 297 try {
3fd3ab2d 298 await sequelizeTypescript.transaction(async t => {
eb080476
C
299 const sequelizeOptions = {
300 transaction: t
301 }
0f320037 302 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 303
eb080476
C
304 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
305 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
306 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
307 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
308 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
2186386c 309 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
2422c46b 310 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
eb080476 311 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
47564bbe 312 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
2922e048
JLB
313 if (videoInfoToUpdate.privacy !== undefined) {
314 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
315 videoInstance.set('privacy', newPrivacy)
316
317 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
318 videoInstance.set('publishedAt', new Date())
319 }
320 }
7b1f49de 321
54141398 322 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 323
0f320037 324 // Video tags update?
2efd32f6 325 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 326 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 327
0f320037
C
328 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
329 videoInstanceUpdated.Tags = tagInstances
eb080476 330 }
7920c273 331
0f320037
C
332 // Video channel update?
333 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 334 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 335 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037
C
336
337 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
338 }
339
2baea0c7
C
340 // Schedule an update in the future?
341 if (videoInfoToUpdate.scheduleUpdate) {
342 await ScheduleVideoUpdateModel.upsert({
343 videoId: videoInstanceUpdated.id,
344 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
345 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
346 }, { transaction: t })
e94fc297
C
347 } else if (videoInfoToUpdate.scheduleUpdate === null) {
348 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
349 }
350
2186386c 351 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
e94fc297 352 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
6fcd19ba 353
80e36cd9
AB
354 auditLogger.update(
355 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
356 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
357 oldVideoAuditView
358 )
359 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
360 })
eb080476 361 } catch (err) {
6fcd19ba
C
362 // Force fields we want to update
363 // If the transaction is retried, sequelize will think the object has not changed
364 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 365 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
366
367 throw err
eb080476 368 }
90d4bb81
C
369
370 return res.type('json').status(204).end()
9f10b292 371}
8c308c2b 372
1f3e9fec
C
373function getVideo (req: express.Request, res: express.Response) {
374 const videoInstance = res.locals.video
375
376 return res.json(videoInstance.toFormattedDetailsJSON())
377}
378
379async function viewVideo (req: express.Request, res: express.Response) {
818f7987 380 const videoInstance = res.locals.video
9e167724 381
490b595a 382 const ip = req.ip
6b616860 383 const exists = await Redis.Instance.isVideoIPViewExists(ip, videoInstance.uuid)
b5c0e955
C
384 if (exists) {
385 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
386 return res.status(204).end()
387 }
388
6b616860
C
389 await Promise.all([
390 Redis.Instance.addVideoView(videoInstance.id),
391 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
392 ])
b5c0e955 393
50d6de9c 394 const serverAccount = await getServerActor()
40ff5707 395
07197db4 396 await sendCreateView(serverAccount, videoInstance, undefined)
9e167724 397
1f3e9fec 398 return res.status(204).end()
9f10b292 399}
8c308c2b 400
9567011b
C
401async function getVideoDescription (req: express.Request, res: express.Response) {
402 const videoInstance = res.locals.video
403 let description = ''
404
405 if (videoInstance.isOwned()) {
406 description = videoInstance.description
407 } else {
571389d4 408 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
409 }
410
411 return res.json({ description })
412}
413
eb080476 414async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
48dce1c9
C
415 const resultList = await VideoModel.listForApi({
416 start: req.query.start,
417 count: req.query.count,
418 sort: req.query.sort,
06a05d5f 419 includeLocalVideos: true,
d525fc39
C
420 categoryOneOf: req.query.categoryOneOf,
421 licenceOneOf: req.query.licenceOneOf,
422 languageOneOf: req.query.languageOneOf,
423 tagsOneOf: req.query.tagsOneOf,
424 tagsAllOf: req.query.tagsAllOf,
425 nsfw: buildNSFWFilter(res, req.query.nsfw),
48dce1c9
C
426 filter: req.query.filter as VideoFilter,
427 withFiles: false
428 })
eb080476
C
429
430 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 431}
c45f7f84 432
eb080476 433async function removeVideo (req: express.Request, res: express.Response) {
3fd3ab2d 434 const videoInstance: VideoModel = res.locals.video
91f6f169 435
3fd3ab2d 436 await sequelizeTypescript.transaction(async t => {
eb080476 437 await videoInstance.destroy({ transaction: t })
91f6f169 438 })
eb080476 439
80e36cd9 440 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 441 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81
C
442
443 return res.type('json').status(204).end()
9f10b292 444}