# WeChat Article Fetcher - Double-click to run
# Requires Python 3: https://python.org -> Download
# Then: pip install requests

import requests, json, time, random, urllib3
urllib3.disable_warnings()

S = "http://120.53.228.229:8650"
K = "x9k2m8v7pL4q"
T = "1185780274"
C = """ua_id=NfTuoAawdPsZXypjAAAAABzJdsQl_iiP1xR6tv2Bams=; uuid=3eff74900c654c68a8a1da6be2350fb7; rand_info=CAESIGgyCO/JyjuFqNWQTZATC0yvVC38OoDYbyspWiypnGVY; slave_bizuin=3191422147; data_bizuin=3191422147; bizuin=3191422147; data_ticket=YRY1RxxPZA/j7T/yu25fFOO36hNjq4Yf27ij1p9WUaMVQqt5MpIR7hWJMJdUgJrZ; slave_sid=NjZkRURKTURVQlI4cmZ1aUFPMFNWT1dtT1NPYXZ5MzM0ak5rQ3ROS3JCMFRuc2ppV25IanprejZfZkZLNUlzVlpXZ29ldXN2dUVWbzlQbVFWTWxhZEd5U0Z0UUhFbTlxWl8xYVRWXzFwdE9OYWkzUmpzcDljbkZSeFJYblJFSEl3bTIyNG13eWpSaEMzVFhn; slave_user=gh_a75ba7e8eb63; xid=410f7e7b04f62d1bca5ab57cbaac9be5; mm_lang=zh_CN"""
FEEDS = [
    ("MzU5NjI5NTkxMQ==", "MP_WXS_3596295911", "中职生"),
    ("Mzg4Njg2NDQ3MA==", "MP_WXS_3886864470", "广东中职菌"),
]

all_articles = []
for fid, mid, name in FEEDS:
    print(f"\n>>> {name}")
    count = 0
    s = requests.Session()
    for p in range(3):
        try:
            r = s.get("https://mp.weixin.qq.com/cgi-bin/appmsgpublish",
                params={"sub":"list","sub_action":"list_ex","begin":p*5,"count":5,"fakeid":fid,"token":T,"lang":"zh_CN","f":"json","ajax":1},
                headers={"Cookie":C,"User-Agent":"Mozilla/5.0","Referer":"https://mp.weixin.qq.com/"},
                timeout=30, verify=False)
            d = r.json()
            ret = d.get("base_resp",{}).get("ret",-1)
            if ret == 200013: print("  freq control"); break
            if ret != 0: print(f"  err:{ret}"); break
            if "publish_page" not in d: break
            pp = json.loads(d["publish_page"])
            for it in pp.get("publish_list",[]):
                pi = json.loads(it.get("publish_info","{}"))
                for a in pi.get("appmsgex",[]):
                    all_articles.append({"id":str(a["aid"]),"mp_id":mid,"title":a.get("title",""),"cover":a.get("cover",""),"link":a.get("link",""),"digest":a.get("digest",""),"update_time":a.get("update_time",0),"create_time":a.get("create_time",0)})
                    count += 1
                    print(f"  {a.get('title','?')[:50]}")
            time.sleep(random.randint(3,8))
        except Exception as e: print(f"  err:{e}"); break
    print(f"  => {count}")
    time.sleep(random.randint(5,10))

print(f"\nTotal: {len(all_articles)}")
if all_articles:
    try:
        r = requests.post(f"{S}/api/articles/import", json={"secret":K,"articles":all_articles}, timeout=30)
        print(f"Upload: {r.json().get('saved',0)}/{r.json().get('total',0)} saved")
    except Exception as e: print(f"Upload fail: {e}")
else:
    print("No new articles")

print("\nDone. Press Enter...")
input()
