canape/backend/admins/stats.go

73 lines
2.4 KiB
Go

package admin
import (
"net/http"
"github.com/jmoiron/sqlx"
"github.com/sirupsen/logrus"
"gitlab.quimbo.fr/odwrtw/canape/backend/web"
)
const (
moviesCountQuery = `SELECT COUNT(*) FROM movies;`
moviesTorrentsCountByIDQuery = `SELECT COUNT(*) FROM (SELECT DISTINCT(imdb_id) FROM movie_torrents) as TMP;`
moviesTorrentsCountQuery = `SELECT COUNT(*) FROM movie_torrents;`
showsCountQuery = `SELECT COUNT(*) FROM shows;`
showsTorrentsCountByIDQuery = `SELECT COUNT(*) FROM (SELECT DISTINCT(imdb_id) FROM episode_torrents) as TMP;`
episodesCountQuery = `SELECT COUNT(*) FROM episodes;`
episodesTorrentsCountByIDQuery = `SELECT COUNT(*) FROM (SELECT DISTINCT(imdb_id, season, episode) FROM episode_torrents) as TMP;`
episodesTorrentsCountQuery = `SELECT COUNT(*) FROM episode_torrents;`
)
// GetCount gets the count from a query
func GetCount(db *sqlx.DB, query string) (int, error) {
var count int
err := db.QueryRow(query).Scan(&count)
if err != nil {
return 0, err
}
return count, nil
}
// GetStatsHandler returns the stats of the app
func GetStatsHandler(env *web.Env, w http.ResponseWriter, r *http.Request) error {
log := env.Log.WithFields(logrus.Fields{
"function": "admin.GetStatsHandler",
})
log.Debug("getting stats")
stats := struct {
MoviesCount int `json:"movies_count"`
MoviesTorrentsCount int `json:"movies_torrents_count"`
MoviesTorrentsCountByID int `json:"movies_torrents_count_by_id"`
ShowsCount int `json:"shows_count"`
ShowsTorrentsCountByID int `json:"shows_torrents_count_by_id"`
EpisodesCount int `json:"episodes_count"`
EpisodesTorrentsCount int `json:"episodes_torrents_count"`
EpisodesTorrentsCountByID int `json:"episodes_torrents_count_by_id"`
}{}
for _, s := range []struct {
query string
ptr *int
}{
{moviesCountQuery, &stats.MoviesCount},
{moviesTorrentsCountQuery, &stats.MoviesTorrentsCount},
{moviesTorrentsCountByIDQuery, &stats.MoviesTorrentsCountByID},
{showsCountQuery, &stats.ShowsCount},
{showsTorrentsCountByIDQuery, &stats.ShowsTorrentsCountByID},
{episodesCountQuery, &stats.EpisodesCount},
{episodesTorrentsCountQuery, &stats.EpisodesTorrentsCount},
{episodesTorrentsCountByIDQuery, &stats.EpisodesTorrentsCountByID},
} {
var err error
*s.ptr, err = GetCount(env.Database, s.query)
if err != nil {
return err
}
}
return env.RenderJSON(w, stats)
}