2022-03-24 13:36:47 +01:00
|
|
|
import express from 'express'
|
2023-07-31 14:34:36 +02:00
|
|
|
import { HttpStatusCode, VideoView } from '@peertube/peertube-models'
|
|
|
|
import { Hooks } from '@server/lib/plugins/hooks.js'
|
|
|
|
import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
|
|
|
|
import { MVideoId } from '@server/types/models/index.js'
|
|
|
|
import {
|
|
|
|
asyncMiddleware,
|
|
|
|
methodsValidator,
|
|
|
|
openapiOperationDoc,
|
|
|
|
optionalAuthenticate,
|
|
|
|
videoViewValidator
|
|
|
|
} from '../../../middlewares/index.js'
|
|
|
|
import { UserVideoHistoryModel } from '../../../models/user/user-video-history.js'
|
2022-03-24 13:36:47 +01:00
|
|
|
|
|
|
|
const viewRouter = express.Router()
|
|
|
|
|
|
|
|
viewRouter.all(
|
|
|
|
[ '/:videoId/views', '/:videoId/watching' ],
|
|
|
|
openapiOperationDoc({ operationId: 'addView' }),
|
|
|
|
methodsValidator([ 'PUT', 'POST' ]),
|
|
|
|
optionalAuthenticate,
|
|
|
|
asyncMiddleware(videoViewValidator),
|
|
|
|
asyncMiddleware(viewVideo)
|
|
|
|
)
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
export {
|
|
|
|
viewRouter
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
async function viewVideo (req: express.Request, res: express.Response) {
|
2022-06-17 14:34:37 +02:00
|
|
|
const video = res.locals.onlyImmutableVideo
|
2022-03-24 13:36:47 +01:00
|
|
|
|
|
|
|
const body = req.body as VideoView
|
|
|
|
|
|
|
|
const ip = req.ip
|
2022-04-06 08:50:43 +02:00
|
|
|
const { successView } = await VideoViewsManager.Instance.processLocalView({
|
2022-03-24 13:36:47 +01:00
|
|
|
video,
|
|
|
|
ip,
|
|
|
|
currentTime: body.currentTime,
|
2024-04-04 11:30:30 +02:00
|
|
|
viewEvent: body.viewEvent,
|
|
|
|
sessionId: body.sessionId
|
2022-03-24 13:36:47 +01:00
|
|
|
})
|
|
|
|
|
|
|
|
if (successView) {
|
2022-07-13 11:58:01 +02:00
|
|
|
Hooks.runAction('action:api.video.viewed', { video, ip, req, res })
|
2022-03-24 13:36:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
await updateUserHistoryIfNeeded(body, video, res)
|
|
|
|
|
|
|
|
return res.status(HttpStatusCode.NO_CONTENT_204).end()
|
|
|
|
}
|
|
|
|
|
|
|
|
async function updateUserHistoryIfNeeded (body: VideoView, video: MVideoId, res: express.Response) {
|
|
|
|
const user = res.locals.oauth?.token.User
|
|
|
|
if (!user) return
|
|
|
|
if (user.videosHistoryEnabled !== true) return
|
|
|
|
|
|
|
|
await UserVideoHistoryModel.upsert({
|
|
|
|
videoId: video.id,
|
|
|
|
userId: user.id,
|
|
|
|
currentTime: body.currentTime
|
|
|
|
})
|
|
|
|
}
|