2021-03-16 02:02:17 +00:00
|
|
|
from django_coreprotect.models import SessionResult, ActivityResult
|
|
|
|
from django_coreprotect.utils import safe_int
|
|
|
|
from datetime import datetime
|
2022-02-12 21:21:03 +00:00
|
|
|
from typing import List
|
2021-03-16 02:02:17 +00:00
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
2022-02-12 21:21:03 +00:00
|
|
|
def activity_results(form) -> List[ActivityResult]:
|
2021-03-16 02:02:17 +00:00
|
|
|
query = ""
|
|
|
|
|
|
|
|
players_clause = ""
|
|
|
|
if form.players:
|
|
|
|
players = []
|
|
|
|
for player in form.players.split(","):
|
|
|
|
players.append(player.strip())
|
2022-02-12 21:21:03 +00:00
|
|
|
clause = " OR ".join([f"cu.user LIKE '%%{p}%%'" for p in players])
|
|
|
|
players_clause = f" WHERE ({clause}) "
|
2021-03-16 02:02:17 +00:00
|
|
|
|
|
|
|
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:
|
2022-02-12 21:21:03 +00:00
|
|
|
query = f'''SELECT
|
2021-03-16 02:02:17 +00:00
|
|
|
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
|
2022-02-12 21:21:03 +00:00
|
|
|
{players_clause}
|
|
|
|
{time_clause}
|
|
|
|
'''
|
2021-03-16 02:02:17 +00:00
|
|
|
|
|
|
|
if 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 []
|