]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Move engines outside package.json
[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
e024fd6a
C
251 // Channel has a new content, set as updated
252 await videoCreated.VideoChannel.setAsUpdated(t)
253
5b77537c 254 await autoBlacklistVideoIfNeeded({
6691c522
C
255 video,
256 user: res.locals.oauth.token.User,
257 isRemote: false,
258 isNew: true,
259 transaction: t
260 })
eb080476 261
993cef4b 262 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
452b3bea 263 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
cadb46d8 264
5b77537c 265 return { videoCreated }
cadb46d8 266 })
94a5ff8a 267
d61893f7
C
268 // Create the torrent file in async way because it could be long
269 createTorrentAndSetInfoHashAsync(video, videoFile)
452b3bea 270 .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
d61893f7
C
271 .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
272 .then(refreshedVideo => {
273 if (!refreshedVideo) return
274
275 // Only federate and notify after the torrent creation
276 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
277
278 return retryTransactionWrapper(() => {
279 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
280 })
281 })
452b3bea 282 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
e8d246d5 283
2186386c 284 if (video.state === VideoState.TO_TRANSCODE) {
77d7e851 285 await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User)
94a5ff8a
C
286 }
287
b4055e1c
C
288 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
289
90d4bb81
C
290 return res.json({
291 video: {
292 id: videoCreated.id,
293 uuid: videoCreated.uuid
294 }
c6c0fa6c 295 })
ed04d94f
C
296}
297
eb080476 298async function updateVideo (req: express.Request, res: express.Response) {
453e83ea 299 const videoInstance = res.locals.videoAll
7f4e7c36 300 const videoFieldsSave = videoInstance.toJSON()
80e36cd9 301 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
556ddc31 302 const videoInfoToUpdate: VideoUpdate = req.body
46a6db24 303
22a73cb8
C
304 const wasConfidentialVideo = videoInstance.isConfidential()
305 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
7b1f49de 306
1ef65f4c
C
307 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
308 video: videoInstance,
309 files: req.files,
310 fallback: () => Promise.resolve(undefined),
311 automaticallyGenerated: false
312 })
ac81d1a0 313
eb080476 314 try {
e8d246d5
C
315 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
316 const sequelizeOptions = { transaction: t }
0f320037 317 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 318
6691c522
C
319 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
320 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
321 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
322 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
323 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
324 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
325 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
326 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
327 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
328 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
b718fd22
C
329
330 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
1735c825 331 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
1e74f19a 332 }
333
22a73cb8 334 let isNewVideo = false
2922e048 335 if (videoInfoToUpdate.privacy !== undefined) {
22a73cb8 336 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
2922e048 337
22a73cb8
C
338 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
339 videoInstance.setPrivacy(newPrivacy)
46a6db24 340
22a73cb8
C
341 // Unfederate the video if the new privacy is not compatible with federation
342 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
46a6db24
C
343 await VideoModel.sendDelete(videoInstance, { transaction: t })
344 }
2922e048 345 }
7b1f49de 346
453e83ea 347 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
7b1f49de 348
3acc5084
C
349 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
350 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
e8bafea3 351
0f320037 352 // Video tags update?
6c9c3b7b
C
353 if (videoInfoToUpdate.tags !== undefined) {
354 await setVideoTags({
355 video: videoInstanceUpdated,
356 tags: videoInfoToUpdate.tags,
357 transaction: t
358 })
359 }
7920c273 360
0f320037
C
361 // Video channel update?
362 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 363 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 364 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037 365
22a73cb8 366 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
367 }
368
2baea0c7
C
369 // Schedule an update in the future?
370 if (videoInfoToUpdate.scheduleUpdate) {
371 await ScheduleVideoUpdateModel.upsert({
372 videoId: videoInstanceUpdated.id,
373 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
374 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
375 }, { transaction: t })
e94fc297
C
376 } else if (videoInfoToUpdate.scheduleUpdate === null) {
377 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
378 }
379
6691c522
C
380 await autoBlacklistVideoIfNeeded({
381 video: videoInstanceUpdated,
382 user: res.locals.oauth.token.User,
383 isRemote: false,
384 isNew: false,
385 transaction: t
386 })
387
5b77537c 388 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
6fcd19ba 389
80e36cd9 390 auditLogger.update(
993cef4b 391 getAuditIdFromRes(res),
80e36cd9
AB
392 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
393 oldVideoAuditView
394 )
452b3bea 395 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid))
e8d246d5
C
396
397 return videoInstanceUpdated
80e36cd9 398 })
e8d246d5 399
22a73cb8 400 if (wasConfidentialVideo) {
5b77537c 401 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
e8d246d5 402 }
b4055e1c 403
7294aab0 404 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
eb080476 405 } catch (err) {
6fcd19ba
C
406 // Force fields we want to update
407 // If the transaction is retried, sequelize will think the object has not changed
408 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 409 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
410
411 throw err
eb080476 412 }
90d4bb81 413
2d53be02
RK
414 return res.type('json')
415 .status(HttpStatusCode.NO_CONTENT_204)
416 .end()
9f10b292 417}
8c308c2b 418
09209296
C
419async function getVideo (req: express.Request, res: express.Response) {
420 // We need more attributes
421 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
b4055e1c 422
89cd1275
C
423 const video = await Hooks.wrapPromiseFun(
424 VideoModel.loadForGetAPI,
453e83ea 425 { id: res.locals.onlyVideoWithRights.id, userId },
b4055e1c
C
426 'filter:api.video.get.result'
427 )
1f3e9fec 428
09209296
C
429 if (video.isOutdated()) {
430 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
04b8c3fb
C
431 }
432
09209296 433 return res.json(video.toFormattedDetailsJSON())
1f3e9fec
C
434}
435
436async function viewVideo (req: express.Request, res: express.Response) {
e4bf7856 437 const immutableVideoAttrs = res.locals.onlyImmutableVideo
9e167724 438
490b595a 439 const ip = req.ip
e4bf7856 440 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
b5c0e955 441 if (exists) {
e4bf7856 442 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
2d53be02 443 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
b5c0e955
C
444 }
445
e4bf7856 446 const video = await VideoModel.load(immutableVideoAttrs.id)
b5c0e955 447
e4bf7856
C
448 const promises: Promise<any>[] = [
449 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
450 ]
9e167724 451
e4bf7856 452 let federateView = true
b4055e1c 453
e4bf7856
C
454 // Increment our live manager
455 if (video.isLive && video.isOwned()) {
456 LiveManager.Instance.addViewTo(video.id)
457
458 // Views of our local live will be sent by our live manager
459 federateView = false
460 }
461
462 // Increment our video views cache counter
463 if (!video.isLive) {
464 promises.push(Redis.Instance.addVideoView(video.id))
465 }
466
467 if (federateView) {
468 const serverActor = await getServerActor()
469 promises.push(sendView(serverActor, video, undefined))
470 }
471
472 await Promise.all(promises)
473
474 Hooks.runAction('action:api.video.viewed', { video, ip })
475
2d53be02 476 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
9f10b292 477}
8c308c2b 478
9567011b 479async function getVideoDescription (req: express.Request, res: express.Response) {
453e83ea 480 const videoInstance = res.locals.videoAll
9567011b
C
481 let description = ''
482
483 if (videoInstance.isOwned()) {
484 description = videoInstance.description
485 } else {
571389d4 486 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
487 }
488
489 return res.json({ description })
490}
491
8319d6ae
RK
492async function getVideoFileMetadata (req: express.Request, res: express.Response) {
493 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
583eb04b 494
8319d6ae
RK
495 return res.json(videoFile.metadata)
496}
497
04b8c3fb 498async function listVideos (req: express.Request, res: express.Response) {
1fd61899 499 const query = req.query as VideosCommonQuery
fe987656
C
500 const countVideos = getCountVideos(req)
501
b4055e1c 502 const apiOptions = await Hooks.wrapObject({
1fd61899
C
503 start: query.start,
504 count: query.count,
505 sort: query.sort,
06a05d5f 506 includeLocalVideos: true,
1fd61899
C
507 categoryOneOf: query.categoryOneOf,
508 licenceOneOf: query.licenceOneOf,
509 languageOneOf: query.languageOneOf,
510 tagsOneOf: query.tagsOneOf,
511 tagsAllOf: query.tagsAllOf,
512 nsfw: buildNSFWFilter(res, query.nsfw),
513 isLive: query.isLive,
514 filter: query.filter,
6e46de09 515 withFiles: false,
fe987656
C
516 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
517 countVideos
b4055e1c
C
518 }, 'filter:api.videos.list.params')
519
89cd1275
C
520 const resultList = await Hooks.wrapPromiseFun(
521 VideoModel.listForApi,
522 apiOptions,
b4055e1c
C
523 'filter:api.videos.list.result'
524 )
eb080476
C
525
526 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 527}
c45f7f84 528
eb080476 529async function removeVideo (req: express.Request, res: express.Response) {
453e83ea 530 const videoInstance = res.locals.videoAll
91f6f169 531
3fd3ab2d 532 await sequelizeTypescript.transaction(async t => {
eb080476 533 await videoInstance.destroy({ transaction: t })
91f6f169 534 })
eb080476 535
993cef4b 536 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 537 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81 538
b4055e1c
C
539 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
540
2d53be02
RK
541 return res.type('json')
542 .status(HttpStatusCode.NO_CONTENT_204)
543 .end()
9f10b292 544}
d61893f7
C
545
546async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
547 await createTorrentAndSetInfoHash(video, fileArg)
548
549 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
550 const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
551 // File does not exist anymore, remove the generated torrent
552 if (!refreshedFile) return fileArg.removeTorrent()
553
554 refreshedFile.infoHash = fileArg.infoHash
555 refreshedFile.torrentFilename = fileArg.torrentFilename
556
557 return refreshedFile.save()
558}