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