-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics.py
More file actions
95 lines (81 loc) · 3.01 KB
/
Copy pathanalytics.py
File metadata and controls
95 lines (81 loc) · 3.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from db import get_connection,safe_close
import json
from datetime import datetime
def increment_hourly_analytics(url_id, fingerprint, suspicious=False):
try:
conn = get_connection()
cursor = conn.cursor()
# Check URL exists
cursor.execute("SELECT 1 FROM urls WHERE id = %s", (url_id,))
if cursor.fetchone() is None:
return
# Current hour
now = datetime.utcnow().replace(minute=0, second=0, microsecond=0)
cursor.execute("""
INSERT INTO url_analytics_hourly (url_id, fingerprint, date_hour, clicks, suspicious_clicks)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
clicks = clicks + VALUES(clicks),
suspicious_clicks = suspicious_clicks + VALUES(suspicious_clicks)
""", (url_id, fingerprint, now, 1 if not suspicious else 0, 1 if suspicious else 0))
conn.commit()
finally:
try:
safe_close(conn) # type: ignore
cursor.close() #type: ignore
except Exception:
pass # Ignore connection errors on close
def update_url_referres(url_id:str,referrer:str|None):
try:
if not referrer:
referrer = "unknown"
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
INSERT INTO url_referrers (url_id, referrer, clicks)
VALUES (%s, %s, 1)
ON DUPLICATE KEY UPDATE clicks = clicks + 1
""",
(url_id, referrer))
conn.commit()
finally:
try:
safe_close(conn) # type: ignore
cursor.close() #type: ignore
except Exception:
pass # Ignore connection errors on close
def update_user_sequence(fingerprint: str, url_code: str, max_length: int = 10):
conn = get_connection()
cursor = conn.cursor(dictionary=True)
try:
cursor.execute("SELECT sequence FROM user_sequences WHERE fingerprint=%s", (fingerprint,))
row = cursor.fetchone()
# Safely load JSON
if row and row['sequence']:
try:
sequence = json.loads(row['sequence'])
if not isinstance(sequence, list):
sequence = [sequence] # wrap single string into a list
except json.JSONDecodeError:
sequence = []
else:
sequence = []
# Append new code
if url_code not in sequence:
sequence.append(url_code)
# Keep only last N
sequence = sequence[-max_length:]
if row:
cursor.execute(
"UPDATE user_sequences SET sequence=%s, last_update=NOW() WHERE fingerprint=%s",
(json.dumps(sequence), fingerprint)
)
else:
cursor.execute(
"INSERT INTO user_sequences (fingerprint, sequence) VALUES (%s, %s)",
(fingerprint, json.dumps(sequence))
)
conn.commit()
finally:
cursor.close()
safe_close(conn)