]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Automatically update playlist thumbnails
[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
65af03a2 226 ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE, false)
3acc5084 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
65af03a2 232 ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW, false)
3acc5084 233 : await generateVideoMiniature(video, videoFile, ThumbnailType.PREVIEW)
eb080476 234
2186386c 235 // Create the torrent file
ac81d1a0 236 await video.createTorrentAndSetInfoHash(videoFile)
eb080476 237
5b77537c 238 const { videoCreated } = 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
5b77537c 271 await autoBlacklistVideoIfNeeded({
6691c522
C
272 video,
273 user: res.locals.oauth.token.User,
274 isRemote: false,
275 isNew: true,
276 transaction: t
277 })
5b77537c 278 await federateVideoIfNeeded(video, true, t)
eb080476 279
993cef4b 280 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
cadb46d8
C
281 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
282
5b77537c 283 return { videoCreated }
cadb46d8 284 })
94a5ff8a 285
5b77537c 286 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
e8d246d5 287
2186386c 288 if (video.state === VideoState.TO_TRANSCODE) {
94a5ff8a 289 // Put uuid because we don't have id auto incremented for now
536598cf
C
290 let dataInput: VideoTranscodingPayload
291
292 if (videoFile.isAudio()) {
293 dataInput = {
294 type: 'merge-audio' as 'merge-audio',
295 resolution: DEFAULT_AUDIO_RESOLUTION,
296 videoUUID: videoCreated.uuid,
297 isNewVideo: true
298 }
299 } else {
300 dataInput = {
301 type: 'optimize' as 'optimize',
302 videoUUID: videoCreated.uuid,
303 isNewVideo: true
304 }
94a5ff8a
C
305 }
306
a0327eed 307 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
94a5ff8a
C
308 }
309
b4055e1c
C
310 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
311
90d4bb81
C
312 return res.json({
313 video: {
314 id: videoCreated.id,
315 uuid: videoCreated.uuid
316 }
317 }).end()
ed04d94f
C
318}
319
eb080476 320async function updateVideo (req: express.Request, res: express.Response) {
dae86118 321 const videoInstance = res.locals.video
7f4e7c36 322 const videoFieldsSave = videoInstance.toJSON()
80e36cd9 323 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
556ddc31 324 const videoInfoToUpdate: VideoUpdate = req.body
46a6db24 325
fd45e8f4 326 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
46a6db24 327 const wasNotPrivateVideo = videoInstance.privacy !== VideoPrivacy.PRIVATE
cef534ed 328 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
7b1f49de 329
ac81d1a0 330 // Process thumbnail or create it from the video
e8bafea3 331 const thumbnailModel = req.files && req.files['thumbnailfile']
65af03a2 332 ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE, false)
e8bafea3 333 : undefined
ac81d1a0 334
e8bafea3 335 const previewModel = req.files && req.files['previewfile']
65af03a2 336 ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW, false)
e8bafea3 337 : undefined
ac81d1a0 338
eb080476 339 try {
e8d246d5
C
340 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
341 const sequelizeOptions = { transaction: t }
0f320037 342 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 343
6691c522
C
344 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
345 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
346 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
347 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
348 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
349 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
350 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
351 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
352 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
353 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
b718fd22
C
354
355 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
1735c825 356 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
1e74f19a 357 }
358
2922e048
JLB
359 if (videoInfoToUpdate.privacy !== undefined) {
360 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
1735c825 361 videoInstance.privacy = newPrivacy
2922e048 362
46a6db24 363 // The video was private, and is not anymore -> publish it
2922e048 364 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
1735c825 365 videoInstance.publishedAt = new Date()
2922e048 366 }
46a6db24
C
367
368 // The video was not private, but now it is -> we need to unfederate it
369 if (wasNotPrivateVideo === true && newPrivacy === VideoPrivacy.PRIVATE) {
370 await VideoModel.sendDelete(videoInstance, { transaction: t })
371 }
2922e048 372 }
7b1f49de 373
54141398 374 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 375
3acc5084
C
376 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
377 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
e8bafea3 378
0f320037 379 // Video tags update?
2efd32f6 380 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 381 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 382
0f320037
C
383 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
384 videoInstanceUpdated.Tags = tagInstances
eb080476 385 }
7920c273 386
0f320037
C
387 // Video channel update?
388 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 389 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 390 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037
C
391
392 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
393 }
394
2baea0c7
C
395 // Schedule an update in the future?
396 if (videoInfoToUpdate.scheduleUpdate) {
397 await ScheduleVideoUpdateModel.upsert({
398 videoId: videoInstanceUpdated.id,
399 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
400 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
401 }, { transaction: t })
e94fc297
C
402 } else if (videoInfoToUpdate.scheduleUpdate === null) {
403 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
404 }
405
6691c522
C
406 await autoBlacklistVideoIfNeeded({
407 video: videoInstanceUpdated,
408 user: res.locals.oauth.token.User,
409 isRemote: false,
410 isNew: false,
411 transaction: t
412 })
413
2186386c 414 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
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
C
426
427 if (wasUnlistedVideo || wasPrivateVideo) {
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,
450 { id: res.locals.video.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) {
818f7987 463 const videoInstance = res.locals.video
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
C
485async function getVideoDescription (req: express.Request, res: express.Response) {
486 const videoInstance = res.locals.video
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) {
b4055e1c 499 const apiOptions = await Hooks.wrapObject({
48dce1c9
C
500 start: req.query.start,
501 count: req.query.count,
502 sort: req.query.sort,
06a05d5f 503 includeLocalVideos: true,
d525fc39
C
504 categoryOneOf: req.query.categoryOneOf,
505 licenceOneOf: req.query.licenceOneOf,
506 languageOneOf: req.query.languageOneOf,
507 tagsOneOf: req.query.tagsOneOf,
508 tagsAllOf: req.query.tagsAllOf,
509 nsfw: buildNSFWFilter(res, req.query.nsfw),
48dce1c9 510 filter: req.query.filter as VideoFilter,
6e46de09 511 withFiles: false,
7ad9b984 512 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
b4055e1c
C
513 }, 'filter:api.videos.list.params')
514
89cd1275
C
515 const resultList = await Hooks.wrapPromiseFun(
516 VideoModel.listForApi,
517 apiOptions,
b4055e1c
C
518 'filter:api.videos.list.result'
519 )
eb080476
C
520
521 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 522}
c45f7f84 523
eb080476 524async function removeVideo (req: express.Request, res: express.Response) {
dae86118 525 const videoInstance = res.locals.video
91f6f169 526
3fd3ab2d 527 await sequelizeTypescript.transaction(async t => {
eb080476 528 await videoInstance.destroy({ transaction: t })
91f6f169 529 })
eb080476 530
993cef4b 531 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 532 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81 533
b4055e1c
C
534 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
535
90d4bb81 536 return res.type('json').status(204).end()
9f10b292 537}