Files
37duAutomation/workflows/share/hr_login_api.py
T
puddy 57028b8626 feat: 新增HR纯接口登录OA接口探针及试用期变更流程增强
新增3个核心文件:
1. workflows/share/oa_login_api.py:OA纯接口登录模块,与浏览器版输出兼容
2. workflows/share/hr_login_api.py:HR纯接口登录模块,支持滑块验证,与浏览器版输出兼容
3. workflows/share/_probe_we_process_todo.py:HR WeProcess待办探针,验证替代OA待办+SSO链路

同时增强试用期变更流程:
- 新增流程交叉验证逻辑,处理已被他人操作的情况
- 新增离职电子签详情链接获取逻辑
- 新增AI表格自动回填逻辑,处理无需处理的情况
- 新增流程待办查询接口,支持反查流程实例
2026-10-06 17:56:36 +08:00

484 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@FileName: hr_login_api.py
@Description: HR 纯接口登录(无浏览器版),「37duHR登录(接口版)」影刀自定义指令模块源码。
与 workflows/share/hr_login.py(浏览器版)输出完全兼容:
- 登录态落盘同一文件 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json;
- cookies 结构一致(name/value/domain/path/...),各业务脚本零改动;
- 对外入口 main(args) 与返回结构 {success, cookie_path, message, relogin} 一致。
区别:全程 requests 接口完成登录(含滑块验证),不打开浏览器、无拖拽拟人。
登录链路(从登录页前端 JS 逆向 + 2025-10 实测验证):
1. GET /RedseaPlatform/ 建立 Session 基础 cookie(routeEhr/JSESSIONID);
2. GET /RedseaPlatform/captcha/get/verification/image.mob 取滑块图,返回
result = {shadeImage(带缺口背景 jpg b64), originImage(原始背景 jpg b64),
cutoutImage(55x55 拼图块 png b64), y(拼图块 top), x(恒 0)};
前端 CSS 固定 340x171 容器、background 原尺寸绘制 => 浏览器只显示原图
左上角 min(w,340) x min(h,171) 的窗口,坐标系 1:1,匹配前需先裁切到该窗口;
3. 定位缺口 x:
a) 首选 diff 法:|shadeImage - originImage| 最大连通域左边界 = 缺口 x
(两图同源成对,diff 定位最准,且天然免疫整图变换);
b) 兜底模板匹配法(与 hr_login.py 浏览器截图版同源算法);
两者互验:diff 可信用 diff,diff 缺失用模板,分歧过大判定本图不可信换图重取;
4. POST /RedseaPlatform/captcha/check/verification/result.mob?x=&y= 校验滑块(返回 true/false);
5. POST /RedseaPlatform/j_red_security_check/PW 提交登录:
form: MENU_TYPE=classic & sysCode=RedseaP & j_username & j_password=<AES密文> & x & y
header: Csrf-Token: RP(前端写死常量);
密码加密:AES-128-ECB + PKCS7,key='ps_uer_!@#BGYUJN'(前端硬编码),输出 base64;
成功判定:state != "0";失败 state == "0" 且 meg 为错误信息;
6. GET getCurUserInfo 校验会话有效后,cookies 落盘 hr_cookies.json。
配置(与 hr_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
hr_login_username=用户名
hr_login_password=密码
hr_validate_url=(可选)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
全局变量(在影刀流程中创建,此指令负责写入):
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
依赖(影刀「Python包管理」安装):
pip install requests python-dotenv opencv-python numpy pycryptodome
入口:
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
python hr_login_api.py 独立运行(等价 main({"force": false}))
"""
import os
import json
import time
import random
import base64
import requests
import cv2
import numpy as np
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from dotenv import load_dotenv
# ================== 共享路径(与 hr_login.py 统一) ==================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
def _load_shared_env():
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
if os.path.exists(SHARED_ENV_FILE):
load_dotenv(SHARED_ENV_FILE)
load_dotenv()
_load_shared_env()
# ================== 配置 ==================
BASE_URL = 'https://hr.37du.co'
LOGIN_URL = BASE_URL + '/RedseaPlatform/'
CAPTCHA_GET_URL = BASE_URL + '/RedseaPlatform/captcha/get/verification/image.mob'
CAPTCHA_CHECK_URL = BASE_URL + '/RedseaPlatform/captcha/check/verification/result.mob'
LOGIN_POST_URL = BASE_URL + '/RedseaPlatform/j_red_security_check/PW'
GET_CUR_USER_INFO_URL = BASE_URL + '/RedseaPlatform/PtUsers.mc?method=getCurUserInfo'
# 前端登录页硬编码:AES 密钥与 CSRF 常量
AES_KEY = b'ps_uer_!@#BGYUJN'
CSRF_TOKEN = 'RP'
USERNAME = os.getenv('hr_login_username', '')
PASSWORD = os.getenv('hr_login_password', '')
# 浏览器可见窗口(登录页 CSS:.imgBg 340x171 固定、background 原尺寸绘制)
VIEW_W = 340
VIEW_H = 171
RETRY_MAX = 5 # 单轮滑块重试次数(与浏览器版一致)
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
TIMEOUT = 15
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"Chrome/120.0.0.0 Safari/537.36")
def ensure_dir(path):
if path:
os.makedirs(path, exist_ok=True)
# ================== Cookies 持久化(格式与 hr_login.py 兼容) ==================
def save_session_cookies(session):
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
与 hr_login.py(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
cookies = []
for c in session.cookies:
cookies.append({
"name": c.name,
"value": c.value,
"domain": c.domain,
"path": c.path or "/",
"expires": int(c.expires) if c.expires else None,
})
if not cookies:
print("未获取到 Cookies,跳过保存")
return
ensure_dir(_SESSIONS_DIR)
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
json.dump(cookies, f, ensure_ascii=False, indent=2)
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
def load_cookies():
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
# ================== 影刀全局变量 ==================
def _set_login_state(value):
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
try:
glv['login_state'] = value
print(f"已写入影刀全局变量 login_state={value}")
except Exception as e:
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
# ================== API 校验 cookies 有效性(与 hr_login.py 同款) ==================
def _is_hr_session_valid():
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。"""
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
try:
cookies = load_cookies()
if not cookies:
return False
session = requests.Session()
session.headers.update({
"User-Agent": UA,
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies:
if c.get("domain") and "37du.co" in c["domain"]:
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
resp = session.post(validate_url, data={}, timeout=15)
if resp.status_code != 200:
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
return False
text = resp.text
return bool(text) and text.lstrip().startswith(("{", "["))
except Exception as e:
print(f"API 校验 cookies 异常:{e}")
return False
# ================== 密码加密(前端 pubAesEncrypt 等价实现) ==================
def aes_encrypt_password(password):
"""AES-128-ECB + PKCS7,key 前端硬编码,输出 base64(与 CryptoJS encrypted.toString() 一致)。"""
cipher = AES.new(AES_KEY, AES.MODE_ECB)
return base64.b64encode(cipher.encrypt(pad(password.encode('utf-8'), 16))).decode('ascii')
# ================== 滑块图获取与裁切 ==================
def new_session():
"""建立会话:先访问登录页拿基础 cookie(routeEhr/JSESSIONID),验证码/登录绑定同一会话。"""
s = requests.Session()
s.headers.update({
"User-Agent": UA,
"Referer": LOGIN_URL,
"X-Requested-With": "XMLHttpRequest",
})
s.get(LOGIN_URL, timeout=TIMEOUT)
return s
def _b64_to_img(b64str, flag):
"""base64 -> cv2 图像(失败返回 None)。"""
if not b64str:
return None
try:
buf = base64.b64decode(b64str)
return cv2.imdecode(np.frombuffer(buf, np.uint8), flag)
except Exception:
return None
def _crop_view(img):
"""裁切到浏览器可见窗口(左上角 min(w,340) x min(h,171)),坐标系与浏览器 1:1。"""
if img is None:
return None
h, w = img.shape[:2]
return img[:min(h, VIEW_H), :min(w, VIEW_W)]
def get_captcha(session):
"""取滑块图,返回 dict(shade, origin, cutout, y);y 为拼图块 top(服务端给定)。"""
resp = session.get(CAPTCHA_GET_URL, timeout=TIMEOUT)
data = resp.json()
res = data.get("result") or {}
shade = _crop_view(_b64_to_img(res.get("shadeImage"), cv2.IMREAD_COLOR))
origin = _crop_view(_b64_to_img(res.get("originImage"), cv2.IMREAD_COLOR))
cutout = _b64_to_img(res.get("cutoutImage"), cv2.IMREAD_UNCHANGED)
y = int(res.get("y") or 0)
return {"shade": shade, "origin": origin, "cutout": cutout, "y": y}
# ================== 缺口定位 ==================
def locate_by_diff(shade, origin):
"""diff 法:shade/origin 同源成对,逐像素差异的最大连通域左边界 = 缺口 x。
返回 (x, 可信度);不可信返回 (None, 原因)。"""
if shade is None or origin is None or shade.shape != origin.shape:
return None, "图片缺失或尺寸不一致"
diff = cv2.absdiff(shade, origin).max(axis=2)
mask = (diff > 30).astype(np.uint8) * 255
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
n, _, stats, _ = cv2.connectedComponentsWithStats(mask)
if n <= 1:
return None, "无差异区域"
best = max(range(1, n), key=lambda i: stats[i, cv2.CC_STAT_AREA])
area = int(stats[best, cv2.CC_STAT_AREA])
x = int(stats[best, cv2.CC_STAT_LEFT])
# 缺口约 55x55(面积 ~3000),过大/过小视为 jpg 噪声或异常
if area < 300 or area > 12000:
return None, f"差异区域面积异常({area})"
return x, f"diff(area={area})"
def match_slider_dual(bg_img, slider_color):
"""模板匹配滑块缺口,返回物理距离 px。
算法与 hr_login.py 浏览器截图版同源(边缘 Canny + TM_CCOEFF_NORMED + 白区加权)。"""
if bg_img is None or slider_color is None:
return None
bg_h, bg_w = bg_img.shape[:2]
x_offset = 0
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
alpha = slider_color[:, :, 3]
slider_rgb = slider_color[:, :, :3]
ys, xs = np.where(alpha > 0)
if len(ys) > 0:
y_min, y_max = np.min(ys), np.max(ys)
x_min, x_max = np.min(xs), np.max(xs)
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
x_offset, _ = x_min, np.min(ys)
else:
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
s_h, s_w = slider_rgb.shape[:2]
if s_h <= 0 or s_w <= 0 or s_w >= bg_w or s_h >= bg_h:
return None
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
bg_edges = cv2.Canny(gray_bg, 50, 150)
slider_edges = cv2.Canny(gray_slider, 50, 150)
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
candidates = []
temp_result = result.copy()
for _ in range(6):
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
if max_val < 0.03:
break
candidates.append((max_val, max_loc))
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
temp_result[y0:y1, x0:x1] = -2.0
if not candidates:
return None
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
def region_whiteness(x, y, w, h):
roi = bg_img[y:y + h, x:x + w]
if roi.size == 0:
return 0.0
return float(np.all(roi > 200, axis=2).mean())
scored = []
for val, loc in candidates:
x, y = loc
if x <= s_w or x > right_limit:
continue
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
if scored:
scored.sort(key=lambda t: t[0], reverse=True)
best_loc = scored[0][2]
else:
best_loc = candidates[0][1]
distance = best_loc[0] - x_offset
if distance < 0:
distance = 0
if distance + s_w > bg_w:
distance = bg_w - s_w
return distance
def solve_distance(cap):
"""定位缺口并输出应提交的 x(= 滑块从 0 到缺口的距离,即缺口左边界 - 拼图透明边)。
返回 (x, 说明);本图不可信返回 (None, 原因)。
几何说明(与浏览器画面一致):
- 原图宽 >= 340:浏览器只显示左上 340x171 裁切窗口;
- 原图宽 < 340:.imgBg 的 background 默认 repeat 会把原图复制拼接到右侧,
画面上缺口可能出现副本(x_g 与 x_g+原图宽),但服务端记录的是原图缺口
坐标 x_g,提交 x_g 即可通过;
因此匹配始终在原图(裁切后)上进行——拼接成画面等价图反而会让 diff 出双峰
(副本也带缺口)——越界过滤上限用实际图宽。
"""
shade = cap["shade"]
cutout = cap["cutout"]
s_w = cutout.shape[1] if cutout is not None else 55
view_w = shade.shape[1] if shade is not None else VIEW_W
x_diff, info = locate_by_diff(cap["shade"], cap["origin"])
x_tpl = match_slider_dual(cap["shade"], cutout)
print(f" 缺口定位:{info} diff_x={x_diff} tpl_x={x_tpl}")
x, how = None, "无法定位"
if x_diff is not None and x_tpl is not None and abs(x_diff - x_tpl) <= 12:
x, how = x_diff, "diff+tpl 一致"
elif x_diff is not None:
x, how = x_diff, "仅 diff(与模板分歧)"
elif x_tpl is not None:
x, how = x_tpl, "仅模板"
if x is None:
return None, how
# 合理性校验:缺口不会贴最左/最右(贴边缺口可能是平铺坐标映射产物,直接换图)
if x <= s_w or x > view_w - s_w:
return None, f"缺口位置越界({x}, 图宽{view_w})"
return x, how
# ================== 滑块校验与登录提交 ==================
def check_slider(session, x, y):
"""提交滑块校验,返回 True/False。"""
resp = session.post(CAPTCHA_CHECK_URL, params={"x": int(round(x)), "y": int(y)}, timeout=TIMEOUT)
try:
return bool(resp.json())
except Exception:
return False
def submit_login(session, username, password, x, y):
"""提交登录,返回 (ok, message)。"""
form = {
"MENU_TYPE": "classic",
"sysCode": "RedseaP",
"j_username": username,
"j_password": aes_encrypt_password(password),
"x": int(round(x)),
"y": int(y),
}
headers = {"Csrf-Token": CSRF_TOKEN}
resp = session.post(LOGIN_POST_URL, data=form, headers=headers, timeout=TIMEOUT)
try:
result = resp.json()
except Exception:
return False, f"登录响应非 JSON(HTTP {resp.status_code})"
if result.get("state") == "0":
return False, str(result.get("meg") or "登录失败")
return True, "登录成功"
def do_login_api(username, password):
"""完整接口登录:滑块校验(带重试)+ 提交登录。成功返回 True。"""
for rnd in range(LOGIN_ROUND_MAX):
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
try:
session = new_session()
except Exception as e:
print(f"建立会话异常:{e}")
time.sleep(1)
continue
for attempt in range(RETRY_MAX):
print(f"--- 第 {attempt + 1} 次尝试验证 ---")
try:
cap = get_captcha(session)
except Exception as e:
print(f"取验证码图异常:{e}")
time.sleep(1)
continue
shade = cap["shade"]
y = cap["y"]
# y 用实际图高校验(裁切窗口高 = min(图高, 171),小图场景更严谨)
if shade is None or not (0 <= y <= shade.shape[0] - 55):
print(f"验证码图异常(shade={None if shade is None else shade.shape}, y={y})")
time.sleep(0.5)
continue
x, info = solve_distance(cap)
if x is None:
time.sleep(random.uniform(0.3, 0.8))
continue
print(f" 提交滑块校验 x={x} y={y}({info})")
if check_slider(session, x, y):
print(" 滑块校验通过")
ok, msg = submit_login(session, username, password, x, y)
if ok:
save_session_cookies(session)
return True
print(f"登录失败:{msg}")
return False # 账号密码类错误,重试无意义
else:
print(" 滑块校验未通过,换图重试")
time.sleep(random.uniform(0.5, 1.2))
time.sleep(1)
return False
# ================== 登录主入口(与 hr_login.py 同构) ==================
def ensure_login(force=False):
"""
确保存在有效的 HR 登录态并缓存 cookies(纯接口,无浏览器)。
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
"""
_load_shared_env()
_set_login_state(False)
if not (USERNAME and PASSWORD):
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置)", "relogin": False}
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
if not force and _is_hr_session_valid():
print("已通过缓存的 Cookies 复用 HR 登录态")
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE,
"message": "复用缓存登录态", "relogin": False}
ok = do_login_api(USERNAME, PASSWORD)
if ok:
# 登录后校验一次会话有效性,确保落盘的 cookies 可用
if _is_hr_session_valid():
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录失败(滑块验证未通过或接口异常)", "relogin": False}
# ================== 影刀自定义指令入口 ==================
def main(args):
"""
影刀自定义指令「37duHR登录(接口版)」调用入口。
args: dict,可选字段 force(bool) 是否强制重新登录
返回: dict {success, cookie_path, message, relogin}
"""
if not args:
args = {}
force = bool(args.get("force", False))
try:
return ensure_login(force=force)
except Exception as e:
return {"success": False, "cookie_path": COOKIE_FILE,
"message": f"登录过程异常:{e}", "relogin": False}
if __name__ == "__main__":
result = main({"force": False})
print("最终结果:", result)