]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Add audio-only option to transcoders and player
[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'
d7a25329
C
67import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
68import { getVideoFilename, 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
C
137videosRouter.post('/:id/views',
138 asyncMiddleware(videosGetValidator),
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
a0327eed 310 await JobQueue.Instance.createJob({ 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
fd45e8f4 329 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
46a6db24 330 const wasNotPrivateVideo = videoInstance.privacy !== VideoPrivacy.PRIVATE
cef534ed 331 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
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
2922e048
JLB
362 if (videoInfoToUpdate.privacy !== undefined) {
363 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
1735c825 364 videoInstance.privacy = newPrivacy
2922e048 365
46a6db24 366 // The video was private, and is not anymore -> publish it
2922e048 367 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
1735c825 368 videoInstance.publishedAt = new Date()
2922e048 369 }
46a6db24
C
370
371 // The video was not private, but now it is -> we need to unfederate it
372 if (wasNotPrivateVideo === true && newPrivacy === VideoPrivacy.PRIVATE) {
373 await VideoModel.sendDelete(videoInstance, { transaction: t })
374 }
2922e048 375 }
7b1f49de 376
453e83ea 377 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
7b1f49de 378
3acc5084
C
379 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
380 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
e8bafea3 381
0f320037 382 // Video tags update?
2efd32f6 383 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 384 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 385
0f320037
C
386 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
387 videoInstanceUpdated.Tags = tagInstances
eb080476 388 }
7920c273 389
0f320037
C
390 // Video channel update?
391 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 392 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 393 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037
C
394
395 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
396 }
397
2baea0c7
C
398 // Schedule an update in the future?
399 if (videoInfoToUpdate.scheduleUpdate) {
400 await ScheduleVideoUpdateModel.upsert({
401 videoId: videoInstanceUpdated.id,
402 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
403 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
404 }, { transaction: t })
e94fc297
C
405 } else if (videoInfoToUpdate.scheduleUpdate === null) {
406 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
407 }
408
6691c522
C
409 await autoBlacklistVideoIfNeeded({
410 video: videoInstanceUpdated,
411 user: res.locals.oauth.token.User,
412 isRemote: false,
413 isNew: false,
414 transaction: t
415 })
416
2186386c 417 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
5b77537c 418 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
6fcd19ba 419
80e36cd9 420 auditLogger.update(
993cef4b 421 getAuditIdFromRes(res),
80e36cd9
AB
422 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
423 oldVideoAuditView
424 )
425 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
e8d246d5
C
426
427 return videoInstanceUpdated
80e36cd9 428 })
e8d246d5
C
429
430 if (wasUnlistedVideo || wasPrivateVideo) {
5b77537c 431 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
e8d246d5 432 }
b4055e1c
C
433
434 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated })
eb080476 435 } catch (err) {
6fcd19ba
C
436 // Force fields we want to update
437 // If the transaction is retried, sequelize will think the object has not changed
438 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 439 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
440
441 throw err
eb080476 442 }
90d4bb81
C
443
444 return res.type('json').status(204).end()
9f10b292 445}
8c308c2b 446
09209296
C
447async function getVideo (req: express.Request, res: express.Response) {
448 // We need more attributes
449 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
b4055e1c 450
89cd1275
C
451 const video = await Hooks.wrapPromiseFun(
452 VideoModel.loadForGetAPI,
453e83ea 453 { id: res.locals.onlyVideoWithRights.id, userId },
b4055e1c
C
454 'filter:api.video.get.result'
455 )
1f3e9fec 456
09209296
C
457 if (video.isOutdated()) {
458 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
459 .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
04b8c3fb
C
460 }
461
09209296 462 return res.json(video.toFormattedDetailsJSON())
1f3e9fec
C
463}
464
465async function viewVideo (req: express.Request, res: express.Response) {
453e83ea 466 const videoInstance = res.locals.videoAll
9e167724 467
490b595a 468 const ip = req.ip
0f6acda1 469 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
b5c0e955
C
470 if (exists) {
471 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
472 return res.status(204).end()
473 }
474
6b616860
C
475 await Promise.all([
476 Redis.Instance.addVideoView(videoInstance.id),
477 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
478 ])
b5c0e955 479
a2377d15 480 const serverActor = await getServerActor()
1e7eb25f 481 await sendView(serverActor, videoInstance, undefined)
9e167724 482
b4055e1c
C
483 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
484
1f3e9fec 485 return res.status(204).end()
9f10b292 486}
8c308c2b 487
9567011b 488async function getVideoDescription (req: express.Request, res: express.Response) {
453e83ea 489 const videoInstance = res.locals.videoAll
9567011b
C
490 let description = ''
491
492 if (videoInstance.isOwned()) {
493 description = videoInstance.description
494 } else {
571389d4 495 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
496 }
497
498 return res.json({ description })
499}
500
04b8c3fb 501async function listVideos (req: express.Request, res: express.Response) {
b4055e1c 502 const apiOptions = await Hooks.wrapObject({
48dce1c9
C
503 start: req.query.start,
504 count: req.query.count,
505 sort: req.query.sort,
06a05d5f 506 includeLocalVideos: true,
d525fc39
C
507 categoryOneOf: req.query.categoryOneOf,
508 licenceOneOf: req.query.licenceOneOf,
509 languageOneOf: req.query.languageOneOf,
510 tagsOneOf: req.query.tagsOneOf,
511 tagsAllOf: req.query.tagsAllOf,
512 nsfw: buildNSFWFilter(res, req.query.nsfw),
48dce1c9 513 filter: req.query.filter as VideoFilter,
6e46de09 514 withFiles: false,
7ad9b984 515 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
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}