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