2022-03-24 08:36:47 -04:00
|
|
|
import express from 'express'
|
|
|
|
import { Hooks } from '@server/lib/plugins/hooks'
|
|
|
|
import { VideoViewsManager } from '@server/lib/views/video-views-manager'
|
|
|
|
import { MVideoId } from '@server/types/models'
|
|
|
|
import { HttpStatusCode, VideoView } from '@shared/models'
|
|
|
|
import { asyncMiddleware, methodsValidator, openapiOperationDoc, optionalAuthenticate, videoViewValidator } from '../../../middlewares'
|
|
|
|
import { UserVideoHistoryModel } from '../../../models/user/user-video-history'
|
|
|
|
|
|
|
|
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 08:34:37 -04:00
|
|
|
const video = res.locals.onlyImmutableVideo
|
2022-03-24 08:36:47 -04:00
|
|
|
|
|
|
|
const body = req.body as VideoView
|
|
|
|
|
|
|
|
const ip = req.ip
|
2022-04-06 02:50:43 -04:00
|
|
|
const { successView } = await VideoViewsManager.Instance.processLocalView({
|
2022-03-24 08:36:47 -04:00
|
|
|
video,
|
|
|
|
ip,
|
|
|
|
currentTime: body.currentTime,
|
|
|
|
viewEvent: body.viewEvent
|
|
|
|
})
|
|
|
|
|
|
|
|
if (successView) {
|
2022-07-13 05:58:01 -04:00
|
|
|
Hooks.runAction('action:api.video.viewed', { video, ip, req, res })
|
2022-03-24 08:36:47 -04: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
|
|
|
|
})
|
|
|
|
}
|