]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Live streaming implementation first step
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
8054669f 2import { move } from 'fs-extra'
3f6b7aa1 3import { extname } from 'path'
8054669f
C
4import toInt from 'validator/lib/toInt'
5import { addOptimizeOrMergeAudioJob } from '@server/helpers/video'
6import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
7import { changeVideoChannelShare } from '@server/lib/activitypub/share'
8import { getVideoActivityPubUrl } from '@server/lib/activitypub/url'
9import { getVideoFilePath } from '@server/lib/video-paths'
10import { getServerActor } from '@server/models/application/application'
11import { MVideoDetails, MVideoFullLight } from '@server/types/models'
b345a804 12import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
8054669f
C
13import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
14import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
15import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
16import { resetSequelizeInstance } from '../../../helpers/database-utils'
17import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils'
d57d1d83 18import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
da854ddd 19import { logger } from '../../../helpers/logger'
8dc8a34e 20import { getFormattedObjects } from '../../../helpers/utils'
8054669f 21import { CONFIG } from '../../../initializers/config'
b345a804
C
22import {
23 DEFAULT_AUDIO_RESOLUTION,
24 MIMETYPES,
25 VIDEO_CATEGORIES,
26 VIDEO_LANGUAGES,
27 VIDEO_LICENCES,
a1587156 28 VIDEO_PRIVACIES
b345a804 29} from '../../../initializers/constants'
8054669f
C
30import { sequelizeTypescript } from '../../../initializers/database'
31import { sendView } from '../../../lib/activitypub/send/send-view'
8dc8a34e 32import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
94a5ff8a 33import { JobQueue } from '../../../lib/job-queue'
8054669f
C
34import { Notifier } from '../../../lib/notifier'
35import { Hooks } from '../../../lib/plugins/hooks'
b5c0e955 36import { Redis } from '../../../lib/redis'
8054669f
C
37import { createVideoMiniatureFromExisting, generateVideoMiniature } from '../../../lib/thumbnail'
38import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
65fcc311 39import {
ac81d1a0 40 asyncMiddleware,
90d4bb81 41 asyncRetryTransactionMiddleware,
ac81d1a0 42 authenticate,
8d427346 43 checkVideoFollowConstraints,
d525fc39 44 commonVideosFiltersValidator,
0883b324 45 optionalAuthenticate,
ac81d1a0
C
46 paginationValidator,
47 setDefaultPagination,
8054669f 48 setDefaultVideosSort,
d57d1d83 49 videoFileMetadataGetValidator,
ac81d1a0 50 videosAddValidator,
09209296 51 videosCustomGetValidator,
ac81d1a0
C
52 videosGetValidator,
53 videosRemoveValidator,
ac81d1a0 54 videosSortValidator,
d57d1d83 55 videosUpdateValidator
65fcc311 56} from '../../../middlewares'
8054669f 57import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
3fd3ab2d
C
58import { TagModel } from '../../../models/video/tag'
59import { VideoModel } from '../../../models/video/video'
60import { VideoFileModel } from '../../../models/video/video-file'
65fcc311
C
61import { abuseVideoRouter } from './abuse'
62import { blacklistRouter } from './blacklist'
40e87e9e 63import { videoCaptionsRouter } from './captions'
8054669f 64import { videoCommentRouter } from './comment'
fbad87b0 65import { videoImportsRouter } from './import'
c6c0fa6c 66import { liveRouter } from './live'
8054669f
C
67import { ownershipVideoRouter } from './ownership'
68import { rateVideoRouter } from './rate'
6e46de09 69import { watchingRouter } from './watching'
65fcc311 70
80e36cd9 71const auditLogger = auditLoggerFactory('videos')
65fcc311 72const videosRouter = express.Router()
9f10b292 73
ac81d1a0
C
74const reqVideoFileAdd = createReqFiles(
75 [ 'videofile', 'thumbnailfile', 'previewfile' ],
14e2014a 76 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
ac81d1a0 77 {
6040f87d
C
78 videofile: CONFIG.STORAGE.TMP_DIR,
79 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
80 previewfile: CONFIG.STORAGE.TMP_DIR
ac81d1a0
C
81 }
82)
83const reqVideoFileUpdate = createReqFiles(
84 [ 'thumbnailfile', 'previewfile' ],
14e2014a 85 MIMETYPES.IMAGE.MIMETYPE_EXT,
ac81d1a0 86 {
6040f87d
C
87 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
88 previewfile: CONFIG.STORAGE.TMP_DIR
ac81d1a0
C
89 }
90)
8c308c2b 91
65fcc311
C
92videosRouter.use('/', abuseVideoRouter)
93videosRouter.use('/', blacklistRouter)
94videosRouter.use('/', rateVideoRouter)
bf1f6508 95videosRouter.use('/', videoCommentRouter)
40e87e9e 96videosRouter.use('/', videoCaptionsRouter)
fbad87b0 97videosRouter.use('/', videoImportsRouter)
74d63469 98videosRouter.use('/', ownershipVideoRouter)
6e46de09 99videosRouter.use('/', watchingRouter)
c6c0fa6c 100videosRouter.use('/', liveRouter)
d33242b0 101
65fcc311
C
102videosRouter.get('/categories', listVideoCategories)
103videosRouter.get('/licences', listVideoLicences)
104videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 105videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 106
65fcc311
C
107videosRouter.get('/',
108 paginationValidator,
109 videosSortValidator,
8054669f 110 setDefaultVideosSort,
f05a1c30 111 setDefaultPagination,
0883b324 112 optionalAuthenticate,
d525fc39 113 commonVideosFiltersValidator,
eb080476 114 asyncMiddleware(listVideos)
fbf1134e 115)
65fcc311
C
116videosRouter.put('/:id',
117 authenticate,
ac81d1a0 118 reqVideoFileUpdate,
a2431b7d 119 asyncMiddleware(videosUpdateValidator),
90d4bb81 120 asyncRetryTransactionMiddleware(updateVideo)
7b1f49de 121)
e95561cd 122videosRouter.post('/upload',
65fcc311 123 authenticate,
ac81d1a0 124 reqVideoFileAdd,
3fd3ab2d 125 asyncMiddleware(videosAddValidator),
90d4bb81 126 asyncRetryTransactionMiddleware(addVideo)
fbf1134e 127)
9567011b
C
128
129videosRouter.get('/:id/description',
a2431b7d 130 asyncMiddleware(videosGetValidator),
9567011b
C
131 asyncMiddleware(getVideoDescription)
132)
8319d6ae
RK
133videosRouter.get('/:id/metadata/:videoFileId',
134 asyncMiddleware(videoFileMetadataGetValidator),
135 asyncMiddleware(getVideoFileMetadata)
136)
65fcc311 137videosRouter.get('/:id',
6e46de09 138 optionalAuthenticate,
09209296 139 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
8d427346 140 asyncMiddleware(checkVideoFollowConstraints),
09209296 141 asyncMiddleware(getVideo)
fbf1134e 142)
1f3e9fec 143videosRouter.post('/:id/views',
2c8776fc 144 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
1f3e9fec
C
145 asyncMiddleware(viewVideo)
146)
198b205c 147
65fcc311
C
148videosRouter.delete('/:id',
149 authenticate,
a2431b7d 150 asyncMiddleware(videosRemoveValidator),
90d4bb81 151 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 152)
198b205c 153
9f10b292 154// ---------------------------------------------------------------------------
c45f7f84 155
65fcc311
C
156export {
157 videosRouter
158}
c45f7f84 159
9f10b292 160// ---------------------------------------------------------------------------
c45f7f84 161
556ddc31 162function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 163 res.json(VIDEO_CATEGORIES)
6e07c3de
C
164}
165
556ddc31 166function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 167 res.json(VIDEO_LICENCES)
6f0c39e2
C
168}
169
556ddc31 170function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 171 res.json(VIDEO_LANGUAGES)
3092476e
C
172}
173
fd45e8f4
C
174function listVideoPrivacies (req: express.Request, res: express.Response) {
175 res.json(VIDEO_PRIVACIES)
176}
177
90d4bb81 178async function addVideo (req: express.Request, res: express.Response) {
8b917537
C
179 // Processing the video could be long
180 // Set timeout to 10 minutes
181 req.setTimeout(1000 * 60 * 10, () => {
182 logger.error('Upload video has timed out.')
183 return res.sendStatus(408)
184 })
185
90d4bb81 186 const videoPhysicalFile = req.files['videofile'][0]
556ddc31 187 const videoInfo: VideoCreate = req.body
9f10b292 188
e11f68a3
C
189 // Prepare data so we don't block the transaction
190 const videoData = {
191 name: videoInfo.name,
192 remote: false,
e11f68a3
C
193 category: videoInfo.category,
194 licence: videoInfo.licence,
195 language: videoInfo.language,
46aaefa9
FS
196 commentsEnabled: videoInfo.commentsEnabled !== false, // If the value is not "false", the default is "true"
197 downloadEnabled: videoInfo.downloadEnabled !== false,
2186386c
C
198 waitTranscoding: videoInfo.waitTranscoding || false,
199 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
200 nsfw: videoInfo.nsfw || false,
e11f68a3 201 description: videoInfo.description,
2422c46b 202 support: videoInfo.support,
2b4dd7e2 203 privacy: videoInfo.privacy || VideoPrivacy.PRIVATE,
e11f68a3 204 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
1e74f19a 205 channelId: res.locals.videoChannel.id,
206 originallyPublishedAt: videoInfo.originallyPublishedAt
e11f68a3 207 }
7ccddd7b 208
96ca24f0 209 const video = new VideoModel(videoData) as MVideoDetails
2186386c 210 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
eb080476 211
46a6db24 212 const videoFile = new VideoFileModel({
e11f68a3 213 extname: extname(videoPhysicalFile.filename),
d7a25329 214 size: videoPhysicalFile.size,
8319d6ae
RK
215 videoStreamingPlaylistId: null,
216 metadata: await getMetadataFromFile<any>(videoPhysicalFile.path)
46a6db24 217 })
2186386c 218
ad3405d0
C
219 if (videoFile.isAudio()) {
220 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
221 } else {
536598cf
C
222 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
223 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
536598cf
C
224 }
225
2186386c 226 // Move physical file
d7a25329 227 const destination = getVideoFilePath(video, videoFile)
14e2014a 228 await move(videoPhysicalFile.path, destination)
e3a682a8 229 // This is important in case if there is another attempt in the retry process
d7a25329 230 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
82815eb6 231 videoPhysicalFile.path = destination
ac81d1a0
C
232
233 // Process thumbnail or create it from the video
234 const thumbnailField = req.files['thumbnailfile']
e8bafea3 235 const thumbnailModel = thumbnailField
65af03a2 236 ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE, false)
3acc5084 237 : await generateVideoMiniature(video, videoFile, ThumbnailType.MINIATURE)
93e1258c 238
ac81d1a0
C
239 // Process preview or create it from the video
240 const previewField = req.files['previewfile']
e8bafea3 241 const previewModel = previewField
65af03a2 242 ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW, false)
3acc5084 243 : await generateVideoMiniature(video, videoFile, ThumbnailType.PREVIEW)
eb080476 244
2186386c 245 // Create the torrent file
d7a25329 246 await createTorrentAndSetInfoHash(video, videoFile)
eb080476 247
5b77537c 248 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
e11f68a3 249 const sequelizeOptions = { transaction: t }
eb080476 250
453e83ea 251 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
e8bafea3 252
3acc5084
C
253 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
254 await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 255
eb080476
C
256 // Do not forget to add video channel information to the created video
257 videoCreated.VideoChannel = res.locals.videoChannel
7920c273 258
eb080476 259 videoFile.videoId = video.id
eb080476 260 await videoFile.save(sequelizeOptions)
e11f68a3
C
261
262 video.VideoFiles = [ videoFile ]
93e1258c 263
2baea0c7 264 // Create tags
2efd32f6 265 if (videoInfo.tags !== undefined) {
3fd3ab2d 266 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
eb080476 267
3fd3ab2d 268 await video.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
269 video.Tags = tagInstances
270 }
271
2baea0c7
C
272 // Schedule an update in the future?
273 if (videoInfo.scheduleUpdate) {
274 await ScheduleVideoUpdateModel.create({
275 videoId: video.id,
276 updateAt: videoInfo.scheduleUpdate.updateAt,
277 privacy: videoInfo.scheduleUpdate.privacy || null
278 }, { transaction: t })
279 }
280
5b77537c 281 await autoBlacklistVideoIfNeeded({
6691c522
C
282 video,
283 user: res.locals.oauth.token.User,
284 isRemote: false,
285 isNew: true,
286 transaction: t
287 })
5b77537c 288 await federateVideoIfNeeded(video, true, t)
eb080476 289
993cef4b 290 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
cadb46d8
C
291 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
292
5b77537c 293 return { videoCreated }
cadb46d8 294 })
94a5ff8a 295
5b77537c 296 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
e8d246d5 297
2186386c 298 if (video.state === VideoState.TO_TRANSCODE) {
d57d1d83 299 await addOptimizeOrMergeAudioJob(videoCreated, videoFile)
94a5ff8a
C
300 }
301
b4055e1c
C
302 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
303
90d4bb81
C
304 return res.json({
305 video: {
306 id: videoCreated.id,
307 uuid: videoCreated.uuid
308 }
c6c0fa6c 309 })
ed04d94f
C
310}
311
eb080476 312async function updateVideo (req: express.Request, res: express.Response) {
453e83ea 313 const videoInstance = res.locals.videoAll
7f4e7c36 314 const videoFieldsSave = videoInstance.toJSON()
80e36cd9 315 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
556ddc31 316 const videoInfoToUpdate: VideoUpdate = req.body
46a6db24 317
22a73cb8
C
318 const wasConfidentialVideo = videoInstance.isConfidential()
319 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
7b1f49de 320
ac81d1a0 321 // Process thumbnail or create it from the video
faa9d434 322 const thumbnailModel = req.files?.['thumbnailfile']
65af03a2 323 ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE, false)
e8bafea3 324 : undefined
ac81d1a0 325
faa9d434 326 const previewModel = req.files?.['previewfile']
65af03a2 327 ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW, false)
e8bafea3 328 : undefined
ac81d1a0 329
eb080476 330 try {
e8d246d5
C
331 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
332 const sequelizeOptions = { transaction: t }
0f320037 333 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 334
6691c522
C
335 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
336 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
337 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
338 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
339 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
340 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
341 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
342 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
343 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
344 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
b718fd22
C
345
346 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
1735c825 347 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
1e74f19a 348 }
349
22a73cb8 350 let isNewVideo = false
2922e048 351 if (videoInfoToUpdate.privacy !== undefined) {
22a73cb8 352 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
2922e048 353
22a73cb8
C
354 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
355 videoInstance.setPrivacy(newPrivacy)
46a6db24 356
22a73cb8
C
357 // Unfederate the video if the new privacy is not compatible with federation
358 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
46a6db24
C
359 await VideoModel.sendDelete(videoInstance, { transaction: t })
360 }
2922e048 361 }
7b1f49de 362
453e83ea 363 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
7b1f49de 364
3acc5084
C
365 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
366 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
e8bafea3 367
0f320037 368 // Video tags update?
2efd32f6 369 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 370 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 371
0f320037
C
372 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
373 videoInstanceUpdated.Tags = tagInstances
eb080476 374 }
7920c273 375
0f320037
C
376 // Video channel update?
377 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 378 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 379 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037 380
22a73cb8 381 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
382 }
383
2baea0c7
C
384 // Schedule an update in the future?
385 if (videoInfoToUpdate.scheduleUpdate) {
386 await ScheduleVideoUpdateModel.upsert({
387 videoId: videoInstanceUpdated.id,
388 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
389 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
390 }, { transaction: t })
e94fc297
C
391 } else if (videoInfoToUpdate.scheduleUpdate === null) {
392 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
393 }
394
6691c522
C
395 await autoBlacklistVideoIfNeeded({
396 video: videoInstanceUpdated,
397 user: res.locals.oauth.token.User,
398 isRemote: false,
399 isNew: false,
400 transaction: t
401 })
402
5b77537c 403 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
6fcd19ba 404
80e36cd9 405 auditLogger.update(
993cef4b 406 getAuditIdFromRes(res),
80e36cd9
AB
407 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
408 oldVideoAuditView
409 )
410 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
e8d246d5
C
411
412 return videoInstanceUpdated
80e36cd9 413 })
e8d246d5 414
22a73cb8 415 if (wasConfidentialVideo) {
5b77537c 416 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
e8d246d5 417 }
b4055e1c 418
7294aab0 419 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
eb080476 420 } catch (err) {
6fcd19ba
C
421 // Force fields we want to update
422 // If the transaction is retried, sequelize will think the object has not changed
423 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 424 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
425
426 throw err
eb080476 427 }
90d4bb81
C
428
429 return res.type('json').status(204).end()
9f10b292 430}
8c308c2b 431
09209296
C
432async function getVideo (req: express.Request, res: express.Response) {
433 // We need more attributes
434 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
b4055e1c 435
89cd1275
C
436 const video = await Hooks.wrapPromiseFun(
437 VideoModel.loadForGetAPI,
453e83ea 438 { id: res.locals.onlyVideoWithRights.id, userId },
b4055e1c
C
439 'filter:api.video.get.result'
440 )
1f3e9fec 441
09209296
C
442 if (video.isOutdated()) {
443 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
04b8c3fb
C
444 }
445
09209296 446 return res.json(video.toFormattedDetailsJSON())
1f3e9fec
C
447}
448
449async function viewVideo (req: express.Request, res: express.Response) {
2c8776fc 450 const videoInstance = res.locals.onlyImmutableVideo
9e167724 451
490b595a 452 const ip = req.ip
0f6acda1 453 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
b5c0e955
C
454 if (exists) {
455 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
456 return res.status(204).end()
457 }
458
6b616860
C
459 await Promise.all([
460 Redis.Instance.addVideoView(videoInstance.id),
461 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
462 ])
b5c0e955 463
a2377d15 464 const serverActor = await getServerActor()
1e7eb25f 465 await sendView(serverActor, videoInstance, undefined)
9e167724 466
b4055e1c
C
467 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
468
1f3e9fec 469 return res.status(204).end()
9f10b292 470}
8c308c2b 471
9567011b 472async function getVideoDescription (req: express.Request, res: express.Response) {
453e83ea 473 const videoInstance = res.locals.videoAll
9567011b
C
474 let description = ''
475
476 if (videoInstance.isOwned()) {
477 description = videoInstance.description
478 } else {
571389d4 479 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
480 }
481
482 return res.json({ description })
483}
484
8319d6ae
RK
485async function getVideoFileMetadata (req: express.Request, res: express.Response) {
486 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
583eb04b 487
8319d6ae
RK
488 return res.json(videoFile.metadata)
489}
490
04b8c3fb 491async function listVideos (req: express.Request, res: express.Response) {
fe987656
C
492 const countVideos = getCountVideos(req)
493
b4055e1c 494 const apiOptions = await Hooks.wrapObject({
48dce1c9
C
495 start: req.query.start,
496 count: req.query.count,
497 sort: req.query.sort,
06a05d5f 498 includeLocalVideos: true,
d525fc39
C
499 categoryOneOf: req.query.categoryOneOf,
500 licenceOneOf: req.query.licenceOneOf,
501 languageOneOf: req.query.languageOneOf,
502 tagsOneOf: req.query.tagsOneOf,
503 tagsAllOf: req.query.tagsAllOf,
504 nsfw: buildNSFWFilter(res, req.query.nsfw),
48dce1c9 505 filter: req.query.filter as VideoFilter,
6e46de09 506 withFiles: false,
fe987656
C
507 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
508 countVideos
b4055e1c
C
509 }, 'filter:api.videos.list.params')
510
89cd1275
C
511 const resultList = await Hooks.wrapPromiseFun(
512 VideoModel.listForApi,
513 apiOptions,
b4055e1c
C
514 'filter:api.videos.list.result'
515 )
eb080476
C
516
517 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 518}
c45f7f84 519
eb080476 520async function removeVideo (req: express.Request, res: express.Response) {
453e83ea 521 const videoInstance = res.locals.videoAll
91f6f169 522
3fd3ab2d 523 await sequelizeTypescript.transaction(async t => {
eb080476 524 await videoInstance.destroy({ transaction: t })
91f6f169 525 })
eb080476 526
993cef4b 527 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 528 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81 529
b4055e1c
C
530 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
531
90d4bb81 532 return res.type('json').status(204).end()
9f10b292 533}