]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Fix notification scrollbar color
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
8054669f 2import { move } from 'fs-extra'
3f6b7aa1 3import { extname } from 'path'
8054669f 4import toInt from 'validator/lib/toInt'
8054669f
C
5import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
6import { changeVideoChannelShare } from '@server/lib/activitypub/share'
de94ac86 7import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
7a4ea932 8import { LiveManager } from '@server/lib/live-manager'
77d7e851 9import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
90a8bd30 10import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
8054669f 11import { getServerActor } from '@server/models/application/application'
d61893f7 12import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
1ef65f4c 13import { VideoCreate, VideoState, VideoUpdate } from '../../../../shared'
77d7e851 14import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
8054669f
C
15import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
16import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
d61893f7 17import { resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers/database-utils'
8054669f 18import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils'
daf6e480 19import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
452b3bea 20import { logger, loggerTagsFactory } from '../../../helpers/logger'
8dc8a34e 21import { getFormattedObjects } from '../../../helpers/utils'
8054669f 22import { CONFIG } from '../../../initializers/config'
b345a804
C
23import {
24 DEFAULT_AUDIO_RESOLUTION,
25 MIMETYPES,
26 VIDEO_CATEGORIES,
27 VIDEO_LANGUAGES,
28 VIDEO_LICENCES,
a1587156 29 VIDEO_PRIVACIES
b345a804 30} from '../../../initializers/constants'
8054669f
C
31import { sequelizeTypescript } from '../../../initializers/database'
32import { sendView } from '../../../lib/activitypub/send/send-view'
8dc8a34e 33import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
94a5ff8a 34import { JobQueue } from '../../../lib/job-queue'
8054669f
C
35import { Notifier } from '../../../lib/notifier'
36import { Hooks } from '../../../lib/plugins/hooks'
b5c0e955 37import { Redis } from '../../../lib/redis'
1ef65f4c 38import { generateVideoMiniature } from '../../../lib/thumbnail'
8054669f 39import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
65fcc311 40import {
ac81d1a0 41 asyncMiddleware,
90d4bb81 42 asyncRetryTransactionMiddleware,
ac81d1a0 43 authenticate,
8d427346 44 checkVideoFollowConstraints,
d525fc39 45 commonVideosFiltersValidator,
0883b324 46 optionalAuthenticate,
ac81d1a0
C
47 paginationValidator,
48 setDefaultPagination,
8054669f 49 setDefaultVideosSort,
d57d1d83 50 videoFileMetadataGetValidator,
ac81d1a0 51 videosAddValidator,
09209296 52 videosCustomGetValidator,
ac81d1a0
C
53 videosGetValidator,
54 videosRemoveValidator,
ac81d1a0 55 videosSortValidator,
d57d1d83 56 videosUpdateValidator
65fcc311 57} from '../../../middlewares'
8054669f 58import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
3fd3ab2d
C
59import { VideoModel } from '../../../models/video/video'
60import { VideoFileModel } from '../../../models/video/video-file'
65fcc311 61import { blacklistRouter } from './blacklist'
40e87e9e 62import { videoCaptionsRouter } from './captions'
8054669f 63import { videoCommentRouter } from './comment'
fbad87b0 64import { videoImportsRouter } from './import'
c6c0fa6c 65import { liveRouter } from './live'
8054669f
C
66import { ownershipVideoRouter } from './ownership'
67import { rateVideoRouter } from './rate'
6e46de09 68import { watchingRouter } from './watching'
65fcc311 69
452b3bea 70const lTags = loggerTagsFactory('api', 'video')
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('/', blacklistRouter)
93videosRouter.use('/', rateVideoRouter)
bf1f6508 94videosRouter.use('/', videoCommentRouter)
40e87e9e 95videosRouter.use('/', videoCaptionsRouter)
fbad87b0 96videosRouter.use('/', videoImportsRouter)
74d63469 97videosRouter.use('/', ownershipVideoRouter)
6e46de09 98videosRouter.use('/', watchingRouter)
c6c0fa6c 99videosRouter.use('/', liveRouter)
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,
8054669f 109 setDefaultVideosSort,
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)
8319d6ae
RK
132videosRouter.get('/:id/metadata/:videoFileId',
133 asyncMiddleware(videoFileMetadataGetValidator),
134 asyncMiddleware(getVideoFileMetadata)
135)
65fcc311 136videosRouter.get('/:id',
6e46de09 137 optionalAuthenticate,
09209296 138 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
8d427346 139 asyncMiddleware(checkVideoFollowConstraints),
09209296 140 asyncMiddleware(getVideo)
fbf1134e 141)
1f3e9fec 142videosRouter.post('/:id/views',
2c8776fc 143 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
1f3e9fec
C
144 asyncMiddleware(viewVideo)
145)
198b205c 146
65fcc311
C
147videosRouter.delete('/:id',
148 authenticate,
a2431b7d 149 asyncMiddleware(videosRemoveValidator),
90d4bb81 150 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 151)
198b205c 152
9f10b292 153// ---------------------------------------------------------------------------
c45f7f84 154
65fcc311
C
155export {
156 videosRouter
157}
c45f7f84 158
9f10b292 159// ---------------------------------------------------------------------------
c45f7f84 160
556ddc31 161function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 162 res.json(VIDEO_CATEGORIES)
6e07c3de
C
163}
164
556ddc31 165function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 166 res.json(VIDEO_LICENCES)
6f0c39e2
C
167}
168
556ddc31 169function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 170 res.json(VIDEO_LANGUAGES)
3092476e
C
171}
172
fd45e8f4
C
173function listVideoPrivacies (req: express.Request, res: express.Response) {
174 res.json(VIDEO_PRIVACIES)
175}
176
90d4bb81 177async function addVideo (req: express.Request, res: express.Response) {
bb4ba6d9 178 // Uploading the video could be long
d4132d3f 179 // Set timeout to 10 minutes, as Express's default is 2 minutes
8b917537
C
180 req.setTimeout(1000 * 60 * 10, () => {
181 logger.error('Upload video has timed out.')
2d53be02 182 return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408)
8b917537
C
183 })
184
90d4bb81 185 const videoPhysicalFile = req.files['videofile'][0]
556ddc31 186 const videoInfo: VideoCreate = req.body
9f10b292 187
1ef65f4c
C
188 const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id)
189 videoData.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
190 videoData.duration = videoPhysicalFile['duration'] // duration was added by a previous middleware
7ccddd7b 191
af4ae64f 192 const video = new VideoModel(videoData) as MVideoFullLight
90a8bd30 193 video.VideoChannel = res.locals.videoChannel
de94ac86 194 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
eb080476 195
46a6db24 196 const videoFile = new VideoFileModel({
e11f68a3 197 extname: extname(videoPhysicalFile.filename),
d7a25329 198 size: videoPhysicalFile.size,
8319d6ae 199 videoStreamingPlaylistId: null,
daf6e480 200 metadata: await getMetadataFromFile(videoPhysicalFile.path)
46a6db24 201 })
2186386c 202
ad3405d0
C
203 if (videoFile.isAudio()) {
204 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
205 } else {
536598cf
C
206 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
207 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
536598cf
C
208 }
209
90a8bd30
C
210 videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname)
211
2186386c 212 // Move physical file
d7a25329 213 const destination = getVideoFilePath(video, videoFile)
14e2014a 214 await move(videoPhysicalFile.path, destination)
e3a682a8 215 // This is important in case if there is another attempt in the retry process
d7a25329 216 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
82815eb6 217 videoPhysicalFile.path = destination
ac81d1a0 218
1ef65f4c
C
219 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
220 video,
221 files: req.files,
a35a2279 222 fallback: type => generateVideoMiniature({ video, videoFile, type })
1ef65f4c 223 })
eb080476 224
5b77537c 225 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
e11f68a3 226 const sequelizeOptions = { transaction: t }
eb080476 227
453e83ea 228 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
e8bafea3 229
3acc5084
C
230 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
231 await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 232
eb080476
C
233 // Do not forget to add video channel information to the created video
234 videoCreated.VideoChannel = res.locals.videoChannel
7920c273 235
eb080476 236 videoFile.videoId = video.id
eb080476 237 await videoFile.save(sequelizeOptions)
e11f68a3
C
238
239 video.VideoFiles = [ videoFile ]
93e1258c 240
1ef65f4c 241 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
eb080476 242
2baea0c7
C
243 // Schedule an update in the future?
244 if (videoInfo.scheduleUpdate) {
245 await ScheduleVideoUpdateModel.create({
246 videoId: video.id,
247 updateAt: videoInfo.scheduleUpdate.updateAt,
248 privacy: videoInfo.scheduleUpdate.privacy || null
249 }, { transaction: t })
250 }
251
5b77537c 252 await autoBlacklistVideoIfNeeded({
6691c522
C
253 video,
254 user: res.locals.oauth.token.User,
255 isRemote: false,
256 isNew: true,
257 transaction: t
258 })
eb080476 259
993cef4b 260 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
452b3bea 261 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
cadb46d8 262
5b77537c 263 return { videoCreated }
cadb46d8 264 })
94a5ff8a 265
d61893f7
C
266 // Create the torrent file in async way because it could be long
267 createTorrentAndSetInfoHashAsync(video, videoFile)
452b3bea 268 .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
d61893f7
C
269 .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
270 .then(refreshedVideo => {
271 if (!refreshedVideo) return
272
273 // Only federate and notify after the torrent creation
274 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
275
276 return retryTransactionWrapper(() => {
277 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
278 })
279 })
452b3bea 280 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
e8d246d5 281
2186386c 282 if (video.state === VideoState.TO_TRANSCODE) {
77d7e851 283 await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User)
94a5ff8a
C
284 }
285
b4055e1c
C
286 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
287
90d4bb81
C
288 return res.json({
289 video: {
290 id: videoCreated.id,
291 uuid: videoCreated.uuid
292 }
c6c0fa6c 293 })
ed04d94f
C
294}
295
eb080476 296async function updateVideo (req: express.Request, res: express.Response) {
453e83ea 297 const videoInstance = res.locals.videoAll
7f4e7c36 298 const videoFieldsSave = videoInstance.toJSON()
80e36cd9 299 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
556ddc31 300 const videoInfoToUpdate: VideoUpdate = req.body
46a6db24 301
22a73cb8
C
302 const wasConfidentialVideo = videoInstance.isConfidential()
303 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
7b1f49de 304
1ef65f4c
C
305 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
306 video: videoInstance,
307 files: req.files,
308 fallback: () => Promise.resolve(undefined),
309 automaticallyGenerated: false
310 })
ac81d1a0 311
eb080476 312 try {
e8d246d5
C
313 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
314 const sequelizeOptions = { transaction: t }
0f320037 315 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 316
6691c522
C
317 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
318 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
319 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
320 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
321 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
322 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
323 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
324 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
325 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
326 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
b718fd22
C
327
328 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
1735c825 329 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
1e74f19a 330 }
331
22a73cb8 332 let isNewVideo = false
2922e048 333 if (videoInfoToUpdate.privacy !== undefined) {
22a73cb8 334 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
2922e048 335
22a73cb8
C
336 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
337 videoInstance.setPrivacy(newPrivacy)
46a6db24 338
22a73cb8
C
339 // Unfederate the video if the new privacy is not compatible with federation
340 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
46a6db24
C
341 await VideoModel.sendDelete(videoInstance, { transaction: t })
342 }
2922e048 343 }
7b1f49de 344
453e83ea 345 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
7b1f49de 346
3acc5084
C
347 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
348 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
e8bafea3 349
0f320037 350 // Video tags update?
6c9c3b7b
C
351 if (videoInfoToUpdate.tags !== undefined) {
352 await setVideoTags({
353 video: videoInstanceUpdated,
354 tags: videoInfoToUpdate.tags,
355 transaction: t
356 })
357 }
7920c273 358
0f320037
C
359 // Video channel update?
360 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 361 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 362 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037 363
22a73cb8 364 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
365 }
366
2baea0c7
C
367 // Schedule an update in the future?
368 if (videoInfoToUpdate.scheduleUpdate) {
369 await ScheduleVideoUpdateModel.upsert({
370 videoId: videoInstanceUpdated.id,
371 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
372 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
373 }, { transaction: t })
e94fc297
C
374 } else if (videoInfoToUpdate.scheduleUpdate === null) {
375 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
376 }
377
6691c522
C
378 await autoBlacklistVideoIfNeeded({
379 video: videoInstanceUpdated,
380 user: res.locals.oauth.token.User,
381 isRemote: false,
382 isNew: false,
383 transaction: t
384 })
385
5b77537c 386 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
6fcd19ba 387
80e36cd9 388 auditLogger.update(
993cef4b 389 getAuditIdFromRes(res),
80e36cd9
AB
390 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
391 oldVideoAuditView
392 )
452b3bea 393 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid))
e8d246d5
C
394
395 return videoInstanceUpdated
80e36cd9 396 })
e8d246d5 397
22a73cb8 398 if (wasConfidentialVideo) {
5b77537c 399 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
e8d246d5 400 }
b4055e1c 401
7294aab0 402 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
eb080476 403 } catch (err) {
6fcd19ba
C
404 // Force fields we want to update
405 // If the transaction is retried, sequelize will think the object has not changed
406 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 407 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
408
409 throw err
eb080476 410 }
90d4bb81 411
2d53be02
RK
412 return res.type('json')
413 .status(HttpStatusCode.NO_CONTENT_204)
414 .end()
9f10b292 415}
8c308c2b 416
09209296
C
417async function getVideo (req: express.Request, res: express.Response) {
418 // We need more attributes
419 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
b4055e1c 420
89cd1275
C
421 const video = await Hooks.wrapPromiseFun(
422 VideoModel.loadForGetAPI,
453e83ea 423 { id: res.locals.onlyVideoWithRights.id, userId },
b4055e1c
C
424 'filter:api.video.get.result'
425 )
1f3e9fec 426
09209296
C
427 if (video.isOutdated()) {
428 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
04b8c3fb
C
429 }
430
09209296 431 return res.json(video.toFormattedDetailsJSON())
1f3e9fec
C
432}
433
434async function viewVideo (req: express.Request, res: express.Response) {
e4bf7856 435 const immutableVideoAttrs = res.locals.onlyImmutableVideo
9e167724 436
490b595a 437 const ip = req.ip
e4bf7856 438 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
b5c0e955 439 if (exists) {
e4bf7856 440 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
2d53be02 441 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
b5c0e955
C
442 }
443
e4bf7856 444 const video = await VideoModel.load(immutableVideoAttrs.id)
b5c0e955 445
e4bf7856
C
446 const promises: Promise<any>[] = [
447 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
448 ]
9e167724 449
e4bf7856 450 let federateView = true
b4055e1c 451
e4bf7856
C
452 // Increment our live manager
453 if (video.isLive && video.isOwned()) {
454 LiveManager.Instance.addViewTo(video.id)
455
456 // Views of our local live will be sent by our live manager
457 federateView = false
458 }
459
460 // Increment our video views cache counter
461 if (!video.isLive) {
462 promises.push(Redis.Instance.addVideoView(video.id))
463 }
464
465 if (federateView) {
466 const serverActor = await getServerActor()
467 promises.push(sendView(serverActor, video, undefined))
468 }
469
470 await Promise.all(promises)
471
472 Hooks.runAction('action:api.video.viewed', { video, ip })
473
2d53be02 474 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
9f10b292 475}
8c308c2b 476
9567011b 477async function getVideoDescription (req: express.Request, res: express.Response) {
453e83ea 478 const videoInstance = res.locals.videoAll
9567011b
C
479 let description = ''
480
481 if (videoInstance.isOwned()) {
482 description = videoInstance.description
483 } else {
571389d4 484 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
485 }
486
487 return res.json({ description })
488}
489
8319d6ae
RK
490async function getVideoFileMetadata (req: express.Request, res: express.Response) {
491 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
583eb04b 492
8319d6ae
RK
493 return res.json(videoFile.metadata)
494}
495
04b8c3fb 496async function listVideos (req: express.Request, res: express.Response) {
fe987656
C
497 const countVideos = getCountVideos(req)
498
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,
fe987656
C
512 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
513 countVideos
b4055e1c
C
514 }, 'filter:api.videos.list.params')
515
89cd1275
C
516 const resultList = await Hooks.wrapPromiseFun(
517 VideoModel.listForApi,
518 apiOptions,
b4055e1c
C
519 'filter:api.videos.list.result'
520 )
eb080476
C
521
522 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 523}
c45f7f84 524
eb080476 525async function removeVideo (req: express.Request, res: express.Response) {
453e83ea 526 const videoInstance = res.locals.videoAll
91f6f169 527
3fd3ab2d 528 await sequelizeTypescript.transaction(async t => {
eb080476 529 await videoInstance.destroy({ transaction: t })
91f6f169 530 })
eb080476 531
993cef4b 532 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 533 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81 534
b4055e1c
C
535 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
536
2d53be02
RK
537 return res.type('json')
538 .status(HttpStatusCode.NO_CONTENT_204)
539 .end()
9f10b292 540}
d61893f7
C
541
542async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
543 await createTorrentAndSetInfoHash(video, fileArg)
544
545 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
546 const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
547 // File does not exist anymore, remove the generated torrent
548 if (!refreshedFile) return fileArg.removeTorrent()
549
550 refreshedFile.infoHash = fileArg.infoHash
551 refreshedFile.torrentFilename = fileArg.torrentFilename
552
553 return refreshedFile.save()
554}