refactor: 改为单包结构,库和命令行放在 src
This commit is contained in:
+160
@@ -0,0 +1,160 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use chrono::{NaiveDate, TimeDelta};
|
||||
|
||||
use crate::record::PunchRecord;
|
||||
|
||||
pub const MIN_WORK_HOURS: f64 = 8.0;
|
||||
pub const SUPPLEMENT_WINDOW_DAYS: i64 = 5;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DayStatus {
|
||||
/// 当天最早和最晚两次间隔不少于 8 小时。
|
||||
Ok,
|
||||
/// 有效打卡少于 2 次。
|
||||
Few,
|
||||
/// 有两次,但间隔不足 8 小时。
|
||||
Short,
|
||||
}
|
||||
|
||||
impl DayStatus {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ok => "正常",
|
||||
Self::Few => "缺卡(不足2次)",
|
||||
Self::Short => "打卡时间不足(<8h)",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_problem(self) -> bool {
|
||||
self != Self::Ok
|
||||
}
|
||||
}
|
||||
|
||||
/// 某一天的打卡汇总。`records` 按有效时间从早到晚排列。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DaySummary {
|
||||
pub day: NaiveDate,
|
||||
pub count: usize,
|
||||
pub first: chrono::NaiveDateTime,
|
||||
pub last: chrono::NaiveDateTime,
|
||||
pub hours: f64,
|
||||
pub status: DayStatus,
|
||||
pub has_supplement: bool,
|
||||
pub records: Vec<PunchRecord>,
|
||||
}
|
||||
|
||||
impl DaySummary {
|
||||
/// 当天最长的一条打卡内容,以及它对应的站点。
|
||||
pub fn content(&self) -> (String, String) {
|
||||
let mut best_site = String::new();
|
||||
let mut best_memo = String::new();
|
||||
for record in &self.records {
|
||||
let memo = record.memo_oneline();
|
||||
if memo.len() >= best_memo.len() {
|
||||
best_memo = memo;
|
||||
best_site = record.site_name.clone().unwrap_or_default();
|
||||
}
|
||||
}
|
||||
(best_site, best_memo)
|
||||
}
|
||||
}
|
||||
|
||||
/// 含 `today` 在内的最近 7 天。
|
||||
pub fn last_week(today: NaiveDate) -> (NaiveDate, NaiveDate) {
|
||||
(today - TimeDelta::days(6), today)
|
||||
}
|
||||
|
||||
/// 按有效打卡日汇总。补卡归到被补的那一天,并且只计已审批通过的。
|
||||
pub fn daily_summaries(
|
||||
rows: Vec<PunchRecord>,
|
||||
start: Option<NaiveDate>,
|
||||
end: Option<NaiveDate>,
|
||||
) -> Vec<DaySummary> {
|
||||
let mut by_day: BTreeMap<NaiveDate, Vec<(chrono::NaiveDateTime, PunchRecord)>> = BTreeMap::new();
|
||||
for record in rows {
|
||||
let Some(at) = record.effective_time() else {
|
||||
continue;
|
||||
};
|
||||
by_day.entry(at.date()).or_default().push((at, record));
|
||||
}
|
||||
|
||||
let mut out = Vec::new();
|
||||
for (day, mut recs) in by_day {
|
||||
if start.is_some_and(|s| day < s) || end.is_some_and(|e| day > e) {
|
||||
continue;
|
||||
}
|
||||
recs.sort_by_key(|(at, _)| *at);
|
||||
let first = recs[0].0;
|
||||
let last = recs.last().unwrap().0;
|
||||
let hours = (last - first).num_seconds() as f64 / 3600.0;
|
||||
let status = if recs.len() < 2 {
|
||||
DayStatus::Few
|
||||
} else if hours < MIN_WORK_HOURS {
|
||||
DayStatus::Short
|
||||
} else {
|
||||
DayStatus::Ok
|
||||
};
|
||||
let has_supplement = recs.iter().any(|(_, r)| r.is_supplement());
|
||||
out.push(DaySummary {
|
||||
day,
|
||||
count: recs.len(),
|
||||
first,
|
||||
last,
|
||||
hours,
|
||||
status,
|
||||
has_supplement,
|
||||
records: recs.into_iter().map(|(_, r)| r).collect(),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::NaiveDate;
|
||||
|
||||
fn rec(sign: &str, supplement: Option<&str>, approved: bool) -> PunchRecord {
|
||||
PunchRecord {
|
||||
sign_id: None,
|
||||
sign_date: Some(sign.into()),
|
||||
sign_type: Some(if supplement.is_some() { 4 } else { 5 }),
|
||||
site_code: None,
|
||||
site_name: Some("站点".into()),
|
||||
memo: Some("1. 上午\n2. 下午".into()),
|
||||
distance: None,
|
||||
supplement_type: supplement.map(|_| 5),
|
||||
supplement_date: supplement.map(str::to_string),
|
||||
supplement_reason: None,
|
||||
approve_status: supplement.map(|_| if approved { 1 } else { 0 }),
|
||||
phone_submit_time: None,
|
||||
status: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approved_supplement_makes_the_day_normal() {
|
||||
let day = NaiveDate::from_ymd_opt(2026, 11, 2).unwrap();
|
||||
let rows = vec![
|
||||
rec("2026-11-02 09:52:09", None, false),
|
||||
rec("2026-11-03 08:32:40", Some("2026-11-02 20:30:00"), true),
|
||||
];
|
||||
let days = daily_summaries(rows, Some(day), Some(day));
|
||||
assert_eq!(days.len(), 1);
|
||||
assert_eq!(days[0].status, DayStatus::Ok);
|
||||
assert!(days[0].has_supplement);
|
||||
assert!(days[0].content().1.contains("2. 下午"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unapproved_supplement_does_not_count() {
|
||||
let day = NaiveDate::from_ymd_opt(2026, 11, 2).unwrap();
|
||||
let rows = vec![
|
||||
rec("2026-11-02 09:52:09", None, false),
|
||||
rec("2026-11-03 08:32:40", Some("2026-11-02 20:30:00"), false),
|
||||
];
|
||||
let days = daily_summaries(rows, Some(day), Some(day));
|
||||
assert_eq!(days[0].status, DayStatus::Few);
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use reqwest::blocking::Client;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::config::AppConfig;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::msa::{self, RsaKeyPair};
|
||||
|
||||
const EMP_BASE: &str = "https://mdm.zte.com.cn/emp/zte-itp-emp-sso";
|
||||
|
||||
/// 一次成功的账号密码登录。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LoginSession {
|
||||
pub emp_no: String,
|
||||
pub token: String,
|
||||
pub tenant_id: String,
|
||||
pub user_info: Value,
|
||||
}
|
||||
|
||||
/// 用配置里的账号、密码和设备身份登录,返回长效 token。
|
||||
pub fn login(config: &AppConfig) -> Result<LoginSession> {
|
||||
if config.password.is_empty() {
|
||||
return Err(Error::MissingConfig("ICENTER_PASSWORD".into()));
|
||||
}
|
||||
let http = Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.build()?;
|
||||
let server_pub = transmission_key(&http, &config.account, &config.tenant_id)?;
|
||||
let keys = RsaKeyPair::generate()?;
|
||||
let local_key = msa::local_key_string();
|
||||
let payload = login_payload(config);
|
||||
let body = msa::encrypt_aes_gcm(&payload, &local_key)?;
|
||||
let data_key = msa::encrypt_rsa(&server_pub, &local_key)?;
|
||||
let response = http
|
||||
.post(format!("{EMP_BASE}/login/pwd"))
|
||||
.header("X-Emp-No", &config.account)
|
||||
.header("X-MSA-Encrypt-PublicKey", &keys.public_b64)
|
||||
.header("X-MSA-Encrypt-DataKey", &data_key)
|
||||
.header("X-Lang-Id", "zh")
|
||||
.header("Client", "android")
|
||||
.header("Accept", "application/json")
|
||||
.header("X-Tenant-Id", &config.tenant_id)
|
||||
.header("Content-Type", "application/json; charset=utf-8")
|
||||
.header("User-Agent", "okhttp/4.12.0")
|
||||
.body(body)
|
||||
.send()?
|
||||
.error_for_status()?;
|
||||
let encrypted_key = response
|
||||
.headers()
|
||||
.get("x-msa-encrypt-datakey")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_string);
|
||||
let text = response.text()?;
|
||||
let Some(encrypted_key) = encrypted_key else {
|
||||
return Err(Error::Login(text.chars().take(300).collect()));
|
||||
};
|
||||
let response_key = keys.decrypt(&encrypted_key)?;
|
||||
let plain = msa::decrypt_aes_gcm(&text, &response_key)?;
|
||||
let data: Value = serde_json::from_str(&plain).map_err(|e| Error::Parse(e.to_string()))?;
|
||||
let code = data["code"]["code"].as_str().unwrap_or("");
|
||||
if code != "0000" {
|
||||
let msg = data["code"]["msg"].as_str().unwrap_or("登录失败");
|
||||
return Err(Error::Login(format!("{code} {msg}")));
|
||||
}
|
||||
let token = data["bo"]["token"]
|
||||
.as_str()
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or_else(|| Error::Login("响应里没有 token".into()))?;
|
||||
Ok(LoginSession {
|
||||
emp_no: config.account.clone(),
|
||||
token: token.to_string(),
|
||||
tenant_id: config.tenant_id.clone(),
|
||||
user_info: data["bo"].clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn transmission_key(http: &Client, emp_no: &str, tenant_id: &str) -> Result<String> {
|
||||
let data: Value = http
|
||||
.get(format!("{EMP_BASE}/login/transmissionkey"))
|
||||
.header("X-Emp-No", emp_no)
|
||||
.header("X-Lang-Id", "zh")
|
||||
.header("X-Tenant-Id", tenant_id)
|
||||
.header("Content-Type", "application/json; charset=utf-8")
|
||||
.header("User-Agent", "okhttp/4.12.0")
|
||||
.send()?
|
||||
.error_for_status()?
|
||||
.json()?;
|
||||
data["bo"]["publicKey"]
|
||||
.as_str()
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| Error::Login(format!("获取传输公钥失败: {data}")))
|
||||
}
|
||||
|
||||
fn login_payload(config: &AppConfig) -> String {
|
||||
let millis = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_millis())
|
||||
.unwrap_or(0);
|
||||
let d = &config.device;
|
||||
serde_json::json!({
|
||||
"loginName": config.account,
|
||||
"loginPwd": config.password,
|
||||
"appId": d.app_id,
|
||||
"deviceBrand": d.device_brand,
|
||||
"deviceMode": d.device_mode,
|
||||
"deviceId": d.device_id,
|
||||
"deviceNum": d.device_num,
|
||||
"androidId": d.android_id,
|
||||
"deviceType": 1,
|
||||
"deviceName": d.device_name,
|
||||
"os": 2,
|
||||
"clientIp": d.client_ip,
|
||||
"packageName": "com.zte.softda",
|
||||
"versionName": d.version_name,
|
||||
"versionCode": d.version_code,
|
||||
"sequence": "relogin",
|
||||
"extendMap": {"timestamp": millis.to_string()},
|
||||
"secretKey": "",
|
||||
"accountId": "",
|
||||
"returnUserInfo": 0,
|
||||
"token": "",
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
/// 当前这台手机的默认值。`.env` 留空时使用。
|
||||
const DEFAULT_DEVICE: DeviceProfile = DeviceProfile {
|
||||
app_id: "A00154",
|
||||
device_id: "V02_CF64B4B1544AC5D3DB79656332385175",
|
||||
device_num: "V02_CF64B4B1544AC5D3DB79656332385175;V02_CF64B4B1544AC5D3DB79656332385175;AID_034b7912-c21d-3bb3-9bfe-ea789d753967",
|
||||
device_brand: "Redmi",
|
||||
device_mode: "25053RT47C",
|
||||
device_name: "Redmi-25053RT47C",
|
||||
android_id: "AID_034b7912-c21d-3bb3-9bfe-ea789d753967",
|
||||
client_ip: "0.0.0.0",
|
||||
version_name: "12.8.1",
|
||||
version_code: 120805,
|
||||
};
|
||||
|
||||
/// 登录报文里的设备身份。换手机或升级 APP 时改配置即可。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DeviceProfile {
|
||||
pub app_id: &'static str,
|
||||
pub device_id: &'static str,
|
||||
pub device_num: &'static str,
|
||||
pub device_brand: &'static str,
|
||||
pub device_mode: &'static str,
|
||||
pub device_name: &'static str,
|
||||
pub android_id: &'static str,
|
||||
pub client_ip: &'static str,
|
||||
pub version_name: &'static str,
|
||||
pub version_code: i64,
|
||||
}
|
||||
|
||||
/// 界面和命令行共用的运行配置。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AppConfig {
|
||||
pub account: String,
|
||||
pub password: String,
|
||||
pub token: String,
|
||||
pub project_id: String,
|
||||
pub org_id: String,
|
||||
pub tenant_id: String,
|
||||
pub device: OwnedDevice,
|
||||
env_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// 从环境读出的设备身份,拥有自己的字符串。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OwnedDevice {
|
||||
pub app_id: String,
|
||||
pub device_id: String,
|
||||
pub device_num: String,
|
||||
pub device_brand: String,
|
||||
pub device_mode: String,
|
||||
pub device_name: String,
|
||||
pub android_id: String,
|
||||
pub client_ip: String,
|
||||
pub version_name: String,
|
||||
pub version_code: i64,
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
/// 从当前目录向上查找 `.env`,环境变量优先于文件。
|
||||
pub fn load() -> Result<Self> {
|
||||
let env_path = find_env();
|
||||
let mut file_env = Vec::new();
|
||||
if let Some(path) = &env_path {
|
||||
file_env = parse_env(&fs::read_to_string(path)?)?;
|
||||
}
|
||||
let get = |key: &str| -> String {
|
||||
env::var(key)
|
||||
.ok()
|
||||
.map(|v| v.trim().to_string())
|
||||
.filter(|v| !v.is_empty())
|
||||
.or_else(|| {
|
||||
file_env
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v.clone())
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let pick = |key: &str, default: &str| {
|
||||
let value = get(key);
|
||||
if value.is_empty() {
|
||||
default.to_string()
|
||||
} else {
|
||||
value
|
||||
}
|
||||
};
|
||||
let account = get("ICENTER_ACCOUNT");
|
||||
let project_id = get("ICENTER_PROJECT_ID");
|
||||
let missing = [("ICENTER_ACCOUNT", account.as_str()), ("ICENTER_PROJECT_ID", project_id.as_str())]
|
||||
.into_iter()
|
||||
.filter(|(_, v)| v.is_empty())
|
||||
.map(|(k, _)| k)
|
||||
.collect::<Vec<_>>();
|
||||
if !missing.is_empty() {
|
||||
return Err(Error::MissingConfig(missing.join(", ")));
|
||||
}
|
||||
let version_code = pick("ICENTER_VERSION_CODE", &DEFAULT_DEVICE.version_code.to_string())
|
||||
.parse::<i64>()
|
||||
.unwrap_or(DEFAULT_DEVICE.version_code);
|
||||
Ok(Self {
|
||||
account,
|
||||
password: get("ICENTER_PASSWORD"),
|
||||
token: get("ICENTER_TOKEN"),
|
||||
project_id,
|
||||
org_id: {
|
||||
let v = get("ICENTER_ORG_ID");
|
||||
if v.is_empty() { "10001".to_string() } else { v }
|
||||
},
|
||||
tenant_id: {
|
||||
let v = get("ICENTER_TENANT_ID");
|
||||
if v.is_empty() { "10001".to_string() } else { v }
|
||||
},
|
||||
device: OwnedDevice {
|
||||
app_id: pick("ICENTER_APP_ID", DEFAULT_DEVICE.app_id),
|
||||
device_id: pick("ICENTER_DEVICE_ID", DEFAULT_DEVICE.device_id),
|
||||
device_num: pick("ICENTER_DEVICE_NUM", DEFAULT_DEVICE.device_num),
|
||||
device_brand: pick("ICENTER_DEVICE_BRAND", DEFAULT_DEVICE.device_brand),
|
||||
device_mode: pick("ICENTER_DEVICE_MODE", DEFAULT_DEVICE.device_mode),
|
||||
device_name: pick("ICENTER_DEVICE_NAME", DEFAULT_DEVICE.device_name),
|
||||
android_id: pick("ICENTER_ANDROID_ID", DEFAULT_DEVICE.android_id),
|
||||
client_ip: pick("ICENTER_CLIENT_IP", DEFAULT_DEVICE.client_ip),
|
||||
version_name: pick("ICENTER_VERSION_NAME", DEFAULT_DEVICE.version_name),
|
||||
version_code,
|
||||
},
|
||||
env_path,
|
||||
})
|
||||
}
|
||||
|
||||
/// 把新 token 写回找到的 `.env`,方便下次直接使用。
|
||||
pub fn store_token(&mut self, token: &str) -> Result<()> {
|
||||
self.token = token.to_string();
|
||||
let Some(path) = &self.env_path else {
|
||||
return Ok(());
|
||||
};
|
||||
let text = fs::read_to_string(path).unwrap_or_default();
|
||||
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
|
||||
let mut found = false;
|
||||
for line in &mut lines {
|
||||
if line.trim_start().starts_with("ICENTER_TOKEN=") {
|
||||
*line = format!("ICENTER_TOKEN={token}");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
lines.push(format!("ICENTER_TOKEN={token}"));
|
||||
}
|
||||
fs::write(path, lines.join("\n") + "\n")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn find_env() -> Option<PathBuf> {
|
||||
let mut dir = env::current_dir().ok()?;
|
||||
loop {
|
||||
let candidate = dir.join(".env");
|
||||
if candidate.is_file() {
|
||||
return Some(candidate);
|
||||
}
|
||||
if !dir.pop() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_env(text: &str) -> Result<Vec<(String, String)>> {
|
||||
let mut out = Vec::new();
|
||||
for raw in text.lines() {
|
||||
let line = raw.trim();
|
||||
if line.is_empty() || line.starts_with('#') || !line.contains('=') {
|
||||
continue;
|
||||
}
|
||||
let (key, value) = line.split_once('=').unwrap();
|
||||
let value = value.trim().trim_matches('"').trim_matches('\'').to_string();
|
||||
out.push((key.trim().to_string(), value));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
use thiserror::Error;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("缺少配置: {0}")]
|
||||
MissingConfig(String),
|
||||
#[error("登录失败: {0}")]
|
||||
Login(String),
|
||||
#[error("登录凭据已失效")]
|
||||
AuthExpired,
|
||||
#[error("拉取打卡记录失败: {0}")]
|
||||
Attendance(String),
|
||||
#[error("网络请求失败: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error("加解密失败: {0}")]
|
||||
Crypto(String),
|
||||
#[error("解析响应失败: {0}")]
|
||||
Parse(String),
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use reqwest::blocking::Client;
|
||||
use serde::Deserialize;
|
||||
use crate::config::AppConfig;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::record::PunchRecord;
|
||||
|
||||
const LIST_MY: &str = "https://iepms.dt.zte.com.cn/zte-crm-iepms-basebff/zte-iccp-iepms-attendance/app/sign/listMy";
|
||||
|
||||
/// 只依赖有效 token 的打卡记录客户端。listMy 不校验签名。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct IepmsClient {
|
||||
account: String,
|
||||
token: String,
|
||||
project_id: String,
|
||||
org_id: String,
|
||||
tenant_id: String,
|
||||
http: Client,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ApiEnvelope<T> {
|
||||
code: ApiCode,
|
||||
bo: Option<T>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ApiCode {
|
||||
code: String,
|
||||
#[serde(default)]
|
||||
msg: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Page {
|
||||
#[serde(default)]
|
||||
total: i64,
|
||||
#[serde(default)]
|
||||
rows: Vec<PunchRecord>,
|
||||
}
|
||||
|
||||
impl IepmsClient {
|
||||
pub fn new(config: &AppConfig) -> Result<Self> {
|
||||
if config.token.is_empty() {
|
||||
return Err(Error::AuthExpired);
|
||||
}
|
||||
Ok(Self {
|
||||
account: config.account.clone(),
|
||||
token: config.token.clone(),
|
||||
project_id: config.project_id.clone(),
|
||||
org_id: config.org_id.clone(),
|
||||
tenant_id: config.tenant_id.clone(),
|
||||
http: Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.build()?,
|
||||
})
|
||||
}
|
||||
|
||||
/// 拉取 `[start, end]` 内的全部记录。日期格式 `YYYY-MM-DD`。
|
||||
pub fn fetch_all(&self, start_date: &str, end_date: &str) -> Result<Vec<PunchRecord>> {
|
||||
let mut out = Vec::new();
|
||||
let mut page = 1;
|
||||
loop {
|
||||
let bo = self.list_my(start_date, end_date, page, 50)?;
|
||||
let total = bo.total;
|
||||
let got = bo.rows.len();
|
||||
out.extend(bo.rows);
|
||||
if got == 0 || out.len() as i64 >= total {
|
||||
break;
|
||||
}
|
||||
page += 1;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn list_my(&self, start_date: &str, end_date: &str, page_num: i64, page_size: i64) -> Result<Page> {
|
||||
let body = serde_json::json!({
|
||||
"projectId": self.project_id,
|
||||
"signUserId": self.account,
|
||||
"startDate": start_date,
|
||||
"endDate": end_date,
|
||||
"signType": 0,
|
||||
"pageSize": page_size,
|
||||
"pageNum": page_num,
|
||||
});
|
||||
let response = self
|
||||
.http
|
||||
.post(LIST_MY)
|
||||
.headers(self.headers()?)
|
||||
.body(body.to_string())
|
||||
.send()?
|
||||
.error_for_status()?;
|
||||
let data: ApiEnvelope<Page> = response
|
||||
.json()
|
||||
.map_err(|e| Error::Parse(e.to_string()))?;
|
||||
match data.code.code.as_str() {
|
||||
"0000" => Ok(data.bo.unwrap_or(Page { total: 0, rows: Vec::new() })),
|
||||
"0002" => Err(Error::AuthExpired),
|
||||
_ => Err(Error::Attendance(format!("{} {}", data.code.code, data.code.msg))),
|
||||
}
|
||||
}
|
||||
|
||||
fn headers(&self) -> Result<reqwest::header::HeaderMap> {
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
let ts = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_millis().to_string())
|
||||
.unwrap_or_else(|_| "0".into());
|
||||
let pairs = [
|
||||
("content-type", "application/json;charset=UTF-8".to_string()),
|
||||
("x-proj-id", self.project_id.clone()),
|
||||
("x-itp-value", format!("projId={};route=true;projVer=V3.0", self.project_id)),
|
||||
("x-emp-no", self.account.clone()),
|
||||
("x-user-guid", self.account.clone()),
|
||||
("internal", "1".into()),
|
||||
("x-auth-value", self.token.clone()),
|
||||
("x-lang-id", "zh_CN".into()),
|
||||
("x-org-id", self.org_id.clone()),
|
||||
("x-origin-servicename", "iEPMS".into()),
|
||||
("x-target-servicename", "zte-iccp-iepms-attendance".into()),
|
||||
("x-tenant-id", self.tenant_id.clone()),
|
||||
("authority", "EPMS_ADMIN".into()),
|
||||
("x-auth-timestamp", ts),
|
||||
("user-agent", "okhttp/4.12.0".into()),
|
||||
];
|
||||
for (key, value) in pairs {
|
||||
headers.insert(
|
||||
reqwest::header::HeaderName::from_bytes(key.as_bytes()).map_err(|e| Error::Parse(e.to_string()))?,
|
||||
reqwest::header::HeaderValue::from_str(&value).map_err(|e| Error::Parse(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
}
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
//! 打卡核心库。界面可以直接调用这里的配置、登录、记录和统计,不必经过命令行。
|
||||
|
||||
mod analyze;
|
||||
mod auth;
|
||||
mod config;
|
||||
mod error;
|
||||
mod iepms;
|
||||
mod msa;
|
||||
mod record;
|
||||
mod report;
|
||||
|
||||
pub use analyze::{daily_summaries, last_week, DayStatus, DaySummary, SUPPLEMENT_WINDOW_DAYS};
|
||||
pub use auth::{login, LoginSession};
|
||||
pub use config::{AppConfig, DeviceProfile};
|
||||
pub use error::{Error, Result};
|
||||
pub use iepms::IepmsClient;
|
||||
pub use record::PunchRecord;
|
||||
pub use report::{load_last_week, WeekReport};
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
use std::process::ExitCode;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(err) => {
|
||||
eprintln!("{err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> punchlog::Result<()> {
|
||||
let mut config = punchlog::AppConfig::load()?;
|
||||
let report = punchlog::load_last_week(&mut config)?;
|
||||
println!("最近一周 {} ~ {}", report.start, report.end);
|
||||
if report.days.is_empty() {
|
||||
println!("这一周没有打卡记录。");
|
||||
return Ok(());
|
||||
}
|
||||
for day in &report.days {
|
||||
let mark = if day.has_supplement { "含补" } else { " " };
|
||||
let (site, memo) = day.content();
|
||||
println!(
|
||||
"{} {} {}~{} {:.1}h {} {}",
|
||||
day.day,
|
||||
mark,
|
||||
day.first.format("%H:%M:%S"),
|
||||
day.last.format("%H:%M:%S"),
|
||||
day.hours,
|
||||
day.status.label(),
|
||||
site
|
||||
);
|
||||
if !memo.is_empty() {
|
||||
println!(" {memo}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
//! iCenter MSA 信封:RSA-OAEP(SHA-256) 保护一次性 AES-256-GCM 密钥。
|
||||
|
||||
use aes_gcm::aead::{Aead, KeyInit};
|
||||
use aes_gcm::{Aes256Gcm, Nonce};
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use base64::Engine;
|
||||
use rand::rngs::OsRng;
|
||||
use rand::Rng;
|
||||
use rsa::pkcs8::{DecodePublicKey, EncodePublicKey};
|
||||
use rsa::{Oaep, RsaPrivateKey, RsaPublicKey};
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
const RSA_ENC_CHUNK: usize = 245;
|
||||
const RSA_DEC_CHUNK: usize = 256;
|
||||
const SPLIT: &str = "$$";
|
||||
|
||||
pub struct RsaKeyPair {
|
||||
private: RsaPrivateKey,
|
||||
pub public_b64: String,
|
||||
}
|
||||
|
||||
impl RsaKeyPair {
|
||||
pub fn generate() -> Result<Self> {
|
||||
let private = RsaPrivateKey::new(&mut OsRng, 2048).map_err(crypto)?;
|
||||
let public = RsaPublicKey::from(&private);
|
||||
let public_b64 = STANDARD.encode(
|
||||
public
|
||||
.to_public_key_der()
|
||||
.map_err(crypto)?
|
||||
.as_bytes(),
|
||||
);
|
||||
Ok(Self { private, public_b64 })
|
||||
}
|
||||
|
||||
pub fn decrypt(&self, encrypted_b64: &str) -> Result<String> {
|
||||
let data = STANDARD.decode(encrypted_b64.trim()).map_err(crypto)?;
|
||||
let mut out = Vec::new();
|
||||
for chunk in data.chunks(RSA_DEC_CHUNK) {
|
||||
out.extend(
|
||||
self.private
|
||||
.decrypt(Oaep::new::<Sha256>(), chunk)
|
||||
.map_err(crypto)?,
|
||||
);
|
||||
}
|
||||
String::from_utf8(out).map_err(|e| Error::Crypto(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// 32 个随机大写字母,再做 base64。这 32 个 ASCII 字节本身就是 AES 密钥。
|
||||
pub fn local_key_string() -> String {
|
||||
let raw: String = (0..32)
|
||||
.map(|_| {
|
||||
let n = OsRng.gen_range(0..26);
|
||||
char::from(b'A' + n)
|
||||
})
|
||||
.collect();
|
||||
STANDARD.encode(raw.as_bytes())
|
||||
}
|
||||
|
||||
pub fn encrypt_rsa(server_pub_b64: &str, plaintext: &str) -> Result<String> {
|
||||
let der = STANDARD.decode(server_pub_b64.trim()).map_err(crypto)?;
|
||||
let public = RsaPublicKey::from_public_key_der(&der).map_err(crypto)?;
|
||||
let data = plaintext.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
for chunk in data.chunks(RSA_ENC_CHUNK) {
|
||||
out.extend(
|
||||
public
|
||||
.encrypt(&mut OsRng, Oaep::new::<Sha256>(), chunk)
|
||||
.map_err(crypto)?,
|
||||
);
|
||||
}
|
||||
Ok(STANDARD.encode(out))
|
||||
}
|
||||
|
||||
pub fn encrypt_aes_gcm(plaintext: &str, local_key_string: &str) -> Result<String> {
|
||||
let key = STANDARD.decode(local_key_string).map_err(crypto)?;
|
||||
let cipher = Aes256Gcm::new_from_slice(&key).map_err(crypto)?;
|
||||
let mut iv = [0u8; 12];
|
||||
OsRng.fill(&mut iv);
|
||||
let ct = cipher
|
||||
.encrypt(Nonce::from_slice(&iv), plaintext.as_bytes())
|
||||
.map_err(crypto)?;
|
||||
Ok(format!("{}{SPLIT}{}", STANDARD.encode(ct), STANDARD.encode(iv)))
|
||||
}
|
||||
|
||||
pub fn decrypt_aes_gcm(encrypted_text: &str, data_key_plain: &str) -> Result<String> {
|
||||
let (ct_b64, iv_b64) = encrypted_text
|
||||
.split_once(SPLIT)
|
||||
.ok_or_else(|| Error::Crypto("密文缺少 $$ 分隔".into()))?;
|
||||
let ct = STANDARD.decode(ct_b64.trim()).map_err(crypto)?;
|
||||
let iv = STANDARD.decode(iv_b64.trim()).map_err(crypto)?;
|
||||
let key = STANDARD.decode(data_key_plain.trim()).map_err(crypto)?;
|
||||
let cipher = Aes256Gcm::new_from_slice(&key).map_err(crypto)?;
|
||||
let plain = cipher
|
||||
.decrypt(Nonce::from_slice(&iv), ct.as_ref())
|
||||
.map_err(crypto)?;
|
||||
String::from_utf8(plain).map_err(|e| Error::Crypto(e.to_string()))
|
||||
}
|
||||
|
||||
fn crypto(err: impl ToString) -> Error {
|
||||
Error::Crypto(err.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn aes_roundtrip() {
|
||||
let key = local_key_string();
|
||||
let enc = encrypt_aes_gcm("打卡", &key).unwrap();
|
||||
assert_eq!(decrypt_aes_gcm(&enc, &key).unwrap(), "打卡");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use chrono::NaiveDateTime;
|
||||
use serde::Deserialize;
|
||||
|
||||
const DT_FMT: &str = "%Y-%m-%d %H:%M:%S";
|
||||
const APPROVED: i64 = 1;
|
||||
|
||||
/// 一条打卡或补卡记录。字段保持服务端原样,界面可以直接展示。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PunchRecord {
|
||||
#[serde(default)]
|
||||
pub sign_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub sign_date: Option<String>,
|
||||
#[serde(default)]
|
||||
pub sign_type: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub site_code: Option<String>,
|
||||
#[serde(default)]
|
||||
pub site_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub memo: Option<String>,
|
||||
#[serde(default)]
|
||||
pub distance: Option<String>,
|
||||
#[serde(default)]
|
||||
pub supplement_type: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub supplement_date: Option<String>,
|
||||
#[serde(default)]
|
||||
pub supplement_reason: Option<String>,
|
||||
#[serde(default)]
|
||||
pub approve_status: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub phone_submit_time: Option<String>,
|
||||
#[serde(default)]
|
||||
pub status: Option<i64>,
|
||||
}
|
||||
|
||||
impl PunchRecord {
|
||||
pub fn is_supplement(&self) -> bool {
|
||||
self.supplement_type.is_some() || self.sign_type == Some(4)
|
||||
}
|
||||
|
||||
/// 这条记录计入哪一个时刻。未审批的补卡不计入。
|
||||
pub fn effective_time(&self) -> Option<NaiveDateTime> {
|
||||
if self.is_supplement() {
|
||||
if self.approve_status != Some(APPROVED) {
|
||||
return None;
|
||||
}
|
||||
return parse_dt(self.supplement_date.as_deref());
|
||||
}
|
||||
parse_dt(self.sign_date.as_deref())
|
||||
}
|
||||
|
||||
pub fn memo_oneline(&self) -> String {
|
||||
self.memo
|
||||
.as_deref()
|
||||
.unwrap_or("")
|
||||
.replace('\r', "\n")
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|line| !line.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" / ")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_dt(value: Option<&str>) -> Option<NaiveDateTime> {
|
||||
let value = value?.get(..19).unwrap_or(value?);
|
||||
NaiveDateTime::parse_from_str(value, DT_FMT).ok()
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
use chrono::{Local, NaiveDate, TimeDelta};
|
||||
|
||||
use crate::analyze::{daily_summaries, last_week, DaySummary, SUPPLEMENT_WINDOW_DAYS};
|
||||
use crate::auth;
|
||||
use crate::config::AppConfig;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::iepms::IepmsClient;
|
||||
|
||||
/// 最近一周的打卡汇总。界面可以直接使用 `days`,不必解析文本。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WeekReport {
|
||||
pub start: NaiveDate,
|
||||
pub end: NaiveDate,
|
||||
pub days: Vec<DaySummary>,
|
||||
}
|
||||
|
||||
/// 读取最近一周。token 失效时用账号密码重新登录,并尽量把新 token 写回 `.env`。
|
||||
pub fn load_last_week(config: &mut AppConfig) -> Result<WeekReport> {
|
||||
let (start, end) = last_week(Local::now().date_naive());
|
||||
let rows = match fetch(config, start, end) {
|
||||
Err(Error::AuthExpired) => {
|
||||
let session = auth::login(config)?;
|
||||
config.store_token(&session.token)?;
|
||||
fetch(config, start, end)?
|
||||
}
|
||||
other => other?,
|
||||
};
|
||||
Ok(WeekReport {
|
||||
start,
|
||||
end,
|
||||
days: daily_summaries(rows, Some(start), Some(end)),
|
||||
})
|
||||
}
|
||||
|
||||
fn fetch(config: &AppConfig, start: NaiveDate, end: NaiveDate) -> Result<Vec<crate::record::PunchRecord>> {
|
||||
let client = IepmsClient::new(config)?;
|
||||
let fetch_end = end + TimeDelta::days(SUPPLEMENT_WINDOW_DAYS);
|
||||
client.fetch_all(&start.to_string(), &fetch_end.to_string())
|
||||
}
|
||||
Reference in New Issue
Block a user