Spaces:
Running
Running
File size: 18,052 Bytes
14c1acb 0dcabd5 14c1acb 0dcabd5 14c1acb 0dcabd5 14c1acb 0dcabd5 14c1acb 0dcabd5 14c1acb 0dcabd5 14c1acb 0dcabd5 14c1acb 0dcabd5 14c1acb 0dcabd5 | 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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 | import json
import os
import time
import threading
import logging
logger = logging.getLogger(__name__)
_DEFAULT_DB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "data")
_HF_DATA = "/data" if os.path.isdir("/data") and "SPACE_ID" in os.environ else None
DB_FILE = os.environ.get("BLOGGER_DB_PATH", os.path.join(_HF_DATA or _DEFAULT_DB_DIR, "blogger_data.json"))
lock = threading.Lock()
DEFAULT_BLOGGER_DATA = {
"config": {
"blog_id": "",
"client_id": "",
"client_secret": "",
"refresh_token": "",
"publish_as_draft": False,
"enabled": False,
"default_jobs_image": "",
},
"ai_keys": {},
"channels": {},
"articles": {},
"published_ids": [],
"sections": {},
"logs": [],
"stats": {
"total_published": 0,
"total_failed": 0,
"daily": {},
"monthly": {},
},
}
class BloggerDatabase:
def __init__(self):
self._cache = None
def _ensure_file(self):
os.makedirs(os.path.dirname(DB_FILE), exist_ok=True)
if not os.path.exists(DB_FILE):
old_path = os.path.join(_DEFAULT_DB_DIR, "blogger_data.json")
if _HF_DATA and os.path.isfile(old_path):
import shutil
shutil.copy2(old_path, DB_FILE)
logger.info(f"Migrated DB from {old_path} to {DB_FILE}")
else:
with open(DB_FILE, "w", encoding="utf-8") as f:
json.dump(DEFAULT_BLOGGER_DATA, f, ensure_ascii=False, indent=2)
def _read(self):
self._ensure_file()
try:
with open(DB_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception as exc:
# Never silently convert a corrupt database into an empty database.
# Recovery is handled by the caller/startup layer.
raise RuntimeError(f"Blogger database read failed: {exc}") from exc
for key, value in DEFAULT_BLOGGER_DATA.items():
if key not in data:
data[key] = value.copy() if isinstance(value, (list, dict)) else value
if not isinstance(data.get("config"), dict):
data["config"] = {}
for k, v in DEFAULT_BLOGGER_DATA["config"].items():
data["config"].setdefault(k, v)
return data
def _write(self, data):
self._ensure_file()
tmp = DB_FILE + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.flush()
try:
os.fsync(f.fileno())
except Exception:
pass
os.replace(tmp, DB_FILE)
self._cache = None
def get_config(self):
with lock:
return dict(self._read().get("config", {}))
def update_config(self, key, value):
with lock:
data = self._read()
data["config"][key] = value
self._write(data)
def get_channel(self, channel_id):
with lock:
data = self._read()
return data.get("channels", {}).get(str(channel_id))
def get_all_channels(self):
with lock:
data = self._read()
return list(data.get("channels", {}).values())
def save_channel(self, channel_id, channel_data):
with lock:
data = self._read()
data["channels"][str(channel_id)] = channel_data
self._write(data)
def delete_channel(self, channel_id):
with lock:
data = self._read()
data["channels"].pop(str(channel_id), None)
self._write(data)
def _find_article_keys(self, articles_dict: dict, query_id: str) -> list:
"""Flexible lookup: matches dict key, internal fingerprint, or 8+ char prefix."""
q = str(query_id or "").strip()
if not q or not isinstance(articles_dict, dict):
return []
matched = []
for k, v in articles_dict.items():
k_str = str(k)
fp_str = str(v.get("fingerprint", "")) if isinstance(v, dict) else ""
if (
k_str == q
or fp_str == q
or (len(q) >= 8 and (k_str.startswith(q) or fp_str.startswith(q)))
or (len(k_str) >= 8 and q.startswith(k_str))
or (len(fp_str) >= 8 and q.startswith(fp_str))
):
matched.append(k_str)
return matched
def save_article(self, article_id, article_data):
with lock:
data = self._read()
aid = str(article_id or (article_data.get("fingerprint") if isinstance(article_data, dict) else "") or int(time.time()))
if isinstance(article_data, dict) and not article_data.get("fingerprint"):
article_data["fingerprint"] = aid
for old_k in self._find_article_keys(data["articles"], aid):
if old_k != aid:
data["articles"].pop(old_k, None)
data["articles"][aid] = article_data
self._write(data)
def get_article(self, article_id):
with lock:
data = self._read()
articles = data.get("articles", {})
keys = self._find_article_keys(articles, article_id)
if not keys:
return None
art = articles[keys[0]]
if isinstance(art, dict) and not art.get("fingerprint"):
art["fingerprint"] = keys[0]
return art
def delete_article(self, article_id) -> int:
with lock:
data = self._read()
articles = data.get("articles", {})
keys = self._find_article_keys(articles, article_id)
removed = 0
fps_to_clean = {str(article_id)}
for k in keys:
art = articles.pop(k, None)
removed += 1
fps_to_clean.add(k)
if isinstance(art, dict) and art.get("fingerprint"):
fps_to_clean.add(str(art["fingerprint"]))
pending = data.get(self.GEMINI_PENDING_KEY, [])
data[self.GEMINI_PENDING_KEY] = [
p for p in pending
if str(p.get("fingerprint", "")) not in fps_to_clean
and not any(str(p.get("fingerprint", "")).startswith(x) for x in fps_to_clean if len(x) >= 8)
]
self._write(data)
return removed
def delete_articles_by_filter(self, status_filter: str = "all") -> int:
with lock:
data = self._read()
articles = data.get("articles", {})
to_delete = []
fps_to_clean = set()
for k, v in list(articles.items()):
st = v.get("status", "unknown") if isinstance(v, dict) else "unknown"
if status_filter == "all" or st == status_filter:
to_delete.append(k)
fps_to_clean.add(str(k))
if isinstance(v, dict) and v.get("fingerprint"):
fps_to_clean.add(str(v["fingerprint"]))
for k in to_delete:
articles.pop(k, None)
if to_delete:
pending = data.get(self.GEMINI_PENDING_KEY, [])
data[self.GEMINI_PENDING_KEY] = [
p for p in pending if str(p.get("fingerprint", "")) not in fps_to_clean
]
self._write(data)
return len(to_delete)
def get_all_articles(self):
with lock:
data = self._read()
result = []
dirty = False
for k, v in data.get("articles", {}).items():
if isinstance(v, dict):
if not v.get("fingerprint"):
v["fingerprint"] = str(k)
dirty = True
result.append(v)
if dirty:
self._write(data)
return result
def is_published(self, fingerprint):
with lock:
data = self._read()
return fingerprint in data.get("published_ids", [])
def mark_published(self, fingerprint):
with lock:
data = self._read()
if fingerprint not in data["published_ids"]:
data["published_ids"].append(fingerprint)
data["stats"]["total_published"] += 1
self._write(data)
def mark_failed(self):
with lock:
data = self._read()
data["stats"]["total_failed"] += 1
self._write(data)
def add_log(self, entry):
with lock:
data = self._read()
data["logs"].append(entry)
if len(data["logs"]) > 1000:
data["logs"] = data["logs"][-1000:]
self._write(data)
def get_logs(self, limit=50):
with lock:
data = self._read()
return list(data["logs"])[-limit:]
def get_stats(self):
with lock:
data = self._read()
return dict(data.get("stats", {}))
def get_articles_by_status(self, status):
with lock:
data = self._read()
result = []
for k, a in data.get("articles", {}).items():
if isinstance(a, dict) and a.get("status") == status:
if not a.get("fingerprint"):
a["fingerprint"] = str(k)
result.append(a)
return result
def update_article_status(self, article_id, status, extra=None):
with lock:
data = self._read()
articles = data.get("articles", {})
for k in self._find_article_keys(articles, article_id):
articles[k]["status"] = status
if extra:
articles[k].update(extra)
self._write(data)
def get_all_sections(self):
with lock:
data = self._read()
return dict(data.get("sections", {}))
def add_section(self, section_id, section_data):
with lock:
data = self._read()
data["sections"][str(section_id)] = section_data
self._write(data)
def delete_section(self, section_id):
with lock:
data = self._read()
data["sections"].pop(str(section_id), None)
self._write(data)
def get_all_ai_keys(self):
with lock:
data = self._read()
return dict(data.get("ai_keys", {}))
def add_ai_key(self, key_id, key_data):
with lock:
data = self._read()
data["ai_keys"][str(key_id)] = {
"name": key_data.get("name", str(key_id)),
"key": key_data.get("key", ""),
"enabled": key_data.get("enabled", True),
"usage_count": 0,
"error_count": 0,
"last_used": 0,
"added_at": int(time.time()),
}
self._write(data)
def delete_ai_key(self, key_id):
with lock:
data = self._read()
data["ai_keys"].pop(str(key_id), None)
self._write(data)
def set_ai_key_enabled(self, key_id, enabled):
with lock:
data = self._read()
if str(key_id) in data["ai_keys"]:
data["ai_keys"][str(key_id)]["enabled"] = enabled
self._write(data)
def increment_daily_count(self, section):
with lock:
data = self._read()
today = time.strftime("%Y-%m-%d")
if "daily" not in data["stats"]:
data["stats"]["daily"] = {}
if today not in data["stats"]["daily"]:
data["stats"]["daily"][today] = {}
data["stats"]["daily"][today][section] = data["stats"]["daily"][today].get(section, 0) + 1
self._write(data)
def increment_ai_key_usage(self, key_id):
with lock:
data = self._read()
if str(key_id) in data["ai_keys"]:
data["ai_keys"][str(key_id)]["usage_count"] = data["ai_keys"][str(key_id)].get("usage_count", 0) + 1
data["ai_keys"][str(key_id)]["last_used"] = int(time.time())
self._write(data)
def increment_ai_key_error(self, key_id):
with lock:
data = self._read()
if str(key_id) in data["ai_keys"]:
data["ai_keys"][str(key_id)]["error_count"] = data["ai_keys"][str(key_id)].get("error_count", 0) + 1
self._write(data)
SCHEDULE_KEY = "_schedule"
def get_schedule_state(self) -> dict:
with lock:
data = self._read()
return data.get("stats", {}).get(self.SCHEDULE_KEY, {"day": "", "last_slot": -1})
def save_schedule_state(self, state: dict):
with lock:
data = self._read()
if "stats" not in data:
data["stats"] = {}
data["stats"][self.SCHEDULE_KEY] = state
self._write(data)
DAILY_SLOTS_KEY = "_daily_slots"
def get_slots_state(self) -> dict:
"""Persistent daily slots state for sections that declare fixed publish slots.
Shape: {"day": str, "sections": {section: {"fixed": {"HH:MM": fp|None},
"candidates": {"HH:MM": fp|None}, "published": {"HH:MM": fp|None},
"source_ids": {fp: source_id}}}}. Sections not yet seen today get empty dicts."""
with lock:
data = self._read()
if "stats" not in data:
data["stats"] = {}
return data["stats"].get(self.DAILY_SLOTS_KEY, {"day": "", "sections": {}})
def save_slots_state(self, state: dict):
with lock:
data = self._read()
if "stats" not in data:
data["stats"] = {}
data["stats"][self.DAILY_SLOTS_KEY] = state
self._write(data)
GEMINI_PENDING_KEY = "_gemini_pending"
def get_gemini_pending_queue(self) -> list:
with lock:
data = self._read()
return data.get(self.GEMINI_PENDING_KEY, [])
def save_gemini_pending_queue(self, queue: list):
with lock:
data = self._read()
data[self.GEMINI_PENDING_KEY] = queue
self._write(data)
def add_to_gemini_pending(self, raw_text: str, source_url: str = "", media: list = None,
fingerprint: str = "", channel_id: str = "", section: str = ""):
with lock:
data = self._read()
pending = data.get(self.GEMINI_PENDING_KEY, [])
# Avoid duplicate entries for the same fingerprint (e.g. re-enqueued after a failed attempt)
if fingerprint and any(p.get("fingerprint") == fingerprint for p in pending):
return
pending.append({
"raw_text": raw_text,
"source_url": source_url,
"media": media or [],
"fingerprint": fingerprint,
"channel_id": channel_id,
"section": section,
"attempts": 0,
"added_at": int(time.time()),
})
data[self.GEMINI_PENDING_KEY] = pending
self._write(data)
def remove_from_gemini_pending(self, index: int = 0):
with lock:
data = self._read()
pending = data.get(self.GEMINI_PENDING_KEY, [])
if 0 <= index < len(pending):
pending.pop(index)
data[self.GEMINI_PENDING_KEY] = pending
self._write(data)
def remove_pending_by_fingerprint(self, fingerprint: str):
"""Remove a pending item by fingerprint (safe against list reordering/races)."""
with lock:
data = self._read()
pending = data.get(self.GEMINI_PENDING_KEY, [])
new_pending = [p for p in pending if p.get("fingerprint") != fingerprint]
if len(new_pending) != len(pending):
data[self.GEMINI_PENDING_KEY] = new_pending
self._write(data)
def increment_pending_attempts(self, fingerprint: str) -> int:
"""Increment and return the attempt counter for a pending item. Returns -1 if not found."""
with lock:
data = self._read()
pending = data.get(self.GEMINI_PENDING_KEY, [])
for p in pending:
if p.get("fingerprint") == fingerprint:
p["attempts"] = p.get("attempts", 0) + 1
data[self.GEMINI_PENDING_KEY] = pending
self._write(data)
return p["attempts"]
return -1
MAX_BACKOFF_SECONDS = 3600
def set_pending_retry_after(self, fingerprint: str, attempts: int):
"""Apply exponential backoff to a pending item so the scheduler does not hot-loop
a repeatedly failing article. Returns the seconds until the next retry."""
seconds = min(self.MAX_BACKOFF_SECONDS, 60 * (2 ** max(0, attempts - 1)))
with lock:
data = self._read()
pending = data.get(self.GEMINI_PENDING_KEY, [])
for p in pending:
if p.get("fingerprint") == fingerprint:
p["retry_after"] = int(time.time()) + seconds
data[self.GEMINI_PENDING_KEY] = pending
self._write(data)
return seconds
return seconds
GEMINI_STATE_KEY = "_gemini"
def get_gemini_state(self) -> dict:
with lock:
data = self._read()
if "stats" not in data:
data["stats"] = {}
return data["stats"].get(self.GEMINI_STATE_KEY, {"global_cooldown_until": 0.0})
def save_gemini_state(self, state: dict):
with lock:
data = self._read()
if "stats" not in data:
data["stats"] = {}
data["stats"][self.GEMINI_STATE_KEY] = state
self._write(data) |