feat: 用 Rust 重写打卡记录,命令行输出最近一周
This commit is contained in:
@@ -1 +0,0 @@
|
||||
"""PunchLog: ZTE iCenter punch-record client (pure Python)."""
|
||||
@@ -1,3 +0,0 @@
|
||||
from .cli import main
|
||||
|
||||
raise SystemExit(main())
|
||||
@@ -1,120 +0,0 @@
|
||||
"""Analyze punch records: daily summary, missing/insufficient detection, today reminder.
|
||||
|
||||
Rule (user-defined): for each day, take the earliest and the latest punch of that day.
|
||||
- If the day has fewer than 2 punches -> 缺卡 (insufficient count)
|
||||
- Else if (latest - earliest) < 8 hours -> 打卡时间不足 (insufficient duration)
|
||||
- Else -> 正常 (OK)
|
||||
|
||||
补卡 (supplementary punch) handling:
|
||||
- A supplement record has ``supplementType`` set and ``signType == 4``. Its ``signDate``
|
||||
is when the supplement was submitted, NOT the real punch time. The real punch time is
|
||||
``supplementDate``, and it only counts when ``approveStatus == 1`` (approved).
|
||||
- So each record is attributed to its *effective* day/time: normal punches use signDate;
|
||||
approved supplements use supplementDate; unapproved supplements are ignored.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, date
|
||||
|
||||
MIN_WORK_HOURS = 8.0
|
||||
_DT_FMT = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
STATUS_OK = "正常"
|
||||
STATUS_FEW = "缺卡(不足2次)"
|
||||
STATUS_SHORT = "打卡时间不足(<8h)"
|
||||
|
||||
APPROVE_PASSED = 1
|
||||
|
||||
|
||||
def _parse_dt(s: str | None) -> datetime | None:
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s[:19], _DT_FMT)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def effective_punch(r: dict) -> datetime | None:
|
||||
"""Effective punch datetime for a record, or None if it should not count.
|
||||
|
||||
- 补卡 (supplementType not null): use supplementDate, only if approved; else ignore.
|
||||
- 普通打卡: use signDate.
|
||||
"""
|
||||
if r.get("supplementType") is not None or r.get("signType") == 4:
|
||||
if r.get("approveStatus") != APPROVE_PASSED:
|
||||
return None
|
||||
return _parse_dt(r.get("supplementDate"))
|
||||
return _parse_dt(r.get("signDate"))
|
||||
|
||||
|
||||
def is_supplement(r: dict) -> bool:
|
||||
return r.get("supplementType") is not None or r.get("signType") == 4
|
||||
|
||||
|
||||
@dataclass
|
||||
class DaySummary:
|
||||
day: date
|
||||
count: int
|
||||
first: datetime | None
|
||||
last: datetime | None
|
||||
hours: float
|
||||
status: str
|
||||
has_supplement: bool = False
|
||||
records: list = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def is_problem(self) -> bool:
|
||||
return self.status != STATUS_OK
|
||||
|
||||
|
||||
def daily_summaries(rows: list[dict], start: date | None = None,
|
||||
end: date | None = None) -> list[DaySummary]:
|
||||
"""Group records by their effective day and classify each day.
|
||||
|
||||
Supplements are attributed to the day they supplement (supplementDate), so callers
|
||||
should fetch a wide-enough window (supplements may be submitted days later). If
|
||||
``start``/``end`` are given, only days within [start, end] are returned.
|
||||
"""
|
||||
by_day: dict[date, list[dict]] = {}
|
||||
for r in rows:
|
||||
dt = effective_punch(r)
|
||||
if dt is None:
|
||||
continue
|
||||
rec = {**r, "_dt": dt}
|
||||
by_day.setdefault(dt.date(), []).append(rec)
|
||||
|
||||
out: list[DaySummary] = []
|
||||
for day in sorted(by_day):
|
||||
if start and day < start:
|
||||
continue
|
||||
if end and day > end:
|
||||
continue
|
||||
recs = sorted(by_day[day], key=lambda x: x["_dt"])
|
||||
first = recs[0]["_dt"]
|
||||
last = recs[-1]["_dt"]
|
||||
hours = (last - first).total_seconds() / 3600.0
|
||||
if len(recs) < 2:
|
||||
status = STATUS_FEW
|
||||
elif hours < MIN_WORK_HOURS:
|
||||
status = STATUS_SHORT
|
||||
else:
|
||||
status = STATUS_OK
|
||||
out.append(DaySummary(day, len(recs), first, last, hours, status,
|
||||
any(is_supplement(r) for r in recs), recs))
|
||||
return out
|
||||
|
||||
|
||||
def today_status(rows: list[dict], today: date | None = None) -> DaySummary | None:
|
||||
today = today or datetime.now().date()
|
||||
for s in daily_summaries(rows):
|
||||
if s.day == today:
|
||||
return s
|
||||
return None
|
||||
|
||||
|
||||
def problems(rows: list[dict], start: date | None = None,
|
||||
end: date | None = None) -> list[DaySummary]:
|
||||
return [s for s in daily_summaries(rows, start, end) if s.is_problem]
|
||||
@@ -1,187 +0,0 @@
|
||||
"""ZTE iCenter login (SSO login/pwd) reproduced in pure Python via the MSA envelope.
|
||||
|
||||
Flow (from cn.com.zte.app.ztesso.manager.SSOManager.getResponse + SSOTokenRequest):
|
||||
1. GET {EMP_BASE}/login/transmissionkey -> bo.publicKey (server RSA transmission key)
|
||||
2. Build SSOTokenRequest JSON (loginName, loginPwd=plaintext password, device fields,
|
||||
extendMap={"timestamp": <ms>}), MSA-encrypt it and POST to {EMP_BASE}/login/pwd.
|
||||
3. Decrypt the MSA response -> bo contains the auth token (used as X-Auth-Value).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import requests
|
||||
|
||||
from . import msa
|
||||
from .config import load_env
|
||||
|
||||
EMP_BASE = "https://mdm.zte.com.cn/emp/zte-itp-emp-sso"
|
||||
CONTENT_TYPE = "application/json; charset=utf-8"
|
||||
|
||||
# Device identity captured from the real client (stable per device).
|
||||
DEFAULT_DEVICE = {
|
||||
"appId": "A00154",
|
||||
"deviceId": "V02_CF64B4B1544AC5D3DB79656332385175",
|
||||
"deviceNum": "V02_CF64B4B1544AC5D3DB79656332385175;V02_CF64B4B1544AC5D3DB79656332385175;AID_034b7912-c21d-3bb3-9bfe-ea789d753967",
|
||||
"deviceBrand": "Redmi",
|
||||
"deviceMode": "25053RT47C",
|
||||
"deviceName": "Redmi-25053RT47C",
|
||||
# getMobileAndroidID() returns "AID_" + local uuid, not the raw uuid.
|
||||
"androidId": "AID_034b7912-c21d-3bb3-9bfe-ea789d753967",
|
||||
# App submits 0.0.0.0 when Wi-Fi is off. The server does not check the source address.
|
||||
"clientIp": "0.0.0.0",
|
||||
"versionName": "12.8.1",
|
||||
"versionCode": 120805,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Session:
|
||||
emp_no: str
|
||||
token: str
|
||||
tenant_id: str = "10001"
|
||||
lang_id: str = "zh"
|
||||
user_info: dict = field(default_factory=dict)
|
||||
cookies: requests.cookies.RequestsCookieJar = field(default_factory=requests.cookies.RequestsCookieJar)
|
||||
client_keys: msa.RSAKeyPair | None = None
|
||||
|
||||
|
||||
def _get_transmission_key(sess: requests.Session, emp_no: str, tenant_id: str, lang_id: str) -> str:
|
||||
r = sess.get(
|
||||
f"{EMP_BASE}/login/transmissionkey",
|
||||
headers={
|
||||
"X-Emp-No": emp_no,
|
||||
"X-Lang-Id": lang_id,
|
||||
"X-Tenant-Id": tenant_id,
|
||||
"Content-Type": CONTENT_TYPE,
|
||||
"User-Agent": "okhttp/4.12.0",
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
pub = (data.get("bo") or {}).get("publicKey")
|
||||
if not pub:
|
||||
raise RuntimeError(f"transmissionkey failed: {data}")
|
||||
return pub
|
||||
|
||||
|
||||
def _device() -> dict:
|
||||
"""Device identity from the environment or .env, falling back to this phone."""
|
||||
file_env = load_env()
|
||||
merged = dict(file_env)
|
||||
for key, value in os.environ.items():
|
||||
if key.startswith("ICENTER_") and value.strip():
|
||||
merged[key] = value.strip()
|
||||
|
||||
def pick(key: str, default: object) -> str:
|
||||
return (merged.get(key) or "").strip() or str(default)
|
||||
|
||||
version_raw = pick("ICENTER_VERSION_CODE", DEFAULT_DEVICE["versionCode"])
|
||||
try:
|
||||
version_code = int(version_raw)
|
||||
except ValueError:
|
||||
version_code = int(DEFAULT_DEVICE["versionCode"])
|
||||
return {
|
||||
"appId": pick("ICENTER_APP_ID", DEFAULT_DEVICE["appId"]),
|
||||
"deviceId": pick("ICENTER_DEVICE_ID", DEFAULT_DEVICE["deviceId"]),
|
||||
"deviceNum": pick("ICENTER_DEVICE_NUM", DEFAULT_DEVICE["deviceNum"]),
|
||||
"deviceBrand": pick("ICENTER_DEVICE_BRAND", DEFAULT_DEVICE["deviceBrand"]),
|
||||
"deviceMode": pick("ICENTER_DEVICE_MODE", DEFAULT_DEVICE["deviceMode"]),
|
||||
"deviceName": pick("ICENTER_DEVICE_NAME", DEFAULT_DEVICE["deviceName"]),
|
||||
"androidId": pick("ICENTER_ANDROID_ID", DEFAULT_DEVICE["androidId"]),
|
||||
"clientIp": pick("ICENTER_CLIENT_IP", DEFAULT_DEVICE["clientIp"]),
|
||||
"versionName": pick("ICENTER_VERSION_NAME", DEFAULT_DEVICE["versionName"]),
|
||||
"versionCode": version_code,
|
||||
}
|
||||
|
||||
|
||||
def _build_login_payload(emp_no: str, password: str, tenant_id: str) -> dict:
|
||||
"""Mirror SSOManager.getResponse + SSOTokenRequest defaults exactly.
|
||||
|
||||
Gson omits null fields, so secretKey/accountId/token are not included.
|
||||
"""
|
||||
d = _device()
|
||||
return {
|
||||
"loginName": emp_no,
|
||||
"loginPwd": password,
|
||||
"appId": d["appId"], # default "A00154"
|
||||
"deviceBrand": d["deviceBrand"], # Build.BRAND
|
||||
"deviceMode": d["deviceMode"], # Build.MODEL
|
||||
"deviceId": d["deviceId"],
|
||||
"deviceNum": d["deviceNum"],
|
||||
"androidId": d["androidId"], # getMobileAndroidID (AID uuid)
|
||||
"deviceType": 1,
|
||||
"deviceName": d["deviceName"], # Build.BRAND + "-" + Build.MODEL
|
||||
# Kotlin default for the omitted os argument is 2 (Android), not 0.
|
||||
"os": 2,
|
||||
"clientIp": d["clientIp"],
|
||||
"packageName": "com.zte.softda",
|
||||
"versionName": d["versionName"],
|
||||
# Omitted versionCode calls SSOConstant.getVersionCode(), i.e. the installed versionCode.
|
||||
"versionCode": d["versionCode"],
|
||||
"sequence": "relogin", # SSOConstant.TYPE_RELOGIN
|
||||
"extendMap": {"timestamp": str(int(time.time() * 1000))},
|
||||
# Omitted strings default to "" and Gson still serializes them.
|
||||
"secretKey": "",
|
||||
"accountId": "",
|
||||
"returnUserInfo": 0,
|
||||
"token": "",
|
||||
}
|
||||
|
||||
|
||||
def login(emp_no: str, password: str, tenant_id: str = "10001", lang_id: str = "zh") -> Session:
|
||||
http = requests.Session()
|
||||
server_pub = _get_transmission_key(http, emp_no, tenant_id, lang_id)
|
||||
|
||||
keys = msa.RSAKeyPair.generate()
|
||||
local_key = msa.gen_local_key_string()
|
||||
|
||||
payload = _build_login_payload(emp_no, password, tenant_id)
|
||||
body = msa.encrypt_aes_gcm(json.dumps(payload, separators=(",", ":")), local_key)
|
||||
data_key = msa.encrypt_rsa(server_pub, local_key)
|
||||
|
||||
r = http.post(
|
||||
f"{EMP_BASE}/login/pwd",
|
||||
data=body.encode("utf-8"),
|
||||
headers={
|
||||
"X-Emp-No": emp_no,
|
||||
"X-MSA-Encrypt-PublicKey": keys.public_b64,
|
||||
"X-MSA-Encrypt-DataKey": data_key,
|
||||
"X-Lang-Id": lang_id,
|
||||
"Client": "android",
|
||||
"Accept": "application/json",
|
||||
"X-Tenant-Id": tenant_id,
|
||||
"Content-Type": CONTENT_TYPE,
|
||||
"User-Agent": "okhttp/4.12.0",
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
r.raise_for_status()
|
||||
|
||||
resp_data_key_hdr = r.headers.get("X-MSA-Encrypt-DataKey") or r.headers.get("x-msa-encrypt-datakey")
|
||||
if not resp_data_key_hdr:
|
||||
# Some error responses are plaintext JSON.
|
||||
raise RuntimeError(f"login/pwd no MSA response header; body={r.text[:300]}")
|
||||
server_local_key = msa.decrypt_rsa(keys._priv, resp_data_key_hdr)
|
||||
plain = msa.decrypt_aes_gcm(r.text, server_local_key)
|
||||
data = json.loads(plain)
|
||||
|
||||
bo = data.get("bo") or {}
|
||||
token = bo.get("token") or bo.get("authValue") or bo.get("eToken") or bo.get("accessToken")
|
||||
if not token:
|
||||
raise RuntimeError(f"login ok but no token in bo keys={list(bo.keys())}; data={json.dumps(data, ensure_ascii=False)[:500]}")
|
||||
|
||||
return Session(
|
||||
emp_no=emp_no,
|
||||
token=token,
|
||||
tenant_id=tenant_id,
|
||||
lang_id=lang_id,
|
||||
user_info=bo,
|
||||
cookies=http.cookies,
|
||||
client_keys=keys,
|
||||
)
|
||||
@@ -1,137 +0,0 @@
|
||||
"""PunchLog command-line tool.
|
||||
|
||||
Usage examples:
|
||||
python -m punchlog # 当月记录 + 今日提醒 + 缺卡统计
|
||||
python -m punchlog --month 2026-10 # 指定月份
|
||||
python -m punchlog --start 2026-10-01 --end 2026-10-31
|
||||
python -m punchlog --csv out.csv # 同时导出明细 CSV
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from .analyze import daily_summaries, today_status, problems, STATUS_OK
|
||||
|
||||
# 补卡最多只能在被补当天后 5 天内提交,超过则无法补卡
|
||||
SUPPLEMENT_WINDOW_DAYS = 5
|
||||
from .config import config_from_env
|
||||
from .iepms import IepmsClient
|
||||
|
||||
|
||||
def _month_range(month: str) -> tuple[str, str]:
|
||||
y, m = (int(x) for x in month.split("-"))
|
||||
start = date(y, m, 1)
|
||||
nxt = date(y + (m == 12), (m % 12) + 1, 1)
|
||||
end = nxt - timedelta(days=1)
|
||||
return start.isoformat(), end.isoformat()
|
||||
|
||||
|
||||
def _default_month() -> str:
|
||||
return datetime.now().strftime("%Y-%m")
|
||||
|
||||
|
||||
def _fmt_t(dt) -> str:
|
||||
return dt.strftime("%H:%M:%S") if dt else "-"
|
||||
|
||||
|
||||
def _memo_oneline(rec: dict) -> str:
|
||||
return " / ".join(x.strip() for x in (rec.get("memo") or "").replace("\r", "\n").split("\n") if x.strip())
|
||||
|
||||
|
||||
def _day_memo(records: list) -> tuple[str, str]:
|
||||
"""Use the longest memo of the day; morning and evening punches usually repeat it."""
|
||||
best_site, best_memo = "", ""
|
||||
for rec in records:
|
||||
memo = _memo_oneline(rec)
|
||||
if len(memo) >= len(best_memo):
|
||||
best_memo = memo
|
||||
best_site = (rec.get("siteName") or "").strip()
|
||||
return best_site, best_memo
|
||||
|
||||
|
||||
def print_table(summaries) -> None:
|
||||
print(f"{'日期':<12}{'次数':>4} {'补卡':<4} {'最早':<9}{'最晚':<9}{'时长h':>6} {'状态':<18}站点")
|
||||
print("-" * 114)
|
||||
for s in summaries:
|
||||
site, memo = _day_memo(s.records)
|
||||
supp = "含补" if s.has_supplement else " "
|
||||
print(f"{s.day.isoformat():<12}{s.count:>4} {supp:<4} {_fmt_t(s.first):<9}{_fmt_t(s.last):<9}"
|
||||
f"{s.hours:>6.1f} {s.status:<18}{site}")
|
||||
if memo:
|
||||
print(f" {memo}")
|
||||
|
||||
|
||||
def export_csv(rows: list[dict], path: str) -> None:
|
||||
cols = ["signDate", "signType", "distance", "siteCode", "siteName", "memo", "phoneSubmitTime", "status"]
|
||||
with open(path, "w", newline="", encoding="utf-8-sig") as f:
|
||||
w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore")
|
||||
w.writeheader()
|
||||
for r in sorted(rows, key=lambda x: x.get("signDate") or ""):
|
||||
w.writerow({k: r.get(k, "") for k in cols})
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
p = argparse.ArgumentParser(prog="punchlog", description="个人打卡记录与缺卡统计")
|
||||
p.add_argument("--month", help="月份 YYYY-MM(默认当月)")
|
||||
p.add_argument("--start", help="起始日期 YYYY-MM-DD")
|
||||
p.add_argument("--end", help="结束日期 YYYY-MM-DD", default="")
|
||||
p.add_argument("--csv", help="导出明细 CSV 到指定路径")
|
||||
p.add_argument("--env", help=".env 路径")
|
||||
return p
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
if args.start:
|
||||
start, end = args.start, args.end
|
||||
else:
|
||||
start, end = _month_range(args.month or _default_month())
|
||||
|
||||
cfg = config_from_env(args.env)
|
||||
client = IepmsClient(cfg)
|
||||
start_d = date.fromisoformat(start)
|
||||
end_d = date.fromisoformat(end) if end else None
|
||||
# 补卡只能在 5 天内补(signDate=提交日,可能晚于被补当天 5 天内),故抓取窗口放宽到 end+5 天,
|
||||
# 再按有效归属日过滤到所选区间;不必拉到今天。
|
||||
fetch_end = (end_d or date.today()) + timedelta(days=SUPPLEMENT_WINDOW_DAYS)
|
||||
rows = client.fetch_all(start, fetch_end.isoformat())
|
||||
|
||||
summaries = daily_summaries(rows, start_d, end_d)
|
||||
print(f"\n== 打卡记录 {start} ~ {end or '今'}({len(summaries)} 天)==")
|
||||
print_table(summaries)
|
||||
|
||||
# 今日提醒
|
||||
today = date.today()
|
||||
today_in_range = start <= today.isoformat() <= (end or "9999")
|
||||
print("\n== 今日提醒 ==")
|
||||
if not today_in_range:
|
||||
print(f"(所选区间 {start}~{end or '今'} 不含今日 {today.isoformat()},跳过今日提醒)")
|
||||
else:
|
||||
ts = today_status(rows, today)
|
||||
if ts is None:
|
||||
print("⚠ 今天还没有打卡记录!")
|
||||
elif ts.status == STATUS_OK:
|
||||
print(f"✓ 今日已打卡 {ts.count} 次,{_fmt_t(ts.first)}~{_fmt_t(ts.last)}({ts.hours:.1f}h),{ts.status}")
|
||||
else:
|
||||
print(f"⚠ 今日打卡 {ts.count} 次,{_fmt_t(ts.first)}~{_fmt_t(ts.last)}({ts.hours:.1f}h),{ts.status}")
|
||||
|
||||
# 缺卡统计
|
||||
probs = problems(rows, start_d, end_d)
|
||||
print(f"\n== 缺卡/不足统计({len(probs)} 天)==")
|
||||
if not probs:
|
||||
print("✓ 区间内无缺卡/时间不足。")
|
||||
for s in probs:
|
||||
print(f" {s.day.isoformat()} {s.status} 次数={s.count} 时长={s.hours:.1f}h "
|
||||
f"({_fmt_t(s.first)}~{_fmt_t(s.last)})")
|
||||
|
||||
if args.csv:
|
||||
export_csv(rows, args.csv)
|
||||
print(f"\n明细已导出: {args.csv}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,48 +0,0 @@
|
||||
"""Load configuration from a .env file (no external dependency)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from .iepms import IepmsConfig
|
||||
|
||||
|
||||
def _find_env(start: Path) -> Path | None:
|
||||
for p in [start, *start.parents]:
|
||||
f = p / ".env"
|
||||
if f.is_file():
|
||||
return f
|
||||
return None
|
||||
|
||||
|
||||
def load_env(path: str | os.PathLike | None = None) -> dict[str, str]:
|
||||
env: dict[str, str] = {}
|
||||
f = Path(path) if path else _find_env(Path(__file__).resolve().parent)
|
||||
if not f or not Path(f).is_file():
|
||||
return env
|
||||
for line in Path(f).read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
k, v = line.split("=", 1)
|
||||
env[k.strip()] = v.strip().strip('"').strip("'")
|
||||
return env
|
||||
|
||||
|
||||
def config_from_env(path: str | os.PathLike | None = None) -> IepmsConfig:
|
||||
env = {**load_env(path), **os.environ}
|
||||
missing = [k for k in ("ICENTER_ACCOUNT", "ICENTER_TOKEN", "ICENTER_PROJECT_ID") if not env.get(k)]
|
||||
if missing:
|
||||
raise SystemExit(
|
||||
"缺少配置: " + ", ".join(missing) + "\n请在 .env 中设置 ICENTER_ACCOUNT / ICENTER_TOKEN / "
|
||||
"ICENTER_PROJECT_ID (token 可用 tools/extract_token 从手机提取)。"
|
||||
)
|
||||
return IepmsConfig(
|
||||
emp_no=env["ICENTER_ACCOUNT"],
|
||||
token=env["ICENTER_TOKEN"],
|
||||
project_id=env["ICENTER_PROJECT_ID"],
|
||||
org_id=env.get("ICENTER_ORG_ID", "10001"),
|
||||
tenant_id=env.get("ICENTER_TENANT_ID", "10001"),
|
||||
cookie=env.get("ICENTER_COOKIE", ""),
|
||||
)
|
||||
@@ -1,97 +0,0 @@
|
||||
"""iEPMS attendance (sign) client.
|
||||
|
||||
Key finding from reverse engineering + live testing: the iEPMS gateway validates the
|
||||
``X-Auth-Value`` token but does NOT enforce ``x-auth-signature`` on the attendance
|
||||
read APIs (listMy returns data with a garbage signature or none at all). So fetching
|
||||
punch records only requires a valid token. We still send a best-effort signature set
|
||||
for parity with the app, but it is not required.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Iterator
|
||||
|
||||
import requests
|
||||
|
||||
IEPMS_HOST = "https://iepms.dt.zte.com.cn"
|
||||
IEPMS_BASE = IEPMS_HOST + "/zte-crm-iepms-basebff"
|
||||
LIST_MY = IEPMS_BASE + "/zte-iccp-iepms-attendance/app/sign/listMy"
|
||||
|
||||
|
||||
@dataclass
|
||||
class IepmsConfig:
|
||||
emp_no: str
|
||||
token: str
|
||||
project_id: str
|
||||
org_id: str = "10001"
|
||||
tenant_id: str = "10001"
|
||||
authority: str = "EPMS_ADMIN"
|
||||
lang_id: str = "zh_CN"
|
||||
cookie: str = ""
|
||||
|
||||
|
||||
def _headers(cfg: IepmsConfig) -> dict:
|
||||
ts = str(int(time.time() * 1000))
|
||||
h = {
|
||||
"content-type": "application/json;charset=UTF-8",
|
||||
"x-proj-id": cfg.project_id,
|
||||
"x-itp-value": f"projId={cfg.project_id};route=true;projVer=V3.0",
|
||||
"x-emp-no": cfg.emp_no,
|
||||
"x-user-guid": cfg.emp_no,
|
||||
"internal": "1",
|
||||
"x-auth-value": cfg.token,
|
||||
"x-lang-id": cfg.lang_id,
|
||||
"x-org-id": cfg.org_id,
|
||||
"x-origin-servicename": "iEPMS",
|
||||
"x-target-servicename": "zte-iccp-iepms-attendance",
|
||||
"x-tenant-id": cfg.tenant_id,
|
||||
"authority": cfg.authority,
|
||||
"x-auth-timestamp": ts,
|
||||
"User-Agent": "okhttp/4.12.0",
|
||||
}
|
||||
if cfg.cookie:
|
||||
h["Cookie"] = cfg.cookie
|
||||
return h
|
||||
|
||||
|
||||
class IepmsClient:
|
||||
def __init__(self, cfg: IepmsConfig, session: requests.Session | None = None):
|
||||
self.cfg = cfg
|
||||
self.http = session or requests.Session()
|
||||
|
||||
def list_my(self, start_date: str, end_date: str = "", sign_type: int = 0,
|
||||
page_num: int = 1, page_size: int = 50) -> dict:
|
||||
body = {
|
||||
"projectId": self.cfg.project_id,
|
||||
"signUserId": self.cfg.emp_no,
|
||||
"startDate": start_date,
|
||||
"endDate": end_date,
|
||||
"signType": sign_type,
|
||||
"pageSize": page_size,
|
||||
"pageNum": page_num,
|
||||
}
|
||||
r = self.http.post(LIST_MY, data=json.dumps(body), headers=_headers(self.cfg), timeout=30)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
code = (data.get("code") or {}).get("code")
|
||||
if code != "0000":
|
||||
raise RuntimeError(f"listMy failed: {data.get('code')}")
|
||||
return data.get("bo") or {}
|
||||
|
||||
def fetch_all(self, start_date: str, end_date: str = "", sign_type: int = 0,
|
||||
page_size: int = 50) -> list[dict]:
|
||||
"""Fetch every page of records in [start_date, end_date]."""
|
||||
out: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
bo = self.list_my(start_date, end_date, sign_type, page, page_size)
|
||||
rows = bo.get("rows") or []
|
||||
out.extend(rows)
|
||||
total = bo.get("total") or 0
|
||||
if len(out) >= total or not rows:
|
||||
break
|
||||
page += 1
|
||||
return out
|
||||
@@ -1,118 +0,0 @@
|
||||
"""MSA (ZTE) encryption envelope, reverse-engineered from cn.com.zte.android.util.KmsKeyUtil.
|
||||
|
||||
Scheme summary (fully reproduced in pure Python):
|
||||
- A per-exchange AES-256 key ``localKeyString``: 32 random uppercase ASCII letters
|
||||
(A-Z), then base64-encoded. The 32 ASCII bytes ARE the AES key; the base64 text is
|
||||
what gets passed around as ``dataKeyPlain``.
|
||||
- Request body: ``AES/GCM/NoPadding`` (12-byte IV, 128-bit tag). Output text is
|
||||
``base64(ciphertext+tag) + "$$" + base64(iv)``.
|
||||
- ``X-MSA-Encrypt-DataKey`` header = RSA-OAEP(SHA-256) encrypt of ``localKeyString``
|
||||
using the server's transmission public key (X509 DER, base64).
|
||||
- ``X-MSA-Encrypt-PublicKey`` header = the client's freshly generated RSA public key
|
||||
(X509 DER, base64). The server encrypts its response AES key to this key.
|
||||
- Response body is decrypted by: RSA-OAEP-decrypt the response ``X-MSA-Encrypt-DataKey``
|
||||
header with the client private key to recover the server's ``localKeyString``, then
|
||||
AES-GCM-decrypt the body with it.
|
||||
|
||||
RSA: 2048-bit, OAEP with SHA-256 and MGF1(SHA-256). Encrypt chunk size 245, decrypt 256.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
import secrets
|
||||
import string
|
||||
from dataclasses import dataclass
|
||||
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
|
||||
_OAEP = padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(),
|
||||
label=None,
|
||||
)
|
||||
|
||||
RSA_ENC_CHUNK = 245
|
||||
RSA_DEC_CHUNK = 256
|
||||
SPLIT_FLAG = "$$"
|
||||
|
||||
|
||||
def _b64e(b: bytes) -> str:
|
||||
return base64.b64encode(b).decode("ascii")
|
||||
|
||||
|
||||
def _b64d(s: str) -> bytes:
|
||||
return base64.b64decode(s)
|
||||
|
||||
|
||||
def gen_local_key_string() -> str:
|
||||
"""32 random uppercase A-Z chars, base64-encoded (KmsKeyUtil.getLocalKeyString)."""
|
||||
raw = "".join(secrets.choice(string.ascii_uppercase) for _ in range(32))
|
||||
return _b64e(raw.encode("ascii"))
|
||||
|
||||
|
||||
@dataclass
|
||||
class RSAKeyPair:
|
||||
public_b64: str # X509 SubjectPublicKeyInfo DER, base64
|
||||
private_b64: str # PKCS8 DER, base64
|
||||
_priv: rsa.RSAPrivateKey
|
||||
|
||||
@classmethod
|
||||
def generate(cls) -> "RSAKeyPair":
|
||||
priv = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
pub_der = priv.public_key().public_bytes(
|
||||
serialization.Encoding.DER,
|
||||
serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||
)
|
||||
priv_der = priv.private_bytes(
|
||||
serialization.Encoding.DER,
|
||||
serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption(),
|
||||
)
|
||||
return cls(_b64e(pub_der), _b64e(priv_der), priv)
|
||||
|
||||
|
||||
def load_public_from_b64(pub_b64: str):
|
||||
return serialization.load_der_public_key(_b64d(pub_b64))
|
||||
|
||||
|
||||
def encrypt_rsa(server_pub_b64: str, plaintext: str) -> str:
|
||||
"""RSA-OAEP(SHA-256) encrypt, chunked by 245 bytes, concatenated, base64."""
|
||||
pub = load_public_from_b64(server_pub_b64)
|
||||
data = plaintext.encode("utf-8")
|
||||
out = bytearray()
|
||||
for i in range(0, len(data), RSA_ENC_CHUNK):
|
||||
out += pub.encrypt(data[i:i + RSA_ENC_CHUNK], _OAEP)
|
||||
return _b64e(bytes(out))
|
||||
|
||||
|
||||
def decrypt_rsa_bytes(priv: rsa.RSAPrivateKey, encrypted_b64: str) -> bytes:
|
||||
data = _b64d(encrypted_b64)
|
||||
out = bytearray()
|
||||
for i in range(0, len(data), RSA_DEC_CHUNK):
|
||||
out += priv.decrypt(data[i:i + RSA_DEC_CHUNK], _OAEP)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def decrypt_rsa(priv: rsa.RSAPrivateKey, encrypted_b64: str) -> str:
|
||||
return decrypt_rsa_bytes(priv, encrypted_b64).decode("utf-8")
|
||||
|
||||
|
||||
def encrypt_aes_gcm(plaintext: str, local_key_string: str) -> str:
|
||||
key = _b64d(local_key_string) # 32 bytes
|
||||
iv = os.urandom(12)
|
||||
ct = AESGCM(key).encrypt(iv, plaintext.encode("utf-8"), None) # ct||tag
|
||||
return _b64e(ct) + SPLIT_FLAG + _b64e(iv)
|
||||
|
||||
|
||||
def decrypt_aes_gcm(encrypted_text: str, data_key_plain: str) -> str:
|
||||
parts = encrypted_text.split(SPLIT_FLAG)
|
||||
if len(parts) != 2:
|
||||
raise ValueError("Invalid encrypted text format")
|
||||
ct = _b64d(parts[0])
|
||||
iv = _b64d(parts[1])
|
||||
key = _b64d(data_key_plain)
|
||||
return AESGCM(key).decrypt(iv, ct, None).decode("utf-8")
|
||||
Reference in New Issue
Block a user