]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/middlewares/videos.ts
Refactor middleware helpers
[github/Chocobozzz/PeerTube.git] / server / helpers / middlewares / videos.ts
CommitLineData
3e753302
C
1import { Response } from 'express'
2import { fetchVideo, VideoFetchType } from '../video'
3import { UserModel } from '../../models/account/user'
4import { UserRight } from '../../../shared/models/users'
5import { VideoChannelModel } from '../../models/video/video-channel'
6import { VideoModel } from '../../models/video/video'
7
8async function doesVideoExist (id: number | string, res: Response, fetchType: VideoFetchType = 'all') {
9 const userId = res.locals.oauth ? res.locals.oauth.token.User.id : undefined
10
11 const video = await fetchVideo(id, fetchType, userId)
12
13 if (video === null) {
14 res.status(404)
15 .json({ error: 'Video not found' })
16 .end()
17
18 return false
19 }
20
21 if (fetchType !== 'none') res.locals.video = video
22 return true
23}
24
25async function doesVideoChannelOfAccountExist (channelId: number, user: UserModel, res: Response) {
26 if (user.hasRight(UserRight.UPDATE_ANY_VIDEO) === true) {
27 const videoChannel = await VideoChannelModel.loadAndPopulateAccount(channelId)
28 if (videoChannel === null) {
29 res.status(400)
30 .json({ error: 'Unknown video `video channel` on this instance.' })
31 .end()
32
33 return false
34 }
35
36 res.locals.videoChannel = videoChannel
37 return true
38 }
39
40 const videoChannel = await VideoChannelModel.loadByIdAndAccount(channelId, user.Account.id)
41 if (videoChannel === null) {
42 res.status(400)
43 .json({ error: 'Unknown video `video channel` for this account.' })
44 .end()
45
46 return false
47 }
48
49 res.locals.videoChannel = videoChannel
50 return true
51}
52
53function checkUserCanManageVideo (user: UserModel, video: VideoModel, right: UserRight, res: Response) {
54 // Retrieve the user who did the request
55 if (video.isOwned() === false) {
56 res.status(403)
57 .json({ error: 'Cannot manage a video of another server.' })
58 .end()
59 return false
60 }
61
62 // Check if the user can delete the video
63 // The user can delete it if he has the right
64 // Or if s/he is the video's account
65 const account = video.VideoChannel.Account
66 if (user.hasRight(right) === false && account.userId !== user.id) {
67 res.status(403)
68 .json({ error: 'Cannot manage a video of another user.' })
69 .end()
70 return false
71 }
72
73 return true
74}
75
76// ---------------------------------------------------------------------------
77
78export {
79 doesVideoChannelOfAccountExist,
80 doesVideoExist,
81 checkUserCanManageVideo
82}