diff --git a/backend/routes/statistics.routes.js b/backend/routes/statistics.routes.js index 716f8f9..8423db9 100644 --- a/backend/routes/statistics.routes.js +++ b/backend/routes/statistics.routes.js @@ -4,9 +4,83 @@ const sequelize = require('../db/database'); const { Op } = require('sequelize'); const EpisodeSeen = require('../models/EpisodeSeen'); const EntrySeen = require('../models/EntrySeen'); +const Episode = require('../models/Episode'); +const Entry = require('../models/Entry'); // ! /statistics +// * GET - Total Watch Time +statisticsRouter.get('/watch-time', async (req, res) => { + const totalWatchTimeSeries = await EpisodeSeen.findOne({ + include: [ + { model: Episode, as: 'episode', attributes: [] } + ], + attributes: [ + [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + ], + }); + + const totalWatchTimeMovies = await EntrySeen.findOne({ + include: [ + { model: Entry, as: 'entry', attributes: [] } + ], + attributes: [ + [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + ], + }); + + const totalWatchTime = { + series: totalWatchTimeSeries.dataValues.watchTime, + movies: totalWatchTimeMovies.dataValues.watchTime + } + + return res.status(200).json(totalWatchTime); +}); + +// * GET - Total Watch Time +statisticsRouter.get('/watch-time/year/:year', async (req, res) => { + const { year } = req.params; + + const totalWatchTimeSeries = await EpisodeSeen.findAll({ + include: [ + { model: Episode, as: 'episode', attributes: [] } + ], + attributes: [ + [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], + [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + ], + where: { + date_seen: { + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] + } + }, + group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + }); + + const totalWatchTimeMovies = await EntrySeen.findAll({ + include: [ + { model: Entry, as: 'entry', attributes: [] } + ], + attributes: [ + [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], + [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + ], + where: { + date_seen: { + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] + } + }, + group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + }); + + const totalWatchTime = { + series: totalWatchTimeSeries, + movies: totalWatchTimeMovies + } + + return res.status(200).json(totalWatchTime); +}); + // * GET - YEAR SEEN HISTORY GROUPED BY MONTH statisticsRouter.get('/watch-count/year/:year', async (req, res) => { try {