1+ import discord
12import psycopg
23import random
34
5+ from discord import app_commands
6+
47from core import Plugin , DEFAULT_TAG , Side , DataObjectFactory , utils , Status , ServiceRegistry , PluginInstallationError
58from datetime import datetime , timedelta , timezone
9+ from discord .ext import tasks
610from fastapi import FastAPI , APIRouter , Form , Query , HTTPException
711from plugins .creditsystem .squadron import Squadron
812from plugins .userstats .filter import StatisticsFilter , PeriodFilter
@@ -159,6 +163,14 @@ def register_routes(self):
159163 )
160164 self .app .include_router (router )
161165
166+ async def cog_load (self ) -> None :
167+ await super ().cog_load ()
168+ self .refresh_views .start ()
169+
170+ async def cog_unload (self ) -> None :
171+ self .refresh_views .cancel ()
172+ await super ().cog_unload ()
173+
162174 async def get_ucid (self , nick : str , date : Union [str , datetime ]) -> str :
163175 if isinstance (date , str ):
164176 date = datetime .fromisoformat (date )
@@ -184,17 +196,7 @@ async def serverstats(self):
184196 async with self .apool .connection () as conn :
185197 async with conn .cursor (row_factory = dict_row ) as cursor :
186198 await cursor .execute ("""
187- SELECT COUNT(DISTINCT p.ucid) AS "totalPlayers",
188- ROUND(SUM(EXTRACT(EPOCH FROM(COALESCE(s.hop_off, NOW() AT TIME ZONE 'UTC') - s.hop_on))) / 3600)::INTEGER AS "totalPlaytime",
189- ROUND(AVG(EXTRACT(EPOCH FROM(COALESCE(s.hop_off, NOW() AT TIME ZONE 'UTC') - s.hop_on))))::INTEGER AS "avgPlaytime",
190- SUM(CASE WHEN s.hop_off IS NULL THEN 1 ELSE 0 END) AS "activePlayers",
191- COUNT(*) AS "totalSorties",
192- SUM(s.kills) AS "totalKills",
193- SUM(s.deaths) AS "totalDeaths",
194- SUM(s.pvp) AS "totalPvPKills",
195- SUM(s.deaths_pvp) AS "totalPvPDeaths"
196- FROM players p JOIN statistics s
197- ON p.ucid = s.player_ucid
199+ SELECT * FROM mv_serverstats
198200 """ )
199201 serverstats = await cursor .fetchone ()
200202 await cursor .execute ("""
@@ -603,6 +605,14 @@ async def create_token() -> str:
603605 "rc" : rc
604606 })
605607
608+ @tasks .loop (hours = 1 )
609+ async def refresh_views (self ):
610+ async with self .apool .connection () as conn :
611+ async with conn .transaction ():
612+ await conn .execute ("""
613+ REFRESH MATERIALIZED VIEW mv_serverstats;
614+ """ )
615+
606616
607617async def setup (bot : DCSServerBot ):
608618 await bot .add_cog (RestAPI (bot ))
0 commit comments