]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Fix separate SQL query for video get
[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 4import toInt from 'validator/lib/toInt'
8054669f
C
5import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
6import { changeVideoChannelShare } from '@server/lib/activitypub/share'
de94ac86 7import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
7a4ea932 8import { LiveManager } from '@server/lib/live-manager'
77d7e851 9import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
90a8bd30 10import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
8054669f 11import { getServerActor } from '@server/models/application/application'
053aed43 12import { MVideoFullLight } from '@server/types/models'
1ef65f4c 13import { VideoCreate, VideoState, VideoUpdate } from '../../../../shared'
77d7e851 14import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
8054669f
C
15import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
16import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
17import { resetSequelizeInstance } from '../../../helpers/database-utils'
18import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils'
daf6e480 19import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
da854ddd 20import { logger } from '../../../helpers/logger'
8dc8a34e 21import { getFormattedObjects } from '../../../helpers/utils'
8054669f 22import { CONFIG } from '../../../initializers/config'
b345a804
C
23import {
24 DEFAULT_AUDIO_RESOLUTION,
25 MIMETYPES,
26 VIDEO_CATEGORIES,
27 VIDEO_LANGUAGES,
28 VIDEO_LICENCES,
a1587156 29 VIDEO_PRIVACIES
b345a804 30} from '../../../initializers/constants'
8054669f
C
31import { sequelizeTypescript } from '../../../initializers/database'
32import { sendView } from '../../../lib/activitypub/send/send-view'
8dc8a34e 33import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
94a5ff8a 34import { JobQueue } from '../../../lib/job-queue'
8054669f
C
35import { Notifier } from '../../../lib/notifier'
36import { Hooks } from '../../../lib/plugins/hooks'
b5c0e955 37import { Redis } from '../../../lib/redis'
1ef65f4c 38import { generateVideoMiniature } from '../../../lib/thumbnail'
8054669f 39import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
65fcc311 40import {
ac81d1a0 41 asyncMiddleware,
90d4bb81 42 asyncRetryTransactionMiddleware,
ac81d1a0 43 authenticate,
8d427346 44 checkVideoFollowConstraints,
d525fc39 45 commonVideosFiltersValidator,
0883b324 46 optionalAuthenticate,
ac81d1a0
C
47 paginationValidator,
48 setDefaultPagination,
8054669f 49 setDefaultVideosSort,
d57d1d83 50 videoFileMetadataGetValidator,
ac81d1a0 51 videosAddValidator,
09209296 52 videosCustomGetValidator,
ac81d1a0
C
53 videosGetValidator,
54 videosRemoveValidator,
ac81d1a0 55 videosSortValidator,
d57d1d83 56 videosUpdateValidator
65fcc311 57} from '../../../middlewares'
8054669f 58import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
3fd3ab2d
C
59import { VideoModel } from '../../../models/video/video'
60import { VideoFileModel } from '../../../models/video/video-file'
65fcc311 61import { blacklistRouter } from './blacklist'
40e87e9e 62import { videoCaptionsRouter } from './captions'
8054669f 63import { videoCommentRouter } from './comment'
fbad87b0 64import { videoImportsRouter } from './import'
c6c0fa6c 65import { liveRouter } from './live'
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('/', blacklistRouter)
92videosRouter.use('/', rateVideoRouter)
bf1f6508 93videosRouter.use('/', videoCommentRouter)
40e87e9e 94videosRouter.use('/', videoCaptionsRouter)
fbad87b0 95videosRouter.use('/', videoImportsRouter)
74d63469 96videosRouter.use('/', ownershipVideoRouter)
6e46de09 97videosRouter.use('/', watchingRouter)
c6c0fa6c 98videosRouter.use('/', liveRouter)
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) {
bb4ba6d9 177 // Uploading the video could be long
d4132d3f 178 // Set timeout to 10 minutes, as Express's default is 2 minutes
8b917537
C
179 req.setTimeout(1000 * 60 * 10, () => {
180 logger.error('Upload video has timed out.')
2d53be02 181 return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408)
8b917537
C
182 })
183
90d4bb81 184 const videoPhysicalFile = req.files['videofile'][0]
556ddc31 185 const videoInfo: VideoCreate = req.body
9f10b292 186
1ef65f4c
C
187 const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id)
188 videoData.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
189 videoData.duration = videoPhysicalFile['duration'] // duration was added by a previous middleware
7ccddd7b 190
af4ae64f 191 const video = new VideoModel(videoData) as MVideoFullLight
90a8bd30 192 video.VideoChannel = res.locals.videoChannel
de94ac86 193 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
eb080476 194
46a6db24 195 const videoFile = new VideoFileModel({
e11f68a3 196 extname: extname(videoPhysicalFile.filename),
d7a25329 197 size: videoPhysicalFile.size,
8319d6ae 198 videoStreamingPlaylistId: null,
daf6e480 199 metadata: await getMetadataFromFile(videoPhysicalFile.path)
46a6db24 200 })
2186386c 201
ad3405d0
C
202 if (videoFile.isAudio()) {
203 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
204 } else {
536598cf
C
205 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
206 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
536598cf
C
207 }
208
90a8bd30
C
209 videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname)
210
2186386c 211 // Move physical file
d7a25329 212 const destination = getVideoFilePath(video, videoFile)
14e2014a 213 await move(videoPhysicalFile.path, destination)
e3a682a8 214 // This is important in case if there is another attempt in the retry process
d7a25329 215 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
82815eb6 216 videoPhysicalFile.path = destination
ac81d1a0 217
1ef65f4c
C
218 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
219 video,
220 files: req.files,
a35a2279 221 fallback: type => generateVideoMiniature({ video, videoFile, type })
1ef65f4c 222 })
eb080476 223
2186386c 224 // Create the torrent file
8efc27bf 225 await createTorrentAndSetInfoHash(video, videoFile)
eb080476 226
5b77537c 227 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
e11f68a3 228 const sequelizeOptions = { transaction: t }
eb080476 229
453e83ea 230 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
e8bafea3 231
3acc5084
C
232 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
233 await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 234
eb080476
C
235 // Do not forget to add video channel information to the created video
236 videoCreated.VideoChannel = res.locals.videoChannel
7920c273 237
eb080476 238 videoFile.videoId = video.id
eb080476 239 await videoFile.save(sequelizeOptions)
e11f68a3
C
240
241 video.VideoFiles = [ videoFile ]
93e1258c 242
1ef65f4c 243 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
eb080476 244
2baea0c7
C
245 // Schedule an update in the future?
246 if (videoInfo.scheduleUpdate) {
247 await ScheduleVideoUpdateModel.create({
248 videoId: video.id,
249 updateAt: videoInfo.scheduleUpdate.updateAt,
250 privacy: videoInfo.scheduleUpdate.privacy || null
251 }, { transaction: t })
252 }
253
5b77537c 254 await autoBlacklistVideoIfNeeded({
6691c522
C
255 video,
256 user: res.locals.oauth.token.User,
257 isRemote: false,
258 isNew: true,
259 transaction: t
260 })
5b77537c 261 await federateVideoIfNeeded(video, true, t)
eb080476 262
993cef4b 263 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
cadb46d8
C
264 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
265
5b77537c 266 return { videoCreated }
cadb46d8 267 })
94a5ff8a 268
5b77537c 269 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
e8d246d5 270
2186386c 271 if (video.state === VideoState.TO_TRANSCODE) {
77d7e851 272 await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User)
94a5ff8a
C
273 }
274
b4055e1c
C
275 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
276
90d4bb81
C
277 return res.json({
278 video: {
279 id: videoCreated.id,
280 uuid: videoCreated.uuid
281 }
c6c0fa6c 282 })
ed04d94f
C
283}
284
eb080476 285async function updateVideo (req: express.Request, res: express.Response) {
453e83ea 286 const videoInstance = res.locals.videoAll
7f4e7c36 287 const videoFieldsSave = videoInstance.toJSON()
80e36cd9 288 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
556ddc31 289 const videoInfoToUpdate: VideoUpdate = req.body
46a6db24 290
22a73cb8
C
291 const wasConfidentialVideo = videoInstance.isConfidential()
292 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
7b1f49de 293
1ef65f4c
C
294 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
295 video: videoInstance,
296 files: req.files,
297 fallback: () => Promise.resolve(undefined),
298 automaticallyGenerated: false
299 })
ac81d1a0 300
eb080476 301 try {
e8d246d5
C
302 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
303 const sequelizeOptions = { transaction: t }
0f320037 304 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 305
6691c522
C
306 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
307 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
308 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
309 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
310 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
311 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
312 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
313 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
314 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
315 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
b718fd22
C
316
317 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
1735c825 318 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
1e74f19a 319 }
320
22a73cb8 321 let isNewVideo = false
2922e048 322 if (videoInfoToUpdate.privacy !== undefined) {
22a73cb8 323 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
2922e048 324
22a73cb8
C
325 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
326 videoInstance.setPrivacy(newPrivacy)
46a6db24 327
22a73cb8
C
328 // Unfederate the video if the new privacy is not compatible with federation
329 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
46a6db24
C
330 await VideoModel.sendDelete(videoInstance, { transaction: t })
331 }
2922e048 332 }
7b1f49de 333
453e83ea 334 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
7b1f49de 335
3acc5084
C
336 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
337 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
e8bafea3 338
0f320037 339 // Video tags update?
1ef65f4c
C
340 await setVideoTags({
341 video: videoInstanceUpdated,
342 tags: videoInfoToUpdate.tags,
343 transaction: t,
344 defaultValue: videoInstanceUpdated.Tags
345 })
7920c273 346
0f320037
C
347 // Video channel update?
348 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 349 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 350 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037 351
22a73cb8 352 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
353 }
354
2baea0c7
C
355 // Schedule an update in the future?
356 if (videoInfoToUpdate.scheduleUpdate) {
357 await ScheduleVideoUpdateModel.upsert({
358 videoId: videoInstanceUpdated.id,
359 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
360 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
361 }, { transaction: t })
e94fc297
C
362 } else if (videoInfoToUpdate.scheduleUpdate === null) {
363 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
364 }
365
6691c522
C
366 await autoBlacklistVideoIfNeeded({
367 video: videoInstanceUpdated,
368 user: res.locals.oauth.token.User,
369 isRemote: false,
370 isNew: false,
371 transaction: t
372 })
373
5b77537c 374 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
6fcd19ba 375
80e36cd9 376 auditLogger.update(
993cef4b 377 getAuditIdFromRes(res),
80e36cd9
AB
378 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
379 oldVideoAuditView
380 )
381 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
e8d246d5
C
382
383 return videoInstanceUpdated
80e36cd9 384 })
e8d246d5 385
22a73cb8 386 if (wasConfidentialVideo) {
5b77537c 387 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
e8d246d5 388 }
b4055e1c 389
7294aab0 390 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
eb080476 391 } catch (err) {
6fcd19ba
C
392 // Force fields we want to update
393 // If the transaction is retried, sequelize will think the object has not changed
394 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 395 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
396
397 throw err
eb080476 398 }
90d4bb81 399
2d53be02
RK
400 return res.type('json')
401 .status(HttpStatusCode.NO_CONTENT_204)
402 .end()
9f10b292 403}
8c308c2b 404
09209296
C
405async function getVideo (req: express.Request, res: express.Response) {
406 // We need more attributes
407 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
b4055e1c 408
89cd1275
C
409 const video = await Hooks.wrapPromiseFun(
410 VideoModel.loadForGetAPI,
453e83ea 411 { id: res.locals.onlyVideoWithRights.id, userId },
b4055e1c
C
412 'filter:api.video.get.result'
413 )
1f3e9fec 414
09209296
C
415 if (video.isOutdated()) {
416 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
04b8c3fb
C
417 }
418
09209296 419 return res.json(video.toFormattedDetailsJSON())
1f3e9fec
C
420}
421
422async function viewVideo (req: express.Request, res: express.Response) {
e4bf7856 423 const immutableVideoAttrs = res.locals.onlyImmutableVideo
9e167724 424
490b595a 425 const ip = req.ip
e4bf7856 426 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
b5c0e955 427 if (exists) {
e4bf7856 428 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
2d53be02 429 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
b5c0e955
C
430 }
431
e4bf7856 432 const video = await VideoModel.load(immutableVideoAttrs.id)
b5c0e955 433
e4bf7856
C
434 const promises: Promise<any>[] = [
435 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
436 ]
9e167724 437
e4bf7856 438 let federateView = true
b4055e1c 439
e4bf7856
C
440 // Increment our live manager
441 if (video.isLive && video.isOwned()) {
442 LiveManager.Instance.addViewTo(video.id)
443
444 // Views of our local live will be sent by our live manager
445 federateView = false
446 }
447
448 // Increment our video views cache counter
449 if (!video.isLive) {
450 promises.push(Redis.Instance.addVideoView(video.id))
451 }
452
453 if (federateView) {
454 const serverActor = await getServerActor()
455 promises.push(sendView(serverActor, video, undefined))
456 }
457
458 await Promise.all(promises)
459
460 Hooks.runAction('action:api.video.viewed', { video, ip })
461
2d53be02 462 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
9f10b292 463}
8c308c2b 464
9567011b 465async function getVideoDescription (req: express.Request, res: express.Response) {
453e83ea 466 const videoInstance = res.locals.videoAll
9567011b
C
467 let description = ''
468
469 if (videoInstance.isOwned()) {
470 description = videoInstance.description
471 } else {
571389d4 472 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
473 }
474
475 return res.json({ description })
476}
477
8319d6ae
RK
478async function getVideoFileMetadata (req: express.Request, res: express.Response) {
479 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
583eb04b 480
8319d6ae
RK
481 return res.json(videoFile.metadata)
482}
483
04b8c3fb 484async function listVideos (req: express.Request, res: express.Response) {
fe987656
C
485 const countVideos = getCountVideos(req)
486
b4055e1c 487 const apiOptions = await Hooks.wrapObject({
48dce1c9
C
488 start: req.query.start,
489 count: req.query.count,
490 sort: req.query.sort,
06a05d5f 491 includeLocalVideos: true,
d525fc39
C
492 categoryOneOf: req.query.categoryOneOf,
493 licenceOneOf: req.query.licenceOneOf,
494 languageOneOf: req.query.languageOneOf,
495 tagsOneOf: req.query.tagsOneOf,
496 tagsAllOf: req.query.tagsAllOf,
497 nsfw: buildNSFWFilter(res, req.query.nsfw),
48dce1c9 498 filter: req.query.filter as VideoFilter,
6e46de09 499 withFiles: false,
fe987656
C
500 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
501 countVideos
b4055e1c
C
502 }, 'filter:api.videos.list.params')
503
89cd1275
C
504 const resultList = await Hooks.wrapPromiseFun(
505 VideoModel.listForApi,
506 apiOptions,
b4055e1c
C
507 'filter:api.videos.list.result'
508 )
eb080476
C
509
510 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 511}
c45f7f84 512
eb080476 513async function removeVideo (req: express.Request, res: express.Response) {
453e83ea 514 const videoInstance = res.locals.videoAll
91f6f169 515
3fd3ab2d 516 await sequelizeTypescript.transaction(async t => {
eb080476 517 await videoInstance.destroy({ transaction: t })
91f6f169 518 })
eb080476 519
993cef4b 520 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 521 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81 522
b4055e1c
C
523 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
524
2d53be02
RK
525 return res.type('json')
526 .status(HttpStatusCode.NO_CONTENT_204)
527 .end()
9f10b292 528}