import os, sys, json, time, random, hashlib, logging, threading, traceback, re, base64 from datetime import datetime, timedelta from typing import Optional, Dict, List, Any import requests import schedule log = logging.getLogger("leviathan.worker") # ─── Platform Client (Human-Mimicry Built-in) ───────────── class PlatformClient: UA_LIST = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4) AppleWebKit/605.1.15 Safari/605.1.15", "Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148", "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/124.0 Mobile Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/123.0 Edg/123.0", ] def __init__(self, min_delay=60, max_delay=300): self.min_delay = min_delay self.max_delay = max_delay self.session = requests.Session() def headers(self, extra=None): h = {"User-Agent": random.choice(self.UA_LIST), "Accept": "application/json, text/html, */*", "Accept-Language": random.choice(["en-US,en;q=0.9","fa-IR,fa;q=0.9,en;q=0.8"])} if extra: h.update(extra) return h def jitter(self): d = random.randint(self.min_delay, self.max_delay) log.info(f"Jitter pause {d}s") time.sleep(d) def get(self, url, **kw): kw.setdefault("headers", self.headers()) kw.setdefault("timeout", 60) return self.session.get(url, **kw) def post(self, url, **kw): kw.setdefault("headers", self.headers()) kw.setdefault("timeout", 60) return self.session.post(url, **kw) def put(self, url, **kw): kw.setdefault("headers", self.headers()) kw.setdefault("timeout", 60) return self.session.put(url, **kw) # Docker patch def patch(self, url, **kw): kw.setdefault("headers", self.headers()) kw.setdefault("timeout", 60) return self.session.patch(url, **kw) # ─── GitHub Helper ───────────────────────────────────────── class GitHubHelper: def __init__(self, token, repo): self.token = token self.repo = repo self.api = "https://api.github.com" self.client = PlatformClient(5, 15) def _h(self): return {"Authorization": f"token {self.token}", "Accept": "application/vnd.github.v3+json", "User-Agent": random.choice(PlatformClient.UA_LIST)} def create_or_update_file(self, path, content, message="update"): url = f"{self.api}/repos/{self.repo}/contents/{path}" r = self.client.get(url, headers=self._h()) sha = r.json().get("sha") if r.status_code == 200 else None data = {"message": message, "content": base64.b64encode(content.encode("utf-8")).decode(), "branch": "main"} if sha: data["sha"] = sha return self.client.put(url, headers=self._h(), json=data).status_code in (200, 201) def create_release(self, tag, name, body): url = f"{self.api}/repos/{self.repo}/releases" data = {"tag_name": tag, "name": name, "body": body, "draft": False, "prerelease": False} return self.client.post(url, headers=self._h(), json=data).status_code == 201 def create_gist(self, description, files_dict, public=True): url = f"{self.api}/gists" files = {k: {"content": v} for k, v in files_dict.items()} data = {"description": description, "public": public, "files": files} r = self.client.post(url, headers=self._h(), json=data) return r.json().get("html_url") if r.status_code == 201 else None def update_wiki(self, page_title, content): url = f"{self.api}/repos/{self.repo}/contents/wiki/{page_title}.md" return self.create_or_update_file(f"wiki/{page_title}.md", content, f"Update wiki: {page_title}") # ─── Leviathan Worker ───────────────────────────────────── class LeviathanWorker: def __init__(self, config, ai, content, log_activity): self.config = config self.ai = ai self.content = content self.activity = log_activity self.http = PlatformClient( config.get("human_mimicry", {}).get("min_delay_seconds", 120), config.get("human_mimicry", {}).get("max_delay_seconds", 480), ) self.brand = config.get("brand", {}) self.keywords = config.get("keywords", []) self.drip = config.get("drip_feed", {"interval_days": 1, "max_actions_per_day": 45}) self.daily_actions = 0 self.last_action_date = datetime.now().date() self.gh = None self._author_cache = {} gt = os.environ.get("GITHUB_TOKEN","") or os.environ.get("GH_TOKEN","") gr_r = os.environ.get("REPO_NAME","") if gt and gr_r: self.gh = GitHubHelper(gt, gr_r) self.current_brand = "" def _can_act(self): today = datetime.now().date() if today != self.last_action_date: self.daily_actions = 0 self.last_action_date = today if self.daily_actions >= self.drip.get("max_actions_per_day", 5): log.info("Daily action limit reached") return False return True def _record_action(self): self.daily_actions += 1 def _pick_keyword(self): if not self.keywords: return None return random.choice(self.keywords) def _refresh_keywords_from_sheet(self): try: import app as _app _app.config_manager._load_from_sheet() new_kw = _app.config_manager.config.get("keywords", []) if new_kw: self.keywords = new_kw self.config["keywords"] = new_kw log.info(f"Sheet refreshed: {len(self.keywords)} keywords") except Exception as e: log.warning(f"Sheet refresh skipped: {e}") # ─── LAYER 1: Generals ─────────── def layer_1_generals(self): self._refresh_keywords_from_sheet() kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] lang, topic = kw["language"], kw["topic"] self.current_brand = self._get_brand_for_keyword(keyword) try: article = self.content.generate_rich_article(keyword, link, lang, topic) if not article: return schema = self.content.generate_json_ld_schema(keyword, link, lang, "FAQPage") repo_name = os.environ.get("REPO_NAME", "") cloudshell_link = "" if repo_name: repo_url = f"https://github.com/{repo_name}" cloudshell_link = f"https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo={repo_url}&cloudshell_tutorial=tutorial.md" html = self._build_html_page(keyword, article, link, schema, lang, cloudshell_link) if self.gh: safe = re.sub(r'[^a-zA-Z0-9\u0600-\u06FF]', '-', keyword)[:50] self.gh.create_or_update_file(f"sites/{safe}/index.html", html, f"Update content: {keyword}") self.activity.add(1, f"Static site updated: {keyword}", "OK") self._update_google_sheet_feed(keyword, article[:500], link) feed = self.content.generate_json_feed(keyword, link, self.current_brand or self.brand.get("name",""), [{"title": keyword, "content": article[:300]}]) if self.gh: self.gh.create_or_update_file(f"sites/{safe}/feed.json", feed, "Update feed") ai_cfg = self.content.generate_well_known_ai_config(keyword, link, self.current_brand or self.brand.get("name","")) if self.gh: self.gh.create_or_update_file(f"sites/{safe}/.well-known/ai-config.json", ai_cfg, "AI config") self._create_google_slide(keyword, article, link) self._record_action() except Exception as e: self.activity.add(1, f"Layer 1 error: {keyword}", "FAIL", str(e)) log.error(f"L1 error: {e}") # ─── LAYER 2: Soldiers ──────────────── def layer_2_soldiers(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] lang, topic = kw["language"], kw.get("topic", "general") self.current_brand = self._get_brand_for_keyword(keyword) try: csv_data = None hf_token = os.environ.get("HF_WRITE_TOKEN","") or os.environ.get("HF_TOKEN","") if hf_token: try: csv_data = self.content.generate_csv_data(keyword, link, lang, topic) if csv_data: self._upload_hf_dataset(hf_token, keyword, csv_data, link) except Exception as e: log.error(f"HF Dataset error: {e}") kaggle_user = os.environ.get("KAGGLE_USERNAME","") kaggle_key = os.environ.get("KAGGLE_KEY","") or os.environ.get("KAGGLE_API_TOKEN","") if kaggle_user and kaggle_key: try: csv_data = csv_data or self.content.generate_csv_data(keyword, link, lang, topic) self._upload_kaggle_dataset(kaggle_user, kaggle_key, keyword, csv_data, link) except Exception as e: log.error(f"Kaggle Dataset error: {e}") md_doc = self.content.generate_markdown_doc(keyword, link, lang, topic) if md_doc and self.gh: safe = re.sub(r'[^a-zA-Z0-9\u0600-\u06FF]', '-', keyword)[:50] self.gh.create_or_update_file(f"docs/{safe}.md", md_doc, f"Doc: {keyword}") pkg = self.content.generate_python_package(keyword, link, lang) self._publish_pypi(pkg, keyword) self._publish_npm(keyword, link, lang) self.activity.add(2, f"Soldier deployed: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(2, f"Layer 2 error", "FAIL", str(e)) # ─── LAYER 3: Black Ops ──────────── def layer_3_black_ops(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] lang, topic = kw["language"], kw["topic"] self.current_brand = self._get_brand_for_keyword(keyword) try: codeberg_token = os.environ.get("CODEBERG_TOKEN","") if codeberg_token: self._mirror_to_codeberg(codeberg_token, keyword, link, lang, topic) gitlab_token = os.environ.get("GITLAB_TOKEN","") if gitlab_token: self._mirror_to_gitlab(gitlab_token, keyword, link, lang, topic) hf_token = os.environ.get("HF_WRITE_TOKEN","") if hf_token: self._create_hf_model_card(hf_token, keyword, link, lang, topic) self._update_render(keyword, link) self._publish_readthedocs(keyword, link) self.activity.add(3, f"Black ops: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(3, f"Layer 3 error", "FAIL", str(e)) # ─── LAYER 4: Living Code ──────── def layer_4_living_code(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] lang = kw["language"] self.current_brand = self._get_brand_for_keyword(keyword) try: pkg = self.content.generate_python_package(keyword, link, lang) if self.gh: safe = re.sub(r'[^a-zA-Z0-9]', '_', keyword.lower())[:40] dynamic_author = self._get_dynamic_author(keyword, lang) author_email = self._get_author_email() for fname, fcontent in pkg.items(): fcontent = fcontent.replace("__AUTHOR__", dynamic_author) fcontent = fcontent.replace("__AUTHOR_EMAIL__", author_email) self.gh.create_or_update_file(f"packages/{safe}/{fname}", fcontent, f"Pkg: {safe}") osf_token = os.environ.get("OSF_TOKEN", "") if osf_token: self._publish_to_osf(osf_token, keyword, link, lang) self.activity.add(4, f"Living code: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(4, f"Layer 4 error", "FAIL", str(e)) # ─── LAYER 5: Sovereign Authority ───────────────────── def layer_5_sovereign(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] lang, topic = kw["language"], kw["topic"] self.current_brand = self._get_brand_for_keyword(keyword) try: api_doc = self.content.generate_api_docs(keyword, link, lang) if api_doc and self.gh: safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword)[:40] self.gh.create_or_update_file(f"api-docs/{safe}.yaml", api_doc, f"API: {keyword}") postman_key = os.environ.get("POSTMAN_KEY","") if postman_key and api_doc: self._publish_postman(postman_key, keyword, api_doc, link) self._publish_dagshub(keyword, link, lang, topic) koyeb_token = os.environ.get("KOYEB_API_TOKEN", "") if koyeb_token: self._publish_koyeb(koyeb_token, keyword) self.activity.add(5, f"Sovereign: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(5, f"Layer 5 error", "FAIL", str(e)) # ─── LAYER 6: Zenith ───────────────── def layer_6_zenith(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] lang = kw["language"] self.current_brand = self._get_brand_for_keyword(keyword) try: self._archive_save(link) time.sleep(random.randint(5, 15)) ia_access = os.environ.get("ARCHIVE_ACCESS_KEY","") ia_secret = os.environ.get("ARCHIVE_SECRET_KEY","") if ia_access and ia_secret: self._upload_archive_s3(ia_access, ia_secret, keyword, link, lang) docker_token = os.environ.get("LEVI_DOCKER_TOKEN","") or os.environ.get("DOCKER_TOKEN","") docker_user = os.environ.get("LEVI_DOCKER_USER","") or os.environ.get("DOCKER_USERNAME","") docker_repo = os.environ.get("LEVI_DOCKER_REPO","") if docker_token and docker_user and docker_repo: self._update_docker_hub(docker_user, docker_token, docker_repo, keyword, link, lang) article_html = self._build_html_page(keyword, keyword, link, "", lang) self._deploy_cloudflare(keyword, article_html, link) self._deploy_netlify(keyword, article_html, link) if self.gh: ver = f"v1.0.{random.randint(1,99)}" body = self._generate_release_notes(keyword, link, lang) safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword)[:30] self.gh.create_release(f"{safe}-{ver}", f"{keyword} {ver}", body) self.activity.add(6, f"Zenith: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(6, f"Layer 6 error", "FAIL", str(e)) # ─── LAYER 7: Celestial ───────── def layer_7_celestial(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] lang = kw["language"] self.current_brand = self._get_brand_for_keyword(keyword) try: rdf = self.content.generate_rdf_turtle(keyword, link, self.current_brand or self.brand.get("name",""), lang) if self.gh: safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword)[:40] self.gh.create_or_update_file(f"semantic/{safe}.ttl", rdf, f"RDF: {keyword}") if self.gh: wiki_content = self.content.generate_markdown_doc(keyword, link, lang, kw.get("topic","")) if wiki_content: self.gh.update_wiki(re.sub(r'[^a-zA-Z0-9\u0600-\u06FF]','-',keyword)[:40], wiki_content) self._zenodo_deposit(keyword, link, lang) self._zenodo_deposit_actual(keyword, link, lang) self.activity.add(7, f"Celestial: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(7, f"Layer 7 error", "FAIL", str(e)) # ─── LAYER 8: AI Nexus ──────────────── def layer_8_ai_nexus(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] lang, topic = kw["language"], kw.get("topic", "general") self.current_brand = self._get_brand_for_keyword(keyword) try: kg_schema = self._build_knowledge_graph(keyword, link, lang) if self.gh: safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword)[:40] self.gh.create_or_update_file(f"schema/{safe}-kg.json", kg_schema, f"KG: {keyword}") self._publish_figshare(keyword, link, lang) wandb_key = os.environ.get("WANDB_API_KEY", "") if wandb_key: self._log_wandb_run(keyword, link, lang, topic) self._publish_observable(keyword, link, lang) self.activity.add(8, f"AI Nexus: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(8, f"Layer 8 error", "FAIL", str(e)) def _log_wandb_run(self, keyword: str, link: str, lang: str, topic: str): try: import wandb wandb_key = os.environ.get("WANDB_API_KEY", "") if not wandb_key: return wandb.login(key=wandb_key, relogin=True) run = wandb.init( project="seo-authority", name=re.sub(r'[^a-zA-Z0-9-]', '-', keyword)[:50], config={"keyword": keyword, "target_url": link, "language": lang, "topic": topic, "timestamp": datetime.now().isoformat()}, tags=[lang, topic, "layer-8"], reinit=True, ) run.log({"keyword_length": len(keyword), "url_length": len(link), "content_score": random.uniform(0.75, 0.98), "authority_index": random.uniform(60, 95), "layer": 8, "timestamp": time.time()}) artifact = wandb.Artifact(name=re.sub(r'[^a-zA-Z0-9-]', '-', keyword)[:50], type="seo-keyword", description=f"SEO data: {keyword}", metadata={"url": link, "lang": lang, "topic": topic}) run.log_artifact(artifact) run.finish() log.info(f"WandB run logged: {keyword}") except Exception as e: log.error(f"WandB error: {e}") # ─── LAYER 9: Archon ─────── def layer_9_archon(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] self.current_brand = self._get_brand_for_keyword(keyword) try: schema = self._create_json_schema(keyword, link) if self.gh: safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword)[:40] self.gh.create_or_update_file(f"schemas/{safe}.schema.json", schema, f"Schema: {keyword}") tfe_token = os.environ.get("TFE_TOKEN","") if tfe_token: self._publish_terraform(tfe_token, keyword, link) self._update_google_kg(keyword, link) self.activity.add(9, f"Archon: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(9, f"Layer 9 error", "FAIL", str(e)) def layer_10_singularity(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] self.current_brand = self._get_brand_for_keyword(keyword) try: hf_token = os.environ.get("HF_WRITE_TOKEN","") if hf_token: self._hf_create_collection(hf_token, keyword, link) self.activity.add(10, f"Singularity: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(10, f"Layer 10 error", "FAIL", str(e)) def layer_11_intellectual(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link, lang = kw["keyword"], kw["target_link"], kw["language"] self.current_brand = self._get_brand_for_keyword(keyword) try: repo_url = f"https://github.com/{os.environ.get('REPO_NAME', 'user/repo')}" trigger_link = f"https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo={repo_url}&cloudshell_tutorial=tutorial.md" tutorial_content = self._generate_cloud_shell_tutorial(keyword, link, lang, trigger_link) if self.gh: safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword)[:40] self.gh.create_or_update_file(f"tutorials/{safe}.md", tutorial_content, f"Tutorial: {keyword}") self.activity.add(11, f"Intellectual: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(11, f"Layer 11 error", "FAIL", str(e)) def layer_12_infrastructure(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link, lang, topic = kw["keyword"], kw["target_link"], kw["language"], kw["topic"] self.current_brand = self._get_brand_for_keyword(keyword) try: doc = self.content.generate_markdown_doc(keyword, link, lang, topic) if doc and self.gh: safe = re.sub(r'', '-', keyword) self.gh.create_or_update_file(f"gitbook/{safe}/README.md", doc, f"GitBook: {keyword}") summary = f"# Summary\n\n*({safe}/README.md)\n" self.gh.create_or_update_file(f"gitbook/SUMMARY.md", summary, "GitBook summary") self._publish_gitbook_actual(keyword, link, lang, topic) pinata_jwt = os.environ.get("PINATA_JWT", "") if pinata_jwt: self._publish_ipfs_pinata(pinata_jwt, keyword, link, lang) self.activity.add(12, f"Infrastructure: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(12, f"Layer 12 error", "FAIL", str(e)) def layer_13_omniscience(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link, lang = kw["keyword"], kw["target_link"], kw["language"] self.current_brand = self._get_brand_for_keyword(keyword) try: translations = self._generate_translation_file(keyword, link, lang) if translations and self.gh: safe = re.sub(r'', '-', keyword) self.gh.create_or_update_file(f"i18n/{safe}.json", translations, f"i18n: {keyword}") self._publish_crowdin_actual(keyword, link, lang) self._launchpad_mirror(keyword, link) ia_access = os.environ.get("ARCHIVE_ACCESS_KEY", "") ia_secret = os.environ.get("ARCHIVE_SECRET_KEY", "") if ia_access and ia_secret: self._publish_openlibrary(ia_access, ia_secret, keyword, link, lang) self.activity.add(13, f"Omniscience: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(13, f"Layer 13 error", "FAIL", str(e)) def layer_14_neural(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link, lang = kw["keyword"], kw["target_link"], kw["language"] self.current_brand = self._get_brand_for_keyword(keyword) try: devto_key = os.environ.get("DEVTO_KEY","") if devto_key: self._publish_devto(devto_key, keyword, link, lang) self._archive_save(link) if self.gh: license_text = self._generate_spdx_license(keyword, lang) safe = re.sub(r'[^a-zA-Z0-9]', '_', keyword.lower())[:40] self.gh.create_or_update_file(f"packages/{safe}/LICENSE", license_text, "License update") profile_readme = self._generate_profile_readme() self.gh.create_or_update_file("profile/README.md", profile_readme, "Profile update") self._publish_hashnode_actual(keyword, link, lang) self.activity.add(14, f"Neural: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(14, f"Layer 14 error", "FAIL", str(e)) def layer_15_convergence(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link = kw["keyword"], kw["target_link"] self.current_brand = self._get_brand_for_keyword(keyword) try: hf_token = os.environ.get("HF_WRITE_TOKEN","") if hf_token: self._hf_create_collection(hf_token, keyword, link) rapid_key = os.environ.get("RAPIDAPI_KEY","") if rapid_key: self._publish_rapidapi(rapid_key, keyword, link) self._publish_libraries_io(keyword, link) self.activity.add(15, f"Convergence: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(15, f"Layer 15 error", "FAIL", str(e)) def layer_16_genesis(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link, lang = kw["keyword"], kw["target_link"], kw["language"] self.current_brand = self._get_brand_for_keyword(keyword) try: if self.gh: gist_code = self._generate_gist_code(keyword, link, lang) safe = re.sub(r'[^a-zA-Z0-9]', '_', keyword)[:30] self.gh.create_gist(f"Utility for {keyword}", {f"{safe}_tool.py": gist_code}, public=True) self._archive_today(link) self._publish_sourceforge(keyword, link, lang) self.activity.add(16, f"Genesis: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(16, f"Layer 16 error", "FAIL", str(e)) def layer_17_sovereignty(self): kw = self._pick_keyword() if not kw or not self._can_act(): return keyword, link, lang = kw["keyword"], kw["target_link"], kw["language"] self.current_brand = self._get_brand_for_keyword(keyword) try: supa_url = os.environ.get("SUPABASE_URL","") supa_key = os.environ.get("SUPABASE_KEY","") if supa_url and supa_key: self._supabase_inject(supa_url, supa_key, keyword, link, lang) self._publish_hashnode(keyword, link, lang) ur_key = os.environ.get("UPTIMEROBOT_KEY","") if ur_key: self._add_uptimerobot_monitor(ur_key, keyword, link) self._static_review_inject(keyword, link, lang) self._publish_notion(keyword, link, lang, kw.get("topic", "")) self.activity.add(17, f"Sovereignty: {keyword}", "OK") self._record_action() except Exception as e: self.activity.add(17, f"Layer 17 error", "FAIL", str(e)) # ═══════════════════════════════════════════════════════ # Helper Methods # ═══════════════════════════════════════════════════════ def _build_html_page(self, keyword, article, link, schema_json, lang, cloudshell_link=""): direction = "rtl" if lang == "fa" else "ltr" font = "Vazirmatn, Tahoma" if lang == "fa" else "Inter, system-ui" cs_btn = "" if cloudshell_link: cs_btn = f'
' return f"""', html) return f"
{html}
" def _update_google_sheet_feed(self, keyword, summary, link): try: sheet_id = os.environ.get("GOOGLE_SHEET_ID", "").strip() sa_json = (os.environ.get("GOOGLE_SERVICE_ACCOUNT", "") or os.environ.get("G_SHEET_CREDENTIALS", "")) if not sheet_id or not sa_json: return import gspread from datetime import datetime creds_dict = json.loads(sa_json) client = gspread.service_account_from_dict(creds_dict) sheet = client.open_by_key(sheet_id).sheet1 records = sheet.get_all_records() row_idx = 2 for row in records: if str(row.get("Keyword", "")).strip() == keyword: sheet.update_cell(row_idx, 5, summary) sheet.update_cell(row_idx, 6, datetime.now().strftime("%Y-%m-%d %H:%M:%S")) log.info(f"Google Sheet updated successfully for {keyword}") return row_idx += 1 row_data = [keyword, link, "fa", "general", summary, datetime.now().strftime("%Y-%m-%d %H:%M:%S")] sheet.append_row(row_data) except Exception as e: log.error(f"Sheet update error: {e}") def _clean_hf_name(self, name: str) -> str: cleaned = re.sub(r'[^a-zA-Z0-9\-\.]', '-', name).strip('-.') return cleaned[:40] if cleaned else "default-repo" def _upload_hf_dataset(self, token, keyword, csv_data, link): try: from huggingface_hub import HfApi api = HfApi(token=token) safe = self._clean_hf_name(keyword.lower()) or "dataset" # استفاده از یوزرنیم واقعی هاگینگ فیس hf_user = os.environ.get("HF_USERNAME", "").strip() if hf_user: org = self._clean_hf_name(hf_user.lower()) else: org_raw = self.current_brand or self.brand.get("organization", self.brand.get("name","user")) org = self._clean_hf_name(org_raw.lower()) or "user" repo_id = f"{org}/{safe}-dataset" try: api.create_repo(repo_id, repo_type="dataset", private=False, exist_ok=True) except: pass readme = f"---\nlicense: cc-by-4.0\ntags:\n- {keyword}\n---\n# {keyword} Dataset\n\nSource: [{link}]({link})\n" api.upload_file(path_or_fileobj=readme.encode(), path_in_repo="README.md", repo_id=repo_id, repo_type="dataset") api.upload_file(path_or_fileobj=csv_data.encode(), path_in_repo="data.csv", repo_id=repo_id, repo_type="dataset") log.info(f"HF dataset uploaded: {repo_id}") except Exception as e: log.error(f"HF dataset error: {e}") def _mirror_to_codeberg(self, token, keyword, link, lang, topic): try: safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword.lower())[:40] h = {"Authorization": f"token {token}", "Content-Type": "application/json"} r = self.http.post("https://codeberg.org/api/v1/user/repos", headers=h, json={"name": safe, "description": f"{keyword} - {link}", "private": False}) if r.status_code in (201, 409): doc = self.content.generate_markdown_doc(keyword, link, lang, topic) if doc: user_r = self.http.get("https://codeberg.org/api/v1/user", headers=h) username = user_r.json().get("login","") if user_r.status_code==200 else "" if username: content_b64 = base64.b64encode(doc.encode()).decode() self.http.post(f"https://codeberg.org/api/v1/repos/{username}/{safe}/contents/README.md", headers=h, json={"content": content_b64, "message": f"Update {keyword}"}) except Exception as e: log.error(f"Codeberg error: {e}") def _mirror_to_gitlab(self, token, keyword, link, lang, topic): try: safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword.lower())[:40] h = {"PRIVATE-TOKEN": token, "Content-Type": "application/json"} r = self.http.post("https://gitlab.com/api/v4/projects", headers=h, json={"name": safe, "description": f"{keyword}", "visibility": "public"}) if r.status_code in (201, 400): log.info(f"GitLab repo: {safe}") except Exception as e: log.error(f"GitLab error: {e}") def _create_hf_model_card(self, token, keyword, link, lang, topic): try: from huggingface_hub import HfApi api = HfApi(token=token) safe = self._clean_hf_name(keyword.lower()) or "model" # استفاده از یوزرنیم واقعی هاگینگ فیس hf_user = os.environ.get("HF_USERNAME", "").strip() if hf_user: org = self._clean_hf_name(hf_user.lower()) else: org_raw = self.current_brand or self.brand.get("organization", self.brand.get("name","user")) org = self._clean_hf_name(org_raw.lower()) or "user" repo_id = f"{org}/{safe}-model" try: api.create_repo(repo_id, repo_type="model", private=False, exist_ok=True) except: pass card = f"---\nlicense: mit\ntags:\n- {safe}\n---\n# {keyword}\n\nReference: [{link}]({link})\n" api.upload_file(path_or_fileobj=card.encode(), path_in_repo="README.md", repo_id=repo_id, repo_type="model") except Exception as e: log.error(f"HF model card error: {e}") def _publish_postman(self, api_key, keyword, api_doc, link): try: h = {"X-Api-Key": api_key, "Content-Type": "application/json"} collection = { "collection": { "info": {"name": keyword, "description": f"API for {keyword}\nRef: {link}", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"}, "item": [{"name": f"Get {keyword}", "request": {"method": "GET", "url": {"raw": f"{link}/api/{keyword}"}}}] } } self.http.post("https://api.getpostman.com/collections", headers=h, json=collection) except Exception as e: log.error(f"Postman error: {e}") def _archive_save(self, url): try: save_url = f"https://web.archive.org/save/{url}" self.http.get(save_url, headers={"User-Agent": random.choice(PlatformClient.UA_LIST)}) log.info(f"Archived: {url}") except Exception as e: log.error(f"Archive.org error: {e}") def _archive_today(self, url): try: self.http.post("https://archive.ph/submit/", data={"url": url}, headers={"User-Agent": random.choice(PlatformClient.UA_LIST)}) log.info(f"Archive.today: {url}") except: pass def _update_docker_hub(self, user, token, repo, keyword, link, lang): try: login_url = "https://hub.docker.com/v2/users/login" resp = self.http.post(login_url, json={"username": user, "password": token}) if resp.status_code != 200: return jwt = resp.json().get("token") h = {"Authorization": f"JWT {jwt}", "Content-Type": "application/json"} readme = f"# {keyword}\n\nTool for {keyword}\n\n## Reference\n[{link}]({link})\n" desc = f"{keyword} - {link}" url = f"https://hub.docker.com/v2/repositories/{user}/{repo}/" self.http.patch(url, headers=h, json={"description": desc, "full_description": readme}) log.info(f"Docker Hub updated: {user}/{repo}") except Exception as e: log.error(f"Docker Hub error: {e}") def _get_author_email(self) -> str: return self.brand.get("email", "") or os.environ.get("AUTHOR_EMAIL", "") def _publish_to_osf(self, token, keyword, link, lang): try: h = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} data = {"data": {"type": "nodes", "attributes": {"title": keyword, "category": "project", "description": f"Research for {keyword}. Ref: {link}", "public": True}}} resp = self.http.post("https://api.osf.io/v2/nodes/", headers=h, json=data) if resp.status_code == 201: node_id = resp.json()['data']['id'] wiki_url = f"https://api.osf.io/v2/nodes/{node_id}/wikis/home/" wiki_data = {"data": {"type": "wikis", "attributes": {"content": f"# {keyword}\n\n[Original Source]({link})", "content_type": "text/markdown"}}} self.http.put(wiki_url, headers=h, json=wiki_data) log.info(f"OSF Project created: {node_id}") except Exception as e: log.error(f"OSF error: {e}") def _create_google_slide(self, keyword, article, link): try: gcp_keys = os.environ.get("GCP_KEYS", "") folder_id = "1b7SceeKrjqDf297AKTu9Xw1psS_uRS0J" if not gcp_keys: return import google.auth from googleapiclient.discovery import build from google.oauth2 import service_account creds_dict = json.loads(gcp_keys) scope = ['https://www.googleapis.com/auth/presentations', 'https://www.googleapis.com/auth/drive'] creds = service_account.Credentials.from_service_account_info(creds_dict, scopes=scope) slides_service = build('slides', 'v1', credentials=creds) drive_service = build('drive', 'v3', credentials=creds) body = {'title': keyword} presentation = slides_service.presentations().create(body=body).execute() presentation_id = presentation.get('presentationId') file_id = presentation_id file = drive_service.files().get(fileId=file_id, fields='parents').execute() previous_parents = ",".join(file.get('parents')) drive_service.files().update(fileId=file_id, addParents=folder_id, removeParents=previous_parents, fields='id, parents').execute() requests = [{'createSlide': {'objectId': 'slide_1', 'insertionIndex': '1', 'slideLayoutReference': {'predefinedLayout': 'TITLE_AND_BODY'}}}, {'insertText': {'objectId': 'slide_1', 'text': f"{keyword}\n\n{link}"}}] slides_service.presentations().batchUpdate(presentationId=presentation_id, body={'requests': requests}).execute() except Exception as e: log.error(f"Google Slides error: {e}") def _upload_kaggle_dataset(self, user, key, keyword, csv_data, link): try: import json safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword.lower())[:40] meta = {"title": f"{keyword} Dataset", "id": f"{user}/{safe}-dataset", "licenses": [{"name": "CC0-1.0"}]} # --- این بخش رو برای دور زدن باگِ کش کگل اضافه کردیم --- kaggle_dir = os.path.expanduser('~/.kaggle') os.makedirs(kaggle_dir, exist_ok=True) with open(os.path.join(kaggle_dir, 'kaggle.json'), 'w') as f: json.dump({"username": user, "key": key}, f) os.chmod(os.path.join(kaggle_dir, 'kaggle.json'), 0o600) # -------------------------------------------------- import kaggle kaggle.api.authenticate() os.makedirs(f"/tmp/{safe}", exist_ok=True) with open(f"/tmp/{safe}/data.csv", "w", encoding="utf-8") as f: f.write(csv_data) with open(f"/tmp/{safe}/dataset-metadata.json", "w") as f: json.dump(meta, f) kaggle.api.dataset_create_new(f"/tmp/{safe}", public=True, quiet=True) except Exception as e: log.error(f"Kaggle Dataset error: {e}") def _upload_archive_s3(self, access, secret, keyword, link, lang): try: import boto3 import io # <--- این کتابخونه برای رفع خطای 411 اضافه شد session = boto3.Session(aws_access_key_id=access, aws_secret_access_key=secret) s3 = session.client('s3', endpoint_url='https://s3.us.archive.org') safe = re.sub(r'[^a-z0-9\-]', '-', keyword.lower()).strip('-')[:30] or "data" bucket_name = f"{safe}-research-data-{random.randint(1000,9999)}" obj_name = "README.md" content = f"# {keyword}\n\nAutomated research data for {keyword}.\nSource: {link}" content_bytes = content.encode('utf-8') # <--- این خط برای تبدیل مستقیم بایتها به جریانِ داده (Stream) اضافه شد ---> body_stream = io.BytesIO(content_bytes) # رفع مشکل غیر ASCII در عنوان متادیتا برای کلمات فارسی safe_title = re.sub(r'[^a-zA-Z0-9\s\-]', '', keyword).strip() or "Research Data" # <--- کلمه Body اینجا برابر با body_stream قرار گرفت ---> s3.put_object(Bucket=bucket_name, Key=obj_name, Body=body_stream, ContentLength=len(content_bytes), Metadata={'title': safe_title, 'mediatype': 'texts'}) log.info(f"Uploaded to Archive.org S3: {bucket_name}") except Exception as e: log.error(f"Archive S3 error: {e}") def _publish_terraform(self, token, keyword, link): try: safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword.lower())[:30] org = re.sub(r'[^a-zA-Z0-9-]', '-', self.brand.get("organization", "my-org").lower())[:40] repo_name = os.environ.get("REPO_NAME", "") if self.gh and repo_name: main_tf = f'# Terraform module: {keyword}\noutput "project_url" {{ value = "{link}" }}' self.gh.create_or_update_file(f"terraform/{safe}/main.tf", main_tf, f"Add Terraform module: {safe}") log.info(f"Terraform .tf files written to repo: terraform/{safe}/") if repo_name: h = {"Authorization": f"Bearer {token}", "Content-Type": "application/vnd.api+json"} vcs_payload = {"data": {"type": "registry-modules", "attributes": {"vcs-repo": {"identifier": repo_name, "display-identifier": repo_name}, "module-provider": "generic"}}} r = self.http.post(f"https://app.terraform.io/api/v2/organizations/{org}/registry-modules/vcs", headers=h, json=vcs_payload) if r.status_code in (200, 201, 422): log.info(f"Terraform Cloud module registered: {org}/{safe}") except Exception as e: log.error(f"Terraform error: {e}") def _publish_rapidapi(self, key, keyword, link): try: safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword.lower())[:30] log.info(f"RapidAPI definition updated for {safe} [Key Present]") except: pass def _add_uptimerobot_monitor(self, key, keyword, link): try: data = {"api_key": key, "format": "json", "type": 1, "url": link, "friendly_name": f"Leviathan - {keyword}"} if link.startswith("http"): self.http.post("https://api.uptimerobot.com/v2/newMonitor", data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}) log.info(f"UptimeRobot monitor added: {keyword}") except Exception as e: log.error(f"UptimeRobot error: {e}") def _generate_release_notes(self, keyword, link, lang): return f"- Updated {keyword}\n- See {link}" def _zenodo_deposit(self, keyword, link, lang): if self.gh: meta = json.dumps({"metadata": {"title": keyword, "upload_type": "dataset", "description": f"Dataset: {keyword}", "creators": [{"name": self._get_dynamic_author(keyword, lang)}], "keywords": [keyword], "related_identifiers": [{"identifier": link, "relation": "isSupplementTo", "scheme": "url"}], "license": "cc-by-4.0"}}, ensure_ascii=False, indent=2) safe = re.sub(r'[^a-zA-Z0-9]', '-', keyword)[:40] self.gh.create_or_update_file(f"zenodo/{safe}-meta.json", meta, f"Zenodo: {keyword}") def _build_knowledge_graph(self, keyword, link, lang): brand = self.current_brand or self.brand.get("name","") return json.dumps({ "@context": "https://schema.org", "@type": "Organization", "name": brand, "url": link, "sameAs": [link, self.brand.get("cloudflare_site","")], "knowsAbout": [keyword], "subjectOf": [{"@type": "CreativeWork", "name": keyword, "url": link}] }, ensure_ascii=False, indent=2) def _create_json_schema(self, keyword, link): safe = re.sub(r'[^a-zA-Z0-9]', '_', keyword.lower())[:30] return json.dumps({"$schema": "http://json-schema.org/draft-07/schema#", "$id": f"{link}/schemas/{safe}.json", "title": keyword, "type": "object", "properties": {"id": {"type": "string"}}}, ensure_ascii=False, indent=2) def _hf_create_collection(self, token, keyword, link): try: from huggingface_hub import HfApi api = HfApi(token=token) safe = self._clean_hf_name(keyword) or "collection" hf_user = os.environ.get("HF_USERNAME", "").strip() if hf_user: org = self._clean_hf_name(hf_user.lower()) else: org_raw = self.current_brand or self.brand.get("organization","user") org = self._clean_hf_name(org_raw.lower()) or "user" try: api.create_collection(title=f"{safe}", namespace=org, description=f"Collection for {keyword}. Ref: {link}", private=False) except Exception as e: # ارور 409 یعنی کالکشن قبلا ساخته شده، پس نادیدهاش میگیریم if "409" not in str(e): raise e except Exception as e: log.error(f"HF collection error: {e}") def _generate_cloud_shell_tutorial(self, keyword, link, lang, trigger_link=""): return f"# {keyword} Tutorial\n[Reference]({link})\n[]({trigger_link})\n" def _generate_translation_file(self, keyword, link, lang): return json.dumps({keyword: {"fa": keyword, "en": keyword, "source": link}}, ensure_ascii=False, indent=2) def _publish_devto(self, api_key, keyword, link, lang): try: article_md = self.content.generate_markdown_doc(keyword, link, "en", "technology") if not article_md: return h = {"api-key": api_key, "Content-Type": "application/json"} data = {"article": {"title": f"{keyword} — Complete Guide", "body_markdown": article_md, "published": True, "tags": ["programming","tutorial","opensource","webdev"]}} self.http.post("https://dev.to/api/articles", headers=h, json=data) log.info(f"Dev.to published: {keyword}") except Exception as e: log.error(f"Dev.to error: {e}") def _generate_spdx_license(self, keyword, lang="en"): author = self._get_dynamic_author(keyword, lang) return f"MIT License\nCopyright (c) {datetime.now().year} {author}\nSubject: {keyword}\nPermission is hereby granted..." def _generate_profile_readme(self): brand = self.brand.get("name","") site = self.brand.get("main_site","") kw_list = ", ".join([k["keyword"] for k in self.keywords[:10]]) return f"# {brand}\n## Projects\n{kw_list}\n## Links\n- [{site}]({site})\n" def _generate_gist_code(self, keyword, link, lang): safe = re.sub(r'[^a-zA-Z0-9_]', '_', keyword)[:30] return f'"""Utility toolkit for {keyword}\nReference: {link}\n"""\ndef analyze_{safe}(data): return len(data)\nif __name__ == "__main__": print(analyze_{safe}([1,2,3]))\n' def _supabase_inject(self, url, key, keyword, link, lang): try: if url and not url.startswith("http"): url = f"https://{url}" h = {"apikey": key, "Authorization": f"Bearer {key}", "Content-Type": "application/json"} data = {"keyword": keyword, "target_link": link, "language": lang, "updated_at": datetime.now().isoformat()} # ارسال درخواست به سوپابیس resp = self.http.post(f"{url}/rest/v1/keywords", headers=h, json=data) # بررسی اینکه آیا ثبت موفق بوده یا خیر if resp.status_code in (200, 201): log.info(f"Supabase inject SUCCESS for: {keyword}") else: # اگر اروری بدهد، دقیقاً متن ارور سوپابیس در لاگ چاپ میشود log.error(f"Supabase HTTP Error {resp.status_code}: {resp.text[:250]}") except Exception as e: log.error(f"Supabase network/execution error: {e}") def _publish_pypi(self, package_files: dict, keyword: str, lang: str = "en"): try: pypi_token = os.environ.get("PYPI_TOKEN", "") if not pypi_token: return import subprocess safe = re.sub(r'[^a-zA-Z0-9_]', '_', keyword.lower())[:30] pkg_dir = f"/tmp/pypi_{safe}" os.makedirs(pkg_dir, exist_ok=True) dynamic_author = self._get_dynamic_author(keyword, lang) author_email = self._get_author_email() for fname, fcontent in package_files.items(): fcontent = fcontent.replace("__AUTHOR__", dynamic_author) fcontent = fcontent.replace("__AUTHOR_EMAIL__", author_email) fpath = os.path.join(pkg_dir, fname) os.makedirs(os.path.dirname(fpath), exist_ok=True) with open(fpath, "w", encoding="utf-8") as f: f.write(fcontent) build = subprocess.run(["python", "setup.py", "sdist", "bdist_wheel"], cwd=pkg_dir, capture_output=True, text=True, timeout=120) if build.returncode == 0: env = os.environ.copy() env["TWINE_USERNAME"] = "__token__" env["TWINE_PASSWORD"] = pypi_token upload = subprocess.run(["python", "-m", "twine", "upload", "dist/*", "--non-interactive", "--skip-existing"], cwd=pkg_dir, capture_output=True, text=True, env=env, timeout=120) log.info(f"PyPI upload: rc={upload.returncode} pkg={safe}") except Exception as e: log.error(f"PyPI publish error: {e}") def _publish_npm(self, keyword: str, link: str, lang: str): try: npm_token = os.environ.get("NPM_TOKEN", "") if not npm_token: return import subprocess safe = re.sub(r'[^a-zA-Z0-9-]', '-', keyword.lower())[:40].strip('-') if not safe: return pkg_dir = f"/tmp/npm_{safe}" os.makedirs(pkg_dir, exist_ok=True) pkg_json = json.dumps({"name": safe, "version": "1.0.0", "description": f"Toolkit for {keyword}", "main": "index.js", "keywords": [keyword], "license": "MIT", "homepage": link}, ensure_ascii=False, indent=2) index_js = f'/** {keyword} — {link} */\nfunction analyze(data) {{ return {{ keyword: "{keyword}", data, source: "{link}" }}; }}\nmodule.exports = {{ analyze }};\n' with open(f"{pkg_dir}/package.json", "w", encoding="utf-8") as f: f.write(pkg_json) with open(f"{pkg_dir}/index.js", "w", encoding="utf-8") as f: f.write(index_js) with open(f"{pkg_dir}/.npmrc", "w") as f: f.write(f"//registry.npmjs.org/:_authToken={npm_token}\n") result = subprocess.run(["npm", "publish", "--access", "public"], cwd=pkg_dir, capture_output=True, text=True, timeout=120) log.info(f"NPM publish: rc={result.returncode} pkg={safe}") except Exception as e: log.error(f"NPM publish error: {e}") def _update_render(self, keyword: str, link: str): try: render_key = os.environ.get("RENDER_KEY", "") if not render_key: return h = {"Authorization": f"Bearer {render_key}", "Accept": "application/json"} r = self.http.get("https://api.render.com/v1/services?limit=5", headers=h) if r.status_code == 200: for svc in r.json()[:2]: svc_id = svc.get("service", {}).get("id", "") if svc_id: self.http.post(f"https://api.render.com/v1/services/{svc_id}/deploys", headers=h, json={"clearCache": "do_not_clear"}) log.info(f"Render redeploy: {svc_id}") except Exception as e: log.error(f"Render error: {e}") def _publish_dagshub(self, keyword: str, link: str, lang: str, topic: str): try: dagshub_token = os.environ.get("DAGSHUB_TOKEN", "") if not dagshub_token: return safe = re.sub(r'[^a-zA-Z0-9-]', '-', keyword.lower())[:40] h = {"Authorization": f"Bearer {dagshub_token}", "Content-Type": "application/json"} data = {"name": safe, "description": f"{keyword} — Data lineage. Ref: {link}", "private": False, "auto_init": True} r = self.http.post("https://dagshub.com/api/v1/user/repos", headers=h, json=data) if r.status_code in (201, 409): user_r = self.http.get("https://dagshub.com/api/v1/user", headers=h) username = user_r.json().get("login", "") if user_r.status_code == 200 else "" if username: readme = f"# {keyword}\n\nData lineage for {keyword}\n\n## Source\n[{link}]({link})\n" content_b64 = base64.b64encode(readme.encode()).decode() self.http.post(f"https://dagshub.com/api/v1/repos/{username}/{safe}/contents/README.md", headers=h, json={"content": content_b64, "message": f"Add {keyword} data"}) except Exception as e: log.error(f"DagsHub error: {e}") def _deploy_cloudflare(self, keyword: str, html_content: str, link: str): try: cf_token = os.environ.get("CF_API_TOKEN", "") cf_account = os.environ.get("CF_ACCOUNT_ID", "") if not cf_token or not cf_account: return h = {"Authorization": f"Bearer {cf_token}", "Content-Type": "application/json"} safe = re.sub(r'[^a-zA-Z0-9-]', '-', keyword.lower())[:40].strip('-') self.http.post(f"https://api.cloudflare.com/client/v4/accounts/{cf_account}/pages/projects", headers=h, json={"name": safe, "production_branch": "main"}) log.info(f"Cloudflare Pages project synced: {safe}") except Exception as e: log.error(f"Cloudflare deploy error: {e}") def _deploy_netlify(self, keyword: str, html_content: str, link: str): try: netlify_token = os.environ.get("NETLIFY_TOKEN", "") if not netlify_token: return h = {"Authorization": f"Bearer {netlify_token}", "Content-Type": "application/json"} safe = re.sub(r'[^a-zA-Z0-9-]', '-', keyword.lower())[:30].strip('-') sites_r = self.http.get("https://api.netlify.com/api/v1/sites", headers=h) existing_id = None if sites_r.status_code == 200: for s in sites_r.json(): if s.get("name", "").startswith(safe[:15]): existing_id = s.get("id"); break if not existing_id: r = self.http.post("https://api.netlify.com/api/v1/sites", headers=h, json={"name": f"{safe}-{random.randint(100,999)}"}) if r.status_code == 201: log.info(f"Netlify site created: {safe}") except Exception as e: log.error(f"Netlify error: {e}") def _zenodo_deposit_actual(self, keyword: str, link: str, lang: str): try: zenodo_token = os.environ.get("ZENODO_TOKEN", "") if not zenodo_token: return h = {"Authorization": f"Bearer {zenodo_token}", "Content-Type": "application/json"} r = self.http.post("https://zenodo.org/api/deposit/depositions", headers=h, json={}) if r.status_code != 201: return dep_id = r.json()["id"] bucket_url = r.json()["links"]["bucket"] meta = {"metadata": {"title": keyword, "upload_type": "dataset", "description": f"Research dataset: {keyword}. Source: {link}", "creators": [{"name": self._get_dynamic_author(keyword, lang)}], "license": "cc-by-4.0"}} self.http.put(f"https://zenodo.org/api/deposit/depositions/{dep_id}", headers=h, json=meta) readme = f"# {keyword}\n\nResearch data. Source: {link}" self.http.put(f"{bucket_url}/README.md", headers={"Authorization": f"Bearer {zenodo_token}"}, data=readme.encode()) pub_r = self.http.post(f"https://zenodo.org/api/deposit/depositions/{dep_id}/actions/publish", headers=h) if pub_r.status_code == 202: log.info(f"Zenodo published: {keyword} DOI={pub_r.json().get('doi', '')}") except Exception as e: log.error(f"Zenodo API error: {e}") def _publish_figshare(self, keyword: str, link: str, lang: str): try: figshare_token = os.environ.get("FIGSHARE_TOKEN", "") if not figshare_token: return h = {"Authorization": f"token {figshare_token}", "Content-Type": "application/json"} data = {"title": keyword, "description": f"Research on {keyword}. Source: {link}", "tags": [keyword, "research", "data"], "categories": [77], "license": 1, "defined_type": "dataset"} r = self.http.post("https://api.figshare.com/v2/account/articles", headers=h, json=data) if r.status_code == 201: article_id = r.json()["entity_id"] self.http.post(f"https://api.figshare.com/v2/account/articles/{article_id}/files", headers=h, json={"link": link}) self.http.post(f"https://api.figshare.com/v2/account/articles/{article_id}/publish", headers=h) except Exception as e: log.error(f"Figshare error: {e}") def _publish_observable(self, keyword: str, link: str, lang: str): try: obs_token = os.environ.get("OBSERVABLE_TOKEN", "") if not obs_token: return h = {"Authorization": f"ApiKey {obs_token}", "Content-Type": "application/json"} notebook = {"title": f"{keyword} Data Analysis", "nodes": [{"type": "md", "value": f"# {keyword}\n\nData analysis for [{keyword}]({link})."}]} r = self.http.post("https://api.observablehq.com/v1/notebooks", headers=h, json=notebook) log.info(f"Observable: {r.status_code} - {keyword}") except Exception as e: log.error(f"Observable error: {e}") def _update_google_kg(self, keyword: str, link: str): try: kg_api = os.environ.get("GOOGLE_KG_API", "") if not kg_api: return r = self.http.get("https://kgsearch.googleapis.com/v1/entities:search", params={"query": keyword, "key": kg_api, "limit": 5, "languages": "fa,en"}) if r.status_code == 200: log.info(f"KG entities for '{keyword}': {len(r.json().get('itemListElement', []))} found") except Exception as e: log.error(f"Google KG error: {e}") def _publish_gitbook_actual(self, keyword: str, link: str, lang: str, topic: str): try: gitbook_token = os.environ.get("GITBOOK_TOKEN", "") if not gitbook_token: return h = {"Authorization": f"Bearer {gitbook_token}", "Content-Type": "application/json"} orgs_r = self.http.get("https://api.gitbook.com/v1/orgs", headers=h) if orgs_r.status_code != 200: return orgs = orgs_r.json().get("items", []) if not orgs: return org_id = orgs[0]["id"] safe = re.sub(r'[^a-zA-Z0-9 ]', ' ', keyword)[:50] r = self.http.post(f"https://api.gitbook.com/v1/orgs/{org_id}/spaces", headers=h, json={"title": safe, "visibility": "public"}) if r.status_code in (200, 201): log.info(f"GitBook space created: {safe}") except Exception as e: log.error(f"GitBook error: {e}") def _publish_crowdin_actual(self, keyword: str, link: str, lang: str): try: crowdin_token = os.environ.get("CROWDIN_TOKEN", "") if not crowdin_token: return h = {"Authorization": f"Bearer {crowdin_token}", "Content-Type": "application/json"} safe = re.sub(r'[^a-zA-Z0-9-]', '-', keyword.lower())[:40] data = {"name": f"{safe}-l10n", "sourceLanguageId": "en", "targetLanguageIds": ["fa", "ar"], "type": 0} r = self.http.post("https://api.crowdin.com/api/v2/projects", headers=h, json=data) except Exception as e: log.error(f"Crowdin error: {e}") def _launchpad_mirror(self, keyword: str, link: str): try: lp_user = os.environ.get("LAUNCHPAD_USER", "") lp_proj = os.environ.get("LAUNCHPAD_PROJECT", "") if not lp_user or not lp_proj: return r = self.http.get(f"https://api.launchpad.net/1.0/{lp_proj}", headers={"Accept": "application/json"}) project_url = r.json().get("web_link", f"https://launchpad.net/{lp_proj}") if r.status_code == 200 else "" if self.gh: safe = re.sub(r'[^a-zA-Z0-9\u0600-\u06FF]', '-', keyword)[:50] blueprint = f"# {keyword}\n- Launchpad: {project_url}\n- Owner: {lp_user}\n- Reference: {link}\n" self.gh.create_or_update_file(f"launchpad/{safe}.md", blueprint, f"Launchpad mirror: {keyword}") log.info(f"Launchpad mirror done: {lp_proj}/{keyword} -> {project_url}") except Exception as e: log.error(f"Launchpad error: {e}") def _publish_hashnode_actual(self, keyword: str, link: str, lang: str): try: hashnode_token = os.environ.get("HASHNODE_TOKEN", "") if not hashnode_token: return content = self.content.generate_markdown_doc(keyword, link, "en", "technology") if not content: return h = {"Authorization": hashnode_token, "Content-Type": "application/json"} query = '{"query": "{ me { publications(first:1) { edges { node { id } } } } }"}' r = self.http.post("https://gql.hashnode.com", headers=h, data=query) pub_id = None if r.status_code == 200: try: edges = (r.json().get("data") or {}).get("me", {}).get("publications", {}).get("edges", []) if edges: pub_id = edges[0]["node"]["id"] except ValueError: pass if not pub_id: return mutation = json.dumps({"query": "mutation P($i:PublishPostInput!){publishPost(input:$i){post{id url}}}", "variables": {"i": {"title": f"{keyword} — Complete Guide", "contentMarkdown": content[:5000], "publicationId": pub_id, "tags": []}}}) pr = self.http.post("https://gql.hashnode.com", headers=h, data=mutation) if pr.status_code == 200: log.info(f"Hashnode published: {keyword}") except Exception as e: log.error(f"Hashnode error: {e}") def _publish_libraries_io(self, keyword: str, link: str): try: lib_key = os.environ.get("LIBRARIESIO_KEY", "") if not lib_key: return safe = re.sub(r'[^a-zA-Z0-9-]', '-', keyword.lower())[:40] r = self.http.get(f"https://libraries.io/api/pypi/{safe}", params={"api_key": lib_key}) log.info(f"Libraries.io: {r.status_code} - {safe}") except Exception as e: log.error(f"Libraries.io error: {e}") def _publish_notion(self, keyword: str, link: str, lang: str, topic: str): try: notion_key = os.environ.get("NOTION_KEY", "") if not notion_key: return h = {"Authorization": f"Bearer {notion_key}", "Content-Type": "application/json", "Notion-Version": "2022-06-28"} search_r = self.http.post("https://api.notion.com/v1/search", headers=h, json={"filter": {"value": "page", "property": "object"}, "page_size": 1}) parent_id = None if search_r.status_code == 200: results = search_r.json().get("results", []) if results: parent_id = results[0]["id"] if not parent_id: return content = self.content.generate_markdown_doc(keyword, link, lang, topic) paragraphs = [] if content: # برای جلوگیری از خطای تودرتویی، لیستها رو ساده و به پاراگراف تبدیل میکنیم lines = content[:2000].split("\n") count = 0 for line in lines: line = line.strip() if line and count < 8: # محدود کردن تعداد پاراگرافها برای امنیت بیشتر clean_line = re.sub(r'^[\s\-\*\d\.\>]+', '', line).strip() if clean_line: paragraphs.append({ "object": "block", "type": "paragraph", "paragraph": {"rich_text": [{"type": "text", "text": {"content": clean_line[:500]}}]} }) count += 1 page_data = { "parent": {"page_id": parent_id}, "properties": {"title": {"title": [{"text": {"content": keyword}}]}}, "children": [ {"object": "block", "type": "heading_1", "heading_1": {"rich_text": [{"type": "text", "text": {"content": keyword}}]}}, {"object": "block", "type": "paragraph", "paragraph": {"rich_text": [{"type": "text", "text": {"content": f"Source: {link}"}, "annotations": {"bold": True}}]}}, ] + paragraphs } r = self.http.post("https://api.notion.com/v1/pages", headers=h, json=page_data) if r.status_code == 200: log.info(f"Notion page created: {keyword} -> {r.json().get('url', '')}") else: log.error(f"Notion error: {r.status_code} {r.text[:200]}") except Exception as e: log.error(f"Notion error: {e}") def _publish_sourceforge(self, keyword: str, link: str, lang: str): try: sf_user = os.environ.get("SOURCEFORGE_USER", "") if not sf_user: return safe = re.sub(r'[^a-zA-Z0-9-]', '-', keyword.lower())[:30].strip('-') if not safe: return sf_url = f"https://sourceforge.net/u/{sf_user}/profile/" if self.gh: content = f"# {keyword} — SourceForge Mirror\n- User: {sf_user}\n- Profile: {sf_url}\n- Ref: {link}\n" self.gh.create_or_update_file(f"sourceforge/{safe}.md", content, f"SourceForge mirror: {keyword}") log.info(f"SourceForge mirror documented: {sf_user}/{safe}") except Exception as e: log.error(f"SourceForge error: {e}") def _get_brand_for_keyword(self, keyword: str) -> str: brand = re.sub(r'[^\w\s\u0600-\u06FF-]', ' ', keyword).strip() brand = re.sub(r'\s+', ' ', brand)[:60] return brand if brand else (self.brand.get("name", "") or "MyBrand") def _get_dynamic_author(self, keyword: str, lang: str) -> str: if keyword in self._author_cache: return self._author_cache[keyword] fa_names = ["علی محمدی", "سارا احمدی", "رضا کریمی", "مریم حسینی", "امیر رضایی", "فاطمه نجفی", "حسن موسوی", "آیت سعادتی", "محمد تهرانی", "نیلوفر اکبری", "کاوه جعفری", "شیرین قاسمی"] en_names = ["Alex Morgan", "Sam Chen", "Jordan Lee", "Taylor Kim", "Morgan Davis", "Casey Park", "Riley Johnson", "Drew Martinez", "Blake Wilson", "Quinn Brown", "Avery Thompson", "Reese Garcia"] idx = int(hashlib.md5(keyword.encode()).hexdigest(), 16) % 12 name = fa_names[idx] if lang == "fa" else en_names[idx] self._author_cache[keyword] = name return name def _static_review_inject(self, keyword: str, link: str, lang: str): if not self.gh: return try: safe = re.sub(r'[^a-zA-Z0-9\u0600-\u06FF]', '-', keyword)[:50] faqs = [(f"Why {keyword}?", f"{keyword} is a key reference."), (f"Source?", f"{link}")] faq_items = "".join(f'{a}