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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
| import os import json import time import requests import re import subprocess import random from urllib import parse from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5 from Crypto.PublicKey import RSA import logging import schedule from dotenv import load_dotenv from datetime import datetime
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) load_dotenv(dotenv_path="sys.env", override=True)
ENV_189_CLIENT_ID = os.getenv("ENV_189_CLIENT_ID", "") ENV_189_CLIENT_SECRET = os.getenv("ENV_189_CLIENT_SECRET", "") TG_BOT_TOKEN = os.getenv("ENV_TG_BOT_TOKEN", "") TG_ADMIN_USER_ID = os.getenv("ENV_TG_ADMIN_USER_ID", "")
SUBS_FILE = "db/subscriptions.json" HISTORY_FILE = "db/history.json"
def load_json(filepath): if os.path.exists(filepath): with open(filepath, 'r', encoding='utf-8') as f: return json.load(f) return {}
def save_json(filepath, data): with open(filepath, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2)
def clean_filename(name): illegal_chars = '"\\/:*?|<>' for char in illegal_chars: name = name.replace(char, '') return name[:255]
def rsaEncrpt(password, public_key): rsakey = RSA.importKey(public_key) cipher = Cipher_pksc1_v1_5.new(rsakey) return cipher.encrypt(password.encode()).hex()
class TelegramNotifier: def __init__(self, bot_token, user_id): self.bot_token = bot_token self.user_id = user_id self.base_url = f"https://api.telegram.org/bot{self.bot_token}/" if self.bot_token else None
def send_message(self, message): if not self.bot_token: return False try: requests.get(f"{self.base_url}sendMessage", params={"chat_id": self.user_id, "text": message}, timeout=10) return True except: return False
class Cloud189ShareInfo: def __init__(self, fileId, shareId, shareMode, cloud189Client, accessCode=""): self.shareDirFileId = fileId self.shareId = shareId self.session = cloud189Client.session self.client = cloud189Client self.shareMode = shareMode self.accessCode = accessCode
def getAllShareFiles(self, folder_id=None): if folder_id is None: folder_id = self.shareDirFileId fileList, folders = [], [] pageNumber = 1 while True: result = self.session.get("https://cloud.189.cn/api/open/share/listShareDir.action", params={ "pageNum": pageNumber, "pageSize": "10000", "fileId": folder_id, "shareDirFileId": self.shareDirFileId, "isFolder": "true", "shareId": self.shareId, "shareMode": self.shareMode, "orderBy": "lastOpTime", "descending": "true", "accessCode": self.accessCode, }).json() if result['res_code'] != 0: break fileListAO = result.get("fileListAO", {}) fileList += fileListAO.get("fileList", []) folders += fileListAO.get("folderList", []) if fileListAO.get("fileListSize", 0) == 0 and len(fileListAO.get("folderList", [])) == 0: break pageNumber += 1 return {"files": fileList, "folders": folders}
def saveShareFiles(self, tasksInfos, targetFolderId): try: response = self.session.post("https://cloud.189.cn/api/open/batch/createBatchTask.action", data={ "type": "SHARE_SAVE", "taskInfos": str(tasksInfos), "targetFolderId": targetFolderId, "shareId": self.shareId, }).json() if response.get("res_code") != 0: return response.get('res_message', 'UNKNOWN_ERROR') taskId = response["taskId"] while True: res = self.session.post("https://cloud.189.cn/api/open/batch/checkBatchTask.action", data={ "taskId": taskId, "type": "SHARE_SAVE" }).json() if res["taskStatus"] != 3 or res.get("errorCode"): break time.sleep(1) return res.get("errorCode") except Exception as e: return str(e)
class Cloud189: def __init__(self): self.session = requests.session() self.session.headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept": "application/json;charset=UTF-8", }
def getEncrypt(self): return self.session.post("https://open.e.189.cn/api/logbox/config/encryptConf.do", data={'appId': 'cloud'}, timeout=15).json()['data']['pubKey']
def getRedirectURL(self): rsp = self.session.get('https://cloud.189.cn/api/portal/loginUrl.action?redirectURL=https://cloud.189.cn/web/redirect.html?returnURL=/main.action', timeout=15) return parse.parse_qs(parse.urlparse(rsp.url).query)
def login(self, username, password): encryptKey = self.getEncrypt() query = self.getRedirectURL() resData = self.session.post('https://open.e.189.cn/api/logbox/oauth2/appConf.do', data={"version": '2.0', "appKey": 'cloud'}, headers={"Referer": 'https://open.e.189.cn/', "lt": query["lt"][0], "REQID": query["reqId"][0]}, timeout=15).json() keyData = f"-----BEGIN PUBLIC KEY-----\n{encryptKey}\n-----END PUBLIC KEY-----" data = { "appKey": 'cloud', "version": '2.0', "accountType": '01', "mailSuffix": '@189.cn', "returnUrl": resData['data']['returnUrl'], "paramId": resData['data']['paramId'], "clientType": '1', "isOauth2": "false", "userName": f"{{NRP}}{rsaEncrpt(username, keyData)}", "password": f"{{NRP}}{rsaEncrpt(password, keyData)}", } result = self.session.post('https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do', data=data, headers={'Referer': 'https://open.e.189.cn/', 'lt': query["lt"][0], 'REQID': query["reqId"][0]}, timeout=15).json() if result['result'] == 0: self.session.get(result['toUrl'], headers={"Host": 'cloud.189.cn'}, timeout=15) else: raise Exception(result['msg'])
def getShareInfo(self, link): url = parse.urlparse(link) try: code = parse.parse_qs(url.query)["code"][0] except: code = url.path.split('/')[-1] pwd = parse.parse_qs(url.query).get('pwd', [''])[0] result = self.session.get("https://cloud.189.cn/api/open/share/getShareInfoByCodeV2.action", params={"shareCode": code}).json() if result.get('res_code') != 0: raise Exception(f"获取分享失败,可能掉线: {result}") file_id = result.get("fileId") share_mode = result.get("shareMode", 1) share_id = result.get("shareId") if pwd: verify_res = self.session.get("https://cloud.189.cn/api/open/share/checkAccessCode.action", params={"shareCode": code, "accessCode": pwd}).json() if verify_res.get('res_code') != 0: raise Exception(f"提取码错误或失效: {verify_res}") share_id = verify_res.get("shareId") if not share_id: raise Exception("未能获取到 shareId,疑似掉线拦截。") return Cloud189ShareInfo(file_id, share_id, share_mode, self, pwd)
def createFolder(self, name, parentFolderId=-11): result = self.session.post("https://cloud.189.cn/api/open/file/createFolder.action", data={"parentFolderId": parentFolderId, "folderName": name}).json() return result["id"]
def getObjectFolderNodes(self, folderId=-11): res = self.session.post("https://cloud.189.cn/api/portal/getObjectFolderNodes.action", data={"id": folderId, "orderBy": 1, "order": "ASC"}).json() if isinstance(res, dict): raise Exception(f"账号掉线或被限制 (获取目录失败): {res}") return res
def mkdirAll(self, path, parentFolderId=-11): path = path.strip("/") if not path: return parentFolderId for name in path.split("/"): found = False for node in self.getObjectFolderNodes(parentFolderId): if node["name"] == name: parentFolderId = node["id"] found = True break if not found: parentFolderId = self.createFolder(name, parentFolderId) return parentFolderId
def get_all_share_files_recursive(info, folder_id=None, current_path=""): all_files = [] result = info.getAllShareFiles(folder_id) for f in result.get("files", []): f["full_path"] = current_path + "/" + f["name"] all_files.append(f) for folder in result.get("folders", []): new_path = current_path + "/" + folder["name"] all_files.extend(get_all_share_files_recursive(info, folder["id"], new_path)) return all_files
def auto_relogin(client): logger.info("🔄 触发自动保活机制:正在重新登录...") try: client.login(ENV_189_CLIENT_ID, ENV_189_CLIENT_SECRET) logger.info("✅ 自动重新登录成功!通行证已刷新。") return True except Exception as e: logger.error(f"❌ 自动重新登录失败: {e}") return False
# ================= 终极仿生:深度休眠与窗口过滤 ================= def check_subscriptions(client, force_target_id=None): subs = load_json(SUBS_FILE) history = load_json(HISTORY_FILE) notifier = TelegramNotifier(TG_BOT_TOKEN, TG_ADMIN_USER_ID)
if not subs: return current_time = time.time() logger.info(f"🔍 巡逻开始,总任务数: {len(subs)}") for target_id, sub_info in subs.items(): try: share_url = sub_info if isinstance(sub_info, str) else sub_info.get("url", "") keyword = "" if isinstance(sub_info, str) else sub_info.get("keyword", "") path = "" if isinstance(sub_info, str) else sub_info.get("path", "") freq = "" if isinstance(sub_info, str) else sub_info.get("freq", "")
if force_target_id and str(target_id) == str(force_target_id): pass elif path: now = datetime.now() curr_h, curr_m, curr_w = now.hour, now.minute, now.weekday() # 读取深度休眠锁 next_check_time = 0 if isinstance(sub_info, str) else sub_info.get("next_check_time", 0)
# 1. 死锁拦截:没到下次指定时间,彻底忽略,省流防封 if current_time < next_check_time: continue
# 2. 每日窗口拦截:电视剧不到晚上 18点 不看 if freq == "日更" or "日更" in path or "电视剧" in path or "剧" in path: if curr_h < 18: continue
# 3. 动漫窗口拦截:只看 10:30-12:00 和 18:30-24:00 if freq == "周更" or "周更" in path or "动漫" in path: update_weekday = 5 if isinstance(sub_info, str) else sub_info.get("update_weekday", 5) if curr_w < update_weekday: continue # 还没到这周更新日,跳过 is_am = (curr_h == 10 and curr_m >= 30) or (curr_h == 11) is_pm = (curr_h >= 18 and curr_m >= 30) or (curr_h >= 19) if not (is_am or is_pm): continue info = client.getShareInfo(share_url) all_files = get_all_share_files_recursive(info) if keyword: all_files = [f for f in all_files if keyword.lower() in f["full_path"].lower()]
new_files = [f for f in all_files if str(f["id"]) not in history]
if new_files: logger.info(f"🎉 发现 {len(new_files)} 个新文件,开始转存...") taskInfos = [{"fileId": f["id"], "fileName": clean_filename(f["name"]), "isFolder": 0} for f in new_files] batch_size = 50 for i in range(0, len(taskInfos), batch_size): batch_tasks = taskInfos[i:i+batch_size] code = info.saveShareFiles(batch_tasks, target_id) if not code: file_names = [] for task in batch_tasks: history[str(task["fileId"])] = {"name": task["fileName"], "sub_id": str(target_id)} file_names.append(task["fileName"]) save_json(HISTORY_FILE, history) notifier.send_message(f"✅【追剧更新】\n🔗 来源: {share_url}\n📂 新增文件:\n" + "\n".join(file_names)) try: openlist_target_path = f"/177{path}" if path.startswith("/") else f"/177/{path}" subprocess.Popen(["/data/data/com.termux/files/usr/bin/bash", "/data/data/com.termux/files/home/refresh.sh", openlist_target_path]) except Exception as script_e: logger.error(f"❌ 联动失败: {script_e}")
# ================= 🌟 更新后计算死锁时间 🌟 ================= subs_for_update = load_json(SUBS_FILE) if str(target_id) in subs_for_update: if isinstance(subs_for_update[str(target_id)], str): subs_for_update[str(target_id)] = {"url": share_url, "keyword": keyword, "path": path} subs_for_update[str(target_id)]["last_update"] = time.time() if freq == "周更" or "周更" in path or "动漫" in path: # 动漫:直接锁死到下个更新日凌晨 target_weekday = subs_for_update[str(target_id)].get("update_weekday", 5) days_ahead = target_weekday - curr_w if days_ahead <= 0: days_ahead += 7 today_midnight = datetime(now.year, now.month, now.day).timestamp() subs_for_update[str(target_id)]["next_check_time"] = today_midnight + days_ahead * 86400 logger.info(f"💤 动漫 {path} 更新完毕,深度休眠 {days_ahead} 天。") elif freq == "日更" or "日更" in path or "电视剧" in path or "剧" in path: # 电视剧:为了防止漏掉当晚后续分集,设定 30 分钟短锁。 # 因为一过 24:00,外层的 `curr_h < 18` 就会把它挡在门外,直到第二天傍晚才重新放行 subs_for_update[str(target_id)]["next_check_time"] = time.time() + 1800 logger.info(f"🎬 电视剧 {path} 已更新,保持警惕防漏更,短休 30 分钟。") else: subs_for_update[str(target_id)]["next_check_time"] = time.time() + 24 * 3600 save_json(SUBS_FILE, subs_for_update) # ========================================================== else: logger.error(f"转存失败,错误码: {code}") except Exception as e: error_msg = str(e) if "掉线" in error_msg or "失败" in error_msg: logger.error("巡逻期间检测到掉线,尝试紧急重连...") auto_relogin(client)
def main_control_loop(client): offset = 0 notifier = TelegramNotifier(TG_BOT_TOKEN, TG_ADMIN_USER_ID)
# 🌟 动态随机步长轮询 🌟 def scheduled_task(): check_subscriptions(client) wait_min = random.randint(25, 45) logger.info(f"⏰ 本次巡逻结束,随机预约 {wait_min} 分钟后再次发车...") schedule.clear('patrol') schedule.every(wait_min).minutes.do(scheduled_task).tag('patrol')
scheduled_task() # 首次发车 schedule.every(6).hours.do(auto_relogin, client)
while True: schedule.run_pending() try: url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/getUpdates?offset={offset}&timeout=10" res = requests.get(url, timeout=15).json() if res.get('ok'): for item in res['result']: offset = item['update_id'] + 1 msg = item.get('message', {}) text = msg.get('text', '') chat_id = msg.get('chat', {}).get('id')
if str(chat_id) == str(TG_ADMIN_USER_ID): text = text.strip() match_bind = re.match(r'^(订阅|绑定)(\d)?\s+', text) match_cancel = re.match(r'^取消订阅(\d)?\s+', text)
if match_bind: action = match_bind.group(1) season_num = match_bind.group(2) freq_tag = "" if "#周更" in text: freq_tag, text = "周更", text.replace("#周更", "").strip() elif "#双更" in text: freq_tag, text = "双更", text.replace("#双更", "").strip() elif "#高频" in text: freq_tag, text = "高频", text.replace("#高频", "").strip() elif "#日更" in text: freq_tag, text = "日更", text.replace("#日更", "").strip() weekday_map = {"周一": 0, "周二": 1, "周三": 2, "周四": 3, "周五": 4, "周六": 5, "周日": 6} t_weekday = 5 for d_name, d_code in weekday_map.items(): if f"#{d_name}" in text: t_weekday = d_code text = text.replace(f"#{d_name}", "").strip() break is_bind = (action == "绑定") parts = text.split() share_url = "" keyword = "" target_path = ""
# 🌟 无死角链接扫描 url_index = -1 for i, p in enumerate(parts): if p.startswith("http"): share_url = p url_index = i break
if url_index != -1: target_path = " ".join(parts[1:url_index]) if url_index < len(parts) - 1: keyword = " ".join(parts[url_index+1:]) else: target_path = " ".join(parts[1:])
if season_num: s_num = int(season_num) if "season" not in target_path.lower(): target_path = f"{target_path.rstrip('/')}/Season {s_num}" if not keyword: keyword = f"S{s_num:02d}"
# 🌟 老数据免发链接打标签功能 if not share_url: subs = load_json(SUBS_FILE) for tid, info in subs.items(): if isinstance(info, dict) and info.get("path") == target_path: share_url = info.get("url", "") break # 🌟 防呆报错 if not share_url: notifier.send_message(f"❌ 解析失败:没找到网盘链接,且数据库中未找到【{target_path}】的历史记录。\n请检查拼写或带上链接重试。") continue
mode_name = "绑定(静默)" if is_bind else "订阅(下载)" tag_msg = f" ⏱️ 频率: {freq_tag}" if freq_tag else "" kw_msg = f" 🎯 过滤: {keyword}" if keyword else "" day_cn = list(weekday_map.keys())[t_weekday] day_msg = f" 📅 盯梢: {day_cn}" if freq_tag == "周更" else "" notifier.send_message(f"⏳ 正在处理{mode_name}目录:\n📁 {target_path}{tag_msg}{kw_msg}{day_msg} ...") try: target_id = client.mkdirAll(target_path) subs = load_json(SUBS_FILE) subs[str(target_id)] = { "url": share_url, "keyword": keyword, "path": target_path, "last_update": 0, "freq": freq_tag, "update_weekday": t_weekday, "next_check_time": 0 # 初始化死锁时间 } save_json(SUBS_FILE, subs) if is_bind: info = client.getShareInfo(share_url) all_files = get_all_share_files_recursive(info) if keyword: all_files = [f for f in all_files if keyword.lower() in f["full_path"].lower()] history = load_json(HISTORY_FILE) for f in all_files: history[str(f["id"])] = {"name": f["name"], "sub_id": str(target_id)} save_json(HISTORY_FILE, history) notifier.send_message(f"✅ 成功绑定!\n❇️ 已将 {len(all_files)} 个旧文件标记为已存。") else: notifier.send_message(f"✅ 成功添加订阅!正在为您优先拉取资源...") check_subscriptions(client, force_target_id=target_id) except Exception as e: if "掉线" in str(e) or "失败" in str(e) or "限制" in str(e): notifier.send_message("⚠️ 网盘疑似掉线,正在自动重连,请稍后重试!") auto_relogin(client) else: notifier.send_message(f"❌ 处理失败: {str(e)}") else: notifier.send_message("❌ 格式错误...") elif match_cancel: season_num = match_cancel.group(1) parts = text.split() if len(parts) >= 2: path_parts = [p for p in parts[1:] if not p.startswith("http")] target_path = " ".join(path_parts) if season_num: s_num = int(season_num) if "season" not in target_path.lower(): target_path = f"{target_path.rstrip('/')}/Season {s_num}"
try: target_id = client.mkdirAll(target_path) subs = load_json(SUBS_FILE) if str(target_id) in subs: del subs[str(target_id)] save_json(SUBS_FILE, subs) path_levels = target_path.strip('/').split('/') raw_name = path_levels[-2] if "season" in path_levels[-1].lower() and len(path_levels) > 1 else path_levels[-1] clean_keyword = re.sub(r'\(.*?\)', '', raw_name).strip() history = load_json(HISTORY_FILE) old_len = len(history) new_history = {} for file_id, file_info in history.items(): if isinstance(file_info, dict): if file_info.get("sub_id") == str(target_id): continue elif isinstance(file_info, str): if clean_keyword and clean_keyword in file_info: continue new_history[file_id] = file_info save_json(HISTORY_FILE, new_history) del_count = old_len - len(new_history)
notifier.send_message(f"✅ 已成功取消订阅:\n📁 {target_path}\n🧹 彻底拔除了 {del_count} 条该剧的底层记忆。") else: notifier.send_message("❎ 未找到该目录。") except Exception as e: pass except: pass time.sleep(2)
if __name__ == '__main__': os.makedirs("db", exist_ok=True) # 🌟 第一步:先开喇叭再干活 notifier = TelegramNotifier(TG_BOT_TOKEN, TG_ADMIN_USER_ID) notifier.send_message("🤖 私人追剧管家已启动,正在尝试登录...") client = Cloud189() try: logger.info("189正在登录 ...") client.login(ENV_189_CLIENT_ID, ENV_189_CLIENT_SECRET) notifier.send_message("✅ 网盘登录成功!全天候仿生监控已就位。") except Exception as e: logger.error(f"登录失败: {e}") notifier.send_message(f"❌ 首次登录失败: {e}\n(脚本将直接退出,请处理后重启)") exit(-1) main_control_loop(client)
|