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