django_coreprotect/activity.py

76 lines
2.4 KiB
Python

from django_coreprotect.models import SessionResult, ActivityResult
from django_coreprotect.utils import safe_int
from datetime import datetime
class ActivityForm:
def __init__(self):
self.players = ""
self.date_from = ""
self.date_to = ""
def activity_data(request):
request_data = request.GET
form = ActivityForm()
# Players
form.players = request_data["players"] if "players" in request_data else ""
# Date and Time
form.date_from = request_data["date_from"] if "date_from" in request_data else ""
form.date_to = request_data["date_to"] if "date_to" in request_data else ""
return form
def activity_results(form):
query = ""
players_clause = ""
if form.players:
players = []
for player in form.players.split(","):
players.append(player.strip())
players_clause = " WHERE ({}) ".format(" OR ".join(["cu.user LIKE '%%{}%%'".format(p) for p in players]))
time_clause = ""
if form.date_from or form.date_to:
df, dt = form.date_from, form.date_to
if form.date_from and not form.date_to:
dt = datetime.now().timestamp()
if form.date_to and not form.date_from:
df = datetime.now().timestamp()
time_clause = " HAVING unix BETWEEN {} AND {} ".format(df, dt)
if players_clause or time_clause:
query = '''SELECT
0 AS id, cs.time AS unix, cu.user AS player, cs.action
FROM co_session cs
JOIN co_user cu ON cs.user = cu.rowid
{players}
{time}
'''.format(players=players_clause, time=time_clause)
if query:
print(query)
sessions = SessionResult.objects.raw(query)
activity = {}
last_session = {}
for session in sessions:
time = -safe_int(session.unix) if session.action == 1 else safe_int(session.unix)
if session.player in activity:
if last_session[session.player] == session.action:
continue
activity[session.player] += time
last_session[session.player] = session.action
else:
activity[session.player] = time
last_session[session.player] = session.action
results = []
for player, time in activity.items():
results.append(ActivityResult(player, time))
return results
return []