aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers
diff options
context:
space:
mode:
Diffstat (limited to 'server/controllers')
-rw-r--r--server/controllers/activitypub/index.ts2
-rw-r--r--server/controllers/api/index.ts4
-rw-r--r--server/controllers/api/pods.ts66
-rw-r--r--server/controllers/api/request-schedulers.ts53
-rw-r--r--server/controllers/api/users.ts42
-rw-r--r--server/controllers/api/videos/abuse.ts4
-rw-r--r--server/controllers/api/videos/channel.ts37
-rw-r--r--server/controllers/api/videos/index.ts88
-rw-r--r--server/controllers/api/videos/rate.ts80
9 files changed, 80 insertions, 296 deletions
diff --git a/server/controllers/activitypub/index.ts b/server/controllers/activitypub/index.ts
index 7a4602b37..2b0e2a489 100644
--- a/server/controllers/activitypub/index.ts
+++ b/server/controllers/activitypub/index.ts
@@ -2,10 +2,12 @@ import * as express from 'express'
2 2
3import { badRequest } from '../../helpers' 3import { badRequest } from '../../helpers'
4import { inboxRouter } from './inbox' 4import { inboxRouter } from './inbox'
5import { activityPubClientRouter } from './client'
5 6
6const remoteRouter = express.Router() 7const remoteRouter = express.Router()
7 8
8remoteRouter.use('/inbox', inboxRouter) 9remoteRouter.use('/inbox', inboxRouter)
10remoteRouter.use('/', activityPubClientRouter)
9remoteRouter.use('/*', badRequest) 11remoteRouter.use('/*', badRequest)
10 12
11// --------------------------------------------------------------------------- 13// ---------------------------------------------------------------------------
diff --git a/server/controllers/api/index.ts b/server/controllers/api/index.ts
index a9205b33c..2e949d531 100644
--- a/server/controllers/api/index.ts
+++ b/server/controllers/api/index.ts
@@ -5,8 +5,6 @@ import { badRequest } from '../../helpers'
5import { oauthClientsRouter } from './oauth-clients' 5import { oauthClientsRouter } from './oauth-clients'
6import { configRouter } from './config' 6import { configRouter } from './config'
7import { podsRouter } from './pods' 7import { podsRouter } from './pods'
8import { remoteRouter } from './remote'
9import { requestSchedulerRouter } from './request-schedulers'
10import { usersRouter } from './users' 8import { usersRouter } from './users'
11import { videosRouter } from './videos' 9import { videosRouter } from './videos'
12 10
@@ -15,8 +13,6 @@ const apiRouter = express.Router()
15apiRouter.use('/oauth-clients', oauthClientsRouter) 13apiRouter.use('/oauth-clients', oauthClientsRouter)
16apiRouter.use('/config', configRouter) 14apiRouter.use('/config', configRouter)
17apiRouter.use('/pods', podsRouter) 15apiRouter.use('/pods', podsRouter)
18apiRouter.use('/remote', remoteRouter)
19apiRouter.use('/request-schedulers', requestSchedulerRouter)
20apiRouter.use('/users', usersRouter) 16apiRouter.use('/users', usersRouter)
21apiRouter.use('/videos', videosRouter) 17apiRouter.use('/videos', videosRouter)
22apiRouter.use('/ping', pong) 18apiRouter.use('/ping', pong)
diff --git a/server/controllers/api/pods.ts b/server/controllers/api/pods.ts
index b44cd6b83..43df3f66f 100644
--- a/server/controllers/api/pods.ts
+++ b/server/controllers/api/pods.ts
@@ -1,26 +1,7 @@
1import * as express from 'express' 1import * as express from 'express'
2 2import { getFormattedObjects } from '../../helpers'
3import { database as db } from '../../initializers/database' 3import { database as db } from '../../initializers/database'
4import { logger, getFormattedObjects } from '../../helpers' 4import { asyncMiddleware, paginationValidator, podsSortValidator, setPagination, setPodsSort } from '../../middlewares'
5import {
6 makeFriends,
7 quitFriends,
8 removeFriend
9} from '../../lib'
10import {
11 authenticate,
12 ensureUserHasRight,
13 makeFriendsValidator,
14 setBodyHostsPort,
15 podRemoveValidator,
16 paginationValidator,
17 setPagination,
18 setPodsSort,
19 podsSortValidator,
20 asyncMiddleware
21} from '../../middlewares'
22import { PodInstance } from '../../models'
23import { UserRight } from '../../../shared'
24 5
25const podsRouter = express.Router() 6const podsRouter = express.Router()
26 7
@@ -31,24 +12,6 @@ podsRouter.get('/',
31 setPagination, 12 setPagination,
32 asyncMiddleware(listPods) 13 asyncMiddleware(listPods)
33) 14)
34podsRouter.post('/make-friends',
35 authenticate,
36 ensureUserHasRight(UserRight.MANAGE_PODS),
37 makeFriendsValidator,
38 setBodyHostsPort,
39 asyncMiddleware(makeFriendsController)
40)
41podsRouter.get('/quit-friends',
42 authenticate,
43 ensureUserHasRight(UserRight.MANAGE_PODS),
44 asyncMiddleware(quitFriendsController)
45)
46podsRouter.delete('/:id',
47 authenticate,
48 ensureUserHasRight(UserRight.MANAGE_PODS),
49 podRemoveValidator,
50 asyncMiddleware(removeFriendController)
51)
52 15
53// --------------------------------------------------------------------------- 16// ---------------------------------------------------------------------------
54 17
@@ -63,28 +26,3 @@ async function listPods (req: express.Request, res: express.Response, next: expr
63 26
64 return res.json(getFormattedObjects(resultList.data, resultList.total)) 27 return res.json(getFormattedObjects(resultList.data, resultList.total))
65} 28}
66
67async function makeFriendsController (req: express.Request, res: express.Response, next: express.NextFunction) {
68 const hosts = req.body.hosts as string[]
69
70 // Don't wait the process that could be long
71 makeFriends(hosts)
72 .then(() => logger.info('Made friends!'))
73 .catch(err => logger.error('Could not make friends.', err))
74
75 return res.type('json').status(204).end()
76}
77
78async function quitFriendsController (req: express.Request, res: express.Response, next: express.NextFunction) {
79 await quitFriends()
80
81 return res.type('json').status(204).end()
82}
83
84async function removeFriendController (req: express.Request, res: express.Response, next: express.NextFunction) {
85 const pod = res.locals.pod as PodInstance
86
87 await removeFriend(pod)
88
89 return res.type('json').status(204).end()
90}
diff --git a/server/controllers/api/request-schedulers.ts b/server/controllers/api/request-schedulers.ts
deleted file mode 100644
index 4c8fbe18b..000000000
--- a/server/controllers/api/request-schedulers.ts
+++ /dev/null
@@ -1,53 +0,0 @@
1import * as express from 'express'
2import * as Bluebird from 'bluebird'
3
4import {
5 AbstractRequestScheduler,
6 getRequestScheduler,
7 getRequestVideoQaduScheduler,
8 getRequestVideoEventScheduler
9} from '../../lib'
10import { authenticate, ensureUserHasRight, asyncMiddleware } from '../../middlewares'
11import { RequestSchedulerStatsAttributes, UserRight } from '../../../shared'
12
13const requestSchedulerRouter = express.Router()
14
15requestSchedulerRouter.get('/stats',
16 authenticate,
17 ensureUserHasRight(UserRight.MANAGE_REQUEST_SCHEDULERS),
18 asyncMiddleware(getRequestSchedulersStats)
19)
20
21// ---------------------------------------------------------------------------
22
23export {
24 requestSchedulerRouter
25}
26
27// ---------------------------------------------------------------------------
28
29async function getRequestSchedulersStats (req: express.Request, res: express.Response, next: express.NextFunction) {
30 const result = await Bluebird.props({
31 requestScheduler: buildRequestSchedulerStats(getRequestScheduler()),
32 requestVideoQaduScheduler: buildRequestSchedulerStats(getRequestVideoQaduScheduler()),
33 requestVideoEventScheduler: buildRequestSchedulerStats(getRequestVideoEventScheduler())
34 })
35
36 return res.json(result)
37}
38
39// ---------------------------------------------------------------------------
40
41async function buildRequestSchedulerStats (requestScheduler: AbstractRequestScheduler<any>) {
42 const count = await requestScheduler.remainingRequestsCount()
43
44 const result: RequestSchedulerStatsAttributes = {
45 totalRequests: count,
46 requestsLimitPods: requestScheduler.limitPods,
47 requestsLimitPerPod: requestScheduler.limitPerPod,
48 remainingMilliSeconds: requestScheduler.remainingMilliSeconds(),
49 milliSecondsInterval: requestScheduler.requestInterval
50 }
51
52 return result
53}
diff --git a/server/controllers/api/users.ts b/server/controllers/api/users.ts
index 9ec6feb57..41ffb64cb 100644
--- a/server/controllers/api/users.ts
+++ b/server/controllers/api/users.ts
@@ -1,37 +1,29 @@
1import * as express from 'express' 1import * as express from 'express'
2 2import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared'
3import { database as db, CONFIG } from '../../initializers' 3import { getFormattedObjects, logger, retryTransactionWrapper } from '../../helpers'
4import { logger, getFormattedObjects, retryTransactionWrapper } from '../../helpers' 4import { CONFIG, database as db } from '../../initializers'
5import { createUserAccountAndChannel } from '../../lib'
5import { 6import {
7 asyncMiddleware,
6 authenticate, 8 authenticate,
7 ensureUserHasRight, 9 ensureUserHasRight,
8 ensureUserRegistrationAllowed, 10 ensureUserRegistrationAllowed,
9 usersAddValidator,
10 usersRegisterValidator,
11 usersUpdateValidator,
12 usersUpdateMeValidator,
13 usersRemoveValidator,
14 usersVideoRatingValidator,
15 usersGetValidator,
16 paginationValidator, 11 paginationValidator,
17 setPagination, 12 setPagination,
18 usersSortValidator,
19 setUsersSort, 13 setUsersSort,
20 token, 14 token,
21 asyncMiddleware 15 usersAddValidator,
16 usersGetValidator,
17 usersRegisterValidator,
18 usersRemoveValidator,
19 usersSortValidator,
20 usersUpdateMeValidator,
21 usersUpdateValidator,
22 usersVideoRatingValidator
22} from '../../middlewares' 23} from '../../middlewares'
23import {
24 UserVideoRate as FormattedUserVideoRate,
25 UserCreate,
26 UserUpdate,
27 UserUpdateMe,
28 UserRole,
29 UserRight
30} from '../../../shared'
31import { createUserAccountAndChannel } from '../../lib'
32import { UserInstance } from '../../models'
33import { videosSortValidator } from '../../middlewares/validators/sort'
34import { setVideosSort } from '../../middlewares/sort' 24import { setVideosSort } from '../../middlewares/sort'
25import { videosSortValidator } from '../../middlewares/validators/sort'
26import { UserInstance } from '../../models'
35 27
36const usersRouter = express.Router() 28const usersRouter = express.Router()
37 29
@@ -176,9 +168,9 @@ function getUser (req: express.Request, res: express.Response, next: express.Nex
176 168
177async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) { 169async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
178 const videoId = +req.params.videoId 170 const videoId = +req.params.videoId
179 const userId = +res.locals.oauth.token.User.id 171 const accountId = +res.locals.oauth.token.User.Account.id
180 172
181 const ratingObj = await db.UserVideoRate.load(userId, videoId, null) 173 const ratingObj = await db.AccountVideoRate.load(accountId, videoId, null)
182 const rating = ratingObj ? ratingObj.type : 'none' 174 const rating = ratingObj ? ratingObj.type : 'none'
183 175
184 const json: FormattedUserVideoRate = { 176 const json: FormattedUserVideoRate = {
diff --git a/server/controllers/api/videos/abuse.ts b/server/controllers/api/videos/abuse.ts
index 04349042b..7a3471116 100644
--- a/server/controllers/api/videos/abuse.ts
+++ b/server/controllers/api/videos/abuse.ts
@@ -1,7 +1,6 @@
1import * as express from 'express' 1import * as express from 'express'
2 2
3import { database as db } from '../../../initializers/database' 3import { database as db } from '../../../initializers/database'
4import * as friends from '../../../lib/friends'
5import { 4import {
6 logger, 5 logger,
7 getFormattedObjects, 6 getFormattedObjects,
@@ -84,7 +83,8 @@ async function reportVideoAbuse (req: express.Request, res: express.Response) {
84 videoUUID: videoInstance.uuid 83 videoUUID: videoInstance.uuid
85 } 84 }
86 85
87 await friends.reportAbuseVideoToFriend(reportData, videoInstance, t) 86 // await friends.reportAbuseVideoToFriend(reportData, videoInstance, t)
87 // TODO: send abuse to origin pod
88 } 88 }
89 }) 89 })
90 90
diff --git a/server/controllers/api/videos/channel.ts b/server/controllers/api/videos/channel.ts
index 4d1f03903..656bc3129 100644
--- a/server/controllers/api/videos/channel.ts
+++ b/server/controllers/api/videos/channel.ts
@@ -1,31 +1,23 @@
1import * as express from 'express' 1import * as express from 'express'
2 2import { VideoChannelCreate, VideoChannelUpdate } from '../../../../shared'
3import { getFormattedObjects, logger, resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers'
3import { database as db } from '../../../initializers' 4import { database as db } from '../../../initializers'
5import { createVideoChannel } from '../../../lib'
4import { 6import {
5 logger, 7 asyncMiddleware,
6 getFormattedObjects,
7 retryTransactionWrapper,
8 resetSequelizeInstance
9} from '../../../helpers'
10import {
11 authenticate, 8 authenticate,
9 listVideoAccountChannelsValidator,
12 paginationValidator, 10 paginationValidator,
13 videoChannelsSortValidator,
14 videoChannelsAddValidator,
15 setVideoChannelsSort,
16 setPagination, 11 setPagination,
17 videoChannelsRemoveValidator, 12 setVideoChannelsSort,
18 videoChannelGetValidator, 13 videoChannelGetValidator,
19 videoChannelsUpdateValidator, 14 videoChannelsAddValidator,
20 listVideoAccountChannelsValidator, 15 videoChannelsRemoveValidator,
21 asyncMiddleware 16 videoChannelsSortValidator,
17 videoChannelsUpdateValidator
22} from '../../../middlewares' 18} from '../../../middlewares'
23import { 19import { AccountInstance, VideoChannelInstance } from '../../../models'
24 createVideoChannel, 20import { sendUpdateVideoChannel } from '../../../lib/activitypub/send-request'
25 updateVideoChannelToFriends
26} from '../../../lib'
27import { VideoChannelInstance, AccountInstance } from '../../../models'
28import { VideoChannelCreate, VideoChannelUpdate } from '../../../../shared'
29 21
30const videoChannelRouter = express.Router() 22const videoChannelRouter = express.Router()
31 23
@@ -137,11 +129,8 @@ async function updateVideoChannel (req: express.Request, res: express.Response)
137 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description) 129 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
138 130
139 await videoChannelInstance.save(sequelizeOptions) 131 await videoChannelInstance.save(sequelizeOptions)
140 const json = videoChannelInstance.toUpdateRemoteJSON()
141
142 // Now we'll update the video channel's meta data to our friends
143 return updateVideoChannelToFriends(json, t)
144 132
133 await sendUpdateVideoChannel(videoChannelInstance, t)
145 }) 134 })
146 135
147 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.uuid) 136 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.uuid)
diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts
index 9ad84609f..063839223 100644
--- a/server/controllers/api/videos/index.ts
+++ b/server/controllers/api/videos/index.ts
@@ -1,57 +1,41 @@
1import * as express from 'express' 1import * as express from 'express'
2import * as multer from 'multer' 2import * as multer from 'multer'
3import { extname, join } from 'path' 3import { extname, join } from 'path'
4 4import { VideoCreate, VideoPrivacy, VideoUpdate } from '../../../../shared'
5import { database as db } from '../../../initializers/database'
6import { 5import {
7 CONFIG, 6 fetchRemoteVideoDescription,
8 REQUEST_VIDEO_QADU_TYPES, 7 generateRandomString,
9 REQUEST_VIDEO_EVENT_TYPES, 8 getFormattedObjects,
10 VIDEO_CATEGORIES, 9 getVideoFileHeight,
11 VIDEO_LICENCES, 10 logger,
12 VIDEO_LANGUAGES, 11 renamePromise,
13 VIDEO_PRIVACIES, 12 resetSequelizeInstance,
14 VIDEO_MIMETYPE_EXT 13 retryTransactionWrapper
15} from '../../../initializers' 14} from '../../../helpers'
16import { 15import { getActivityPubUrl } from '../../../helpers/activitypub'
17 addEventToRemoteVideo, 16import { CONFIG, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_MIMETYPE_EXT, VIDEO_PRIVACIES } from '../../../initializers'
18 quickAndDirtyUpdateVideoToFriends, 17import { database as db } from '../../../initializers/database'
19 addVideoToFriends, 18import { sendAddVideo, sendUpdateVideoChannel } from '../../../lib/activitypub/send-request'
20 updateVideoToFriends, 19import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler/transcoding-job-scheduler'
21 JobScheduler,
22 fetchRemoteDescription
23} from '../../../lib'
24import { 20import {
21 asyncMiddleware,
25 authenticate, 22 authenticate,
26 paginationValidator, 23 paginationValidator,
27 videosSortValidator,
28 setVideosSort,
29 setPagination, 24 setPagination,
30 setVideosSearch, 25 setVideosSearch,
31 videosUpdateValidator, 26 setVideosSort,
32 videosSearchValidator,
33 videosAddValidator, 27 videosAddValidator,
34 videosGetValidator, 28 videosGetValidator,
35 videosRemoveValidator, 29 videosRemoveValidator,
36 asyncMiddleware 30 videosSearchValidator,
31 videosSortValidator,
32 videosUpdateValidator
37} from '../../../middlewares' 33} from '../../../middlewares'
38import {
39 logger,
40 retryTransactionWrapper,
41 generateRandomString,
42 getFormattedObjects,
43 renamePromise,
44 getVideoFileHeight,
45 resetSequelizeInstance
46} from '../../../helpers'
47import { VideoInstance } from '../../../models' 34import { VideoInstance } from '../../../models'
48import { VideoCreate, VideoUpdate, VideoPrivacy } from '../../../../shared'
49
50import { abuseVideoRouter } from './abuse' 35import { abuseVideoRouter } from './abuse'
51import { blacklistRouter } from './blacklist' 36import { blacklistRouter } from './blacklist'
52import { rateVideoRouter } from './rate'
53import { videoChannelRouter } from './channel' 37import { videoChannelRouter } from './channel'
54import { getActivityPubUrl } from '../../../helpers/activitypub' 38import { rateVideoRouter } from './rate'
55 39
56const videosRouter = express.Router() 40const videosRouter = express.Router()
57 41
@@ -225,7 +209,7 @@ async function addVideo (req: express.Request, res: express.Response, videoPhysi
225 } 209 }
226 210
227 tasks.push( 211 tasks.push(
228 JobScheduler.Instance.createJob(t, 'videoFileOptimizer', dataInput) 212 transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
229 ) 213 )
230 } 214 }
231 await Promise.all(tasks) 215 await Promise.all(tasks)
@@ -252,9 +236,7 @@ async function addVideo (req: express.Request, res: express.Response, videoPhysi
252 // Don't send video to remote pods, it is private 236 // Don't send video to remote pods, it is private
253 if (video.privacy === VideoPrivacy.PRIVATE) return undefined 237 if (video.privacy === VideoPrivacy.PRIVATE) return undefined
254 238
255 const remoteVideo = await video.toAddRemoteJSON() 239 await sendAddVideo(video, t)
256 // Now we'll add the video's meta data to our friends
257 return addVideoToFriends(remoteVideo, t)
258 }) 240 })
259 241
260 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID) 242 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID)
@@ -302,14 +284,12 @@ async function updateVideo (req: express.Request, res: express.Response) {
302 284
303 // Now we'll update the video's meta data to our friends 285 // Now we'll update the video's meta data to our friends
304 if (wasPrivateVideo === false) { 286 if (wasPrivateVideo === false) {
305 const json = videoInstance.toUpdateRemoteJSON() 287 await sendUpdateVideoChannel(videoInstance, t)
306 return updateVideoToFriends(json, t)
307 } 288 }
308 289
309 // Video is not private anymore, send a create action to remote pods 290 // Video is not private anymore, send a create action to remote pods
310 if (wasPrivateVideo === true && videoInstance.privacy !== VideoPrivacy.PRIVATE) { 291 if (wasPrivateVideo === true && videoInstance.privacy !== VideoPrivacy.PRIVATE) {
311 const remoteVideo = await videoInstance.toAddRemoteJSON() 292 await sendAddVideo(videoInstance, t)
312 return addVideoToFriends(remoteVideo, t)
313 } 293 }
314 }) 294 })
315 295
@@ -324,7 +304,7 @@ async function updateVideo (req: express.Request, res: express.Response) {
324 } 304 }
325} 305}
326 306
327function getVideo (req: express.Request, res: express.Response) { 307async function getVideo (req: express.Request, res: express.Response) {
328 const videoInstance = res.locals.video 308 const videoInstance = res.locals.video
329 309
330 if (videoInstance.isOwned()) { 310 if (videoInstance.isOwned()) {
@@ -333,21 +313,11 @@ function getVideo (req: express.Request, res: express.Response) {
333 // For example, only add a view when a user watch a video during 30s etc 313 // For example, only add a view when a user watch a video during 30s etc
334 videoInstance.increment('views') 314 videoInstance.increment('views')
335 .then(() => { 315 .then(() => {
336 const qaduParams = { 316 // TODO: send to followers a notification
337 videoId: videoInstance.id,
338 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
339 }
340 return quickAndDirtyUpdateVideoToFriends(qaduParams)
341 }) 317 })
342 .catch(err => logger.error('Cannot add view to video %s.', videoInstance.uuid, err)) 318 .catch(err => logger.error('Cannot add view to video %s.', videoInstance.uuid, err))
343 } else { 319 } else {
344 // Just send the event to our friends 320 // TODO: send view event to followers
345 const eventParams = {
346 videoId: videoInstance.id,
347 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
348 }
349 addEventToRemoteVideo(eventParams)
350 .catch(err => logger.error('Cannot add event to remote video %s.', videoInstance.uuid, err))
351 } 321 }
352 322
353 // Do not wait the view system 323 // Do not wait the view system
@@ -361,7 +331,7 @@ async function getVideoDescription (req: express.Request, res: express.Response)
361 if (videoInstance.isOwned()) { 331 if (videoInstance.isOwned()) {
362 description = videoInstance.description 332 description = videoInstance.description
363 } else { 333 } else {
364 description = await fetchRemoteDescription(videoInstance) 334 description = await fetchRemoteVideoDescription(videoInstance)
365 } 335 }
366 336
367 return res.json({ description }) 337 return res.json({ description })
diff --git a/server/controllers/api/videos/rate.ts b/server/controllers/api/videos/rate.ts
index 727984506..955277d25 100644
--- a/server/controllers/api/videos/rate.ts
+++ b/server/controllers/api/videos/rate.ts
@@ -1,25 +1,11 @@
1import * as express from 'express' 1import * as express from 'express'
2
3import { database as db } from '../../../initializers/database'
4import {
5 logger,
6 retryTransactionWrapper
7} from '../../../helpers'
8import {
9 VIDEO_RATE_TYPES,
10 REQUEST_VIDEO_EVENT_TYPES,
11 REQUEST_VIDEO_QADU_TYPES
12} from '../../../initializers'
13import {
14 addEventsToRemoteVideo,
15 quickAndDirtyUpdatesVideoToFriends
16} from '../../../lib'
17import {
18 authenticate,
19 videoRateValidator,
20 asyncMiddleware
21} from '../../../middlewares'
22import { UserVideoRateUpdate } from '../../../../shared' 2import { UserVideoRateUpdate } from '../../../../shared'
3import { logger, retryTransactionWrapper } from '../../../helpers'
4import { VIDEO_RATE_TYPES } from '../../../initializers'
5import { database as db } from '../../../initializers/database'
6import { asyncMiddleware, authenticate, videoRateValidator } from '../../../middlewares'
7import { AccountInstance } from '../../../models/account/account-interface'
8import { VideoInstance } from '../../../models/video/video-interface'
23 9
24const rateVideoRouter = express.Router() 10const rateVideoRouter = express.Router()
25 11
@@ -51,12 +37,12 @@ async function rateVideoRetryWrapper (req: express.Request, res: express.Respons
51async function rateVideo (req: express.Request, res: express.Response) { 37async function rateVideo (req: express.Request, res: express.Response) {
52 const body: UserVideoRateUpdate = req.body 38 const body: UserVideoRateUpdate = req.body
53 const rateType = body.rating 39 const rateType = body.rating
54 const videoInstance = res.locals.video 40 const videoInstance: VideoInstance = res.locals.video
55 const userInstance = res.locals.oauth.token.User 41 const accountInstance: AccountInstance = res.locals.oauth.token.User.Account
56 42
57 await db.sequelize.transaction(async t => { 43 await db.sequelize.transaction(async t => {
58 const sequelizeOptions = { transaction: t } 44 const sequelizeOptions = { transaction: t }
59 const previousRate = await db.UserVideoRate.load(userInstance.id, videoInstance.id, t) 45 const previousRate = await db.AccountVideoRate.load(accountInstance.id, videoInstance.id, t)
60 46
61 let likesToIncrement = 0 47 let likesToIncrement = 0
62 let dislikesToIncrement = 0 48 let dislikesToIncrement = 0
@@ -79,12 +65,12 @@ async function rateVideo (req: express.Request, res: express.Response) {
79 } 65 }
80 } else if (rateType !== 'none') { // There was not a previous rate, insert a new one if there is a rate 66 } else if (rateType !== 'none') { // There was not a previous rate, insert a new one if there is a rate
81 const query = { 67 const query = {
82 userId: userInstance.id, 68 accountId: accountInstance.id,
83 videoId: videoInstance.id, 69 videoId: videoInstance.id,
84 type: rateType 70 type: rateType
85 } 71 }
86 72
87 await db.UserVideoRate.create(query, sequelizeOptions) 73 await db.AccountVideoRate.create(query, sequelizeOptions)
88 } 74 }
89 75
90 const incrementQuery = { 76 const incrementQuery = {
@@ -96,48 +82,12 @@ async function rateVideo (req: express.Request, res: express.Response) {
96 // It is useful for the user to have a feedback 82 // It is useful for the user to have a feedback
97 await videoInstance.increment(incrementQuery, sequelizeOptions) 83 await videoInstance.increment(incrementQuery, sequelizeOptions)
98 84
99 // Send a event to original pod
100 if (videoInstance.isOwned() === false) { 85 if (videoInstance.isOwned() === false) {
101 86 // TODO: Send a event to original pod
102 const eventsParams = [] 87 } else {
103 88 // TODO: Send update to followers
104 if (likesToIncrement !== 0) {
105 eventsParams.push({
106 videoId: videoInstance.id,
107 type: REQUEST_VIDEO_EVENT_TYPES.LIKES,
108 count: likesToIncrement
109 })
110 }
111
112 if (dislikesToIncrement !== 0) {
113 eventsParams.push({
114 videoId: videoInstance.id,
115 type: REQUEST_VIDEO_EVENT_TYPES.DISLIKES,
116 count: dislikesToIncrement
117 })
118 }
119
120 await addEventsToRemoteVideo(eventsParams, t)
121 } else { // We own the video, we need to send a quick and dirty update to friends to notify the counts changed
122 const qadusParams = []
123
124 if (likesToIncrement !== 0) {
125 qadusParams.push({
126 videoId: videoInstance.id,
127 type: REQUEST_VIDEO_QADU_TYPES.LIKES
128 })
129 }
130
131 if (dislikesToIncrement !== 0) {
132 qadusParams.push({
133 videoId: videoInstance.id,
134 type: REQUEST_VIDEO_QADU_TYPES.DISLIKES
135 })
136 }
137
138 await quickAndDirtyUpdatesVideoToFriends(qadusParams, t)
139 } 89 }
140 }) 90 })
141 91
142 logger.info('User video rate for video %s of user %s updated.', videoInstance.name, userInstance.username) 92 logger.info('Account video rate for video %s of account %s updated.', videoInstance.name, accountInstance.name)
143} 93}