bep40 commited on
Commit
79c1874
·
verified ·
1 Parent(s): 1b652ad

Upload shorts_cache.py

Browse files
Files changed (1) hide show
  1. shorts_cache.py +56 -0
shorts_cache.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """VNEWS Shorts Runtime Cache - External Updater Module"""
2
+ import os, json, time, threading
3
+
4
+ _shorts_runtime_cache = None
5
+ _shorts_cache_ts = 0
6
+ _shorts_cache_lock = threading.Lock()
7
+ SHORTS_UPDATE_SECRET = os.environ.get("SHORTS_UPDATE_SECRET", "vnews-shorts-2026")
8
+ SHORTS_CACHE_FILE = "/data/shorts_runtime_cache.json" if os.path.isdir("/data") else "/app/shorts_runtime_cache.json"
9
+
10
+ def get_runtime_cache():
11
+ global _shorts_runtime_cache, _shorts_cache_ts
12
+ with _shorts_cache_lock:
13
+ if _shorts_runtime_cache is not None:
14
+ age = time.time() - _shorts_cache_ts
15
+ if age < 7200:
16
+ return _shorts_runtime_cache
17
+ try:
18
+ if os.path.exists(SHORTS_CACHE_FILE):
19
+ with open(SHORTS_CACHE_FILE, "r", encoding="utf-8") as f:
20
+ data = json.load(f)
21
+ age = time.time() - data.get("ts", 0)
22
+ if age < 86400:
23
+ items = data.get("items", [])
24
+ with _shorts_cache_lock:
25
+ _shorts_runtime_cache = items
26
+ _shorts_cache_ts = data.get("ts", time.time())
27
+ return items
28
+ except Exception as e:
29
+ print(f"[cache] read error: {e}")
30
+ return None
31
+
32
+ def set_runtime_cache(items):
33
+ global _shorts_runtime_cache, _shorts_cache_ts
34
+ ts = time.time()
35
+ with _shorts_cache_lock:
36
+ _shorts_runtime_cache = items
37
+ _shorts_cache_ts = ts
38
+ try:
39
+ os.makedirs(os.path.dirname(SHORTS_CACHE_FILE), exist_ok=True)
40
+ payload = {"items": items, "ts": ts, "count": len(items)}
41
+ with open(SHORTS_CACHE_FILE, "w", encoding="utf-8") as f:
42
+ json.dump(payload, f, ensure_ascii=False, indent=2)
43
+ print(f"[cache] saved {len(items)} shorts to {SHORTS_CACHE_FILE}")
44
+ except Exception as e:
45
+ print(f"[cache] write skipped: {e}")
46
+ return len(items)
47
+
48
+ def get_cache_status():
49
+ cache = None
50
+ with _shorts_cache_lock:
51
+ if _shorts_runtime_cache is not None:
52
+ cache = _shorts_runtime_cache
53
+ age = int(time.time() - _shorts_cache_ts)
54
+ else:
55
+ age = -1
56
+ return {"cached": cache is not None, "count": len(cache) if cache else 0, "age_seconds": age, "has_persistent": os.path.isdir("/data"), "cache_file_exists": os.path.exists(SHORTS_CACHE_FILE)}