Karan Adhikari commited on
Commit
6bf4c2a
·
unverified ·
1 Parent(s): 0f3d954

Create utils.py

Browse files
Files changed (1) hide show
  1. Backend/helper/utils.py +59 -0
Backend/helper/utils.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+
3
+ from Backend import db
4
+ from Backend.logger import LOGGER
5
+ from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS
6
+
7
+ async def track_usage(stream_id: str, token: str, token_data: dict):
8
+ await asyncio.sleep(2)
9
+ limits = token_data.get("limits", {}) if token_data else {}
10
+ usage = token_data.get("usage", {}) if token_data else {}
11
+ daily_limit_gb = limits.get("daily_limit_gb")
12
+ monthly_limit_gb = limits.get("monthly_limit_gb")
13
+ initial_daily_bytes = usage.get("daily", {}).get("bytes", 0)
14
+ initial_monthly_bytes = usage.get("monthly", {}).get("bytes", 0)
15
+ last_tracked_bytes = 0
16
+ update_interval = 10
17
+ try:
18
+ while True:
19
+ await asyncio.sleep(update_interval)
20
+ stream_info = ACTIVE_STREAMS.get(stream_id)
21
+ if not stream_info:
22
+ for rec in RECENT_STREAMS:
23
+ if rec.get("stream_id") == stream_id:
24
+ final_bytes = rec.get("total_bytes", 0)
25
+ delta = final_bytes - last_tracked_bytes
26
+ if delta > 0:
27
+ try:
28
+ await db.update_token_usage(token, delta)
29
+ except Exception as e:
30
+ LOGGER.error(f"Final usage update failed: {e}")
31
+ break
32
+ return
33
+ current_bytes = stream_info.get("total_bytes", 0)
34
+ delta = current_bytes - last_tracked_bytes
35
+ if delta > 0:
36
+ try:
37
+ await db.update_token_usage(token, delta)
38
+ last_tracked_bytes = current_bytes
39
+ except Exception as e:
40
+ LOGGER.error(f"Periodic usage update failed: {e}")
41
+ if daily_limit_gb and daily_limit_gb > 0:
42
+ current_daily_gb = (initial_daily_bytes + current_bytes) / (1024 ** 3)
43
+ if current_daily_gb >= daily_limit_gb:
44
+ LOGGER.debug(f"Daily limit reached for token, stream {stream_id} may be blocked by verify_token")
45
+ if monthly_limit_gb and monthly_limit_gb > 0:
46
+ current_monthly_gb = (initial_monthly_bytes + current_bytes) / (1024 ** 3)
47
+ if current_monthly_gb >= monthly_limit_gb:
48
+ LOGGER.debug(f"Monthly limit reached for token, stream {stream_id} may be blocked by verify_token")
49
+ except asyncio.CancelledError:
50
+ stream_info = ACTIVE_STREAMS.get(stream_id)
51
+ if stream_info:
52
+ current_bytes = stream_info.get("total_bytes", 0)
53
+ delta = current_bytes - last_tracked_bytes
54
+ if delta > 0:
55
+ try:
56
+ await db.update_token_usage(token, delta)
57
+ LOGGER.info(f"Cancelled - final update for {stream_id}: {delta} bytes")
58
+ except Exception as e:
59
+ LOGGER.error(f"Cancelled usage update failed: {e}")