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