]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/view.ts
Support studio transcoding in peertube runner
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / view.ts
1 import express from 'express'
2 import { Hooks } from '@server/lib/plugins/hooks'
3 import { VideoViewsManager } from '@server/lib/views/video-views-manager'
4 import { MVideoId } from '@server/types/models'
5 import { HttpStatusCode, VideoView } from '@shared/models'
6 import { asyncMiddleware, methodsValidator, openapiOperationDoc, optionalAuthenticate, videoViewValidator } from '../../../middlewares'
7 import { UserVideoHistoryModel } from '../../../models/user/user-video-history'
8
9 const viewRouter = express.Router()
10
11 viewRouter.all(
12 [ '/:videoId/views', '/:videoId/watching' ],
13 openapiOperationDoc({ operationId: 'addView' }),
14 methodsValidator([ 'PUT', 'POST' ]),
15 optionalAuthenticate,
16 asyncMiddleware(videoViewValidator),
17 asyncMiddleware(viewVideo)
18 )
19
20 // ---------------------------------------------------------------------------
21
22 export {
23 viewRouter
24 }
25
26 // ---------------------------------------------------------------------------
27
28 async function viewVideo (req: express.Request, res: express.Response) {
29 const video = res.locals.onlyImmutableVideo
30
31 const body = req.body as VideoView
32
33 const ip = req.ip
34 const { successView } = await VideoViewsManager.Instance.processLocalView({
35 video,
36 ip,
37 currentTime: body.currentTime,
38 viewEvent: body.viewEvent
39 })
40
41 if (successView) {
42 Hooks.runAction('action:api.video.viewed', { video, ip, req, res })
43 }
44
45 await updateUserHistoryIfNeeded(body, video, res)
46
47 return res.status(HttpStatusCode.NO_CONTENT_204).end()
48 }
49
50 async function updateUserHistoryIfNeeded (body: VideoView, video: MVideoId, res: express.Response) {
51 const user = res.locals.oauth?.token.User
52 if (!user) return
53 if (user.videosHistoryEnabled !== true) return
54
55 await UserVideoHistoryModel.upsert({
56 videoId: video.id,
57 userId: user.id,
58 currentTime: body.currentTime
59 })
60 }