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