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