| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884 |
- package biz.xy;
- import base.WechatC;
- import com.google.gson.JsonElement;
- import com.google.gson.JsonObject;
- import com.google.gson.JsonParser;
- import jakarta.servlet.http.HttpServletRequest;
- import okhttp3.Response;
- import org.apache.commons.io.FileUtils;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import ss.AppB;
- import ss.cmn.idcard.IdcardU;
- import ss.cmn.str.StrDate;
- import ss.cmn.str.StrUuid;
- import ss.db.Db;
- import ss.db.FaceCollectDb;
- import ss.db.SqlCmd;
- import ss.http.HttpU;
- import ss.serv.Serv;
- import ss.serv.ServC;
- import java.io.File;
- import java.sql.SQLException;
- import java.sql.Timestamp;
- import java.net.URLEncoder;
- import java.nio.charset.StandardCharsets;
- import java.text.SimpleDateFormat;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.concurrent.ConcurrentHashMap;
- /**
- * 2026-07-25:匿名人脸采集服务。
- * 使用 FACE_COLLECT 独立数据源,提供扫码令牌校验、身份证号验重、提交覆盖和结果查询。
- */
- public class FaceCollectServ extends Serv {
- private static final Logger log4j = LogManager.getLogger(FaceCollectServ.class);
- private static final String TAB_FACE_COLLECT = "XY_FACE_COLLECT";
- private static final String TAB_FACE_COLLECT_LOG = "XY_FACE_COLLECT_LOG";
- private static final String TAB_FACE_COLLECT_TOKEN = "XY_FACE_COLLECT_TOKEN";
- private static final String SEQ_FACE_COLLECT = "SEQ_XY_FACE_COLLECT";
- private static final String SEQ_FACE_COLLECT_LOG = "SEQ_XY_FACE_COLLECT_LOG";
- private static final String SEQ_FACE_COLLECT_TOKEN = "SEQ_XY_FACE_COLLECT_TOKEN";
- private static final String DEF_SCENE = "faceCollect";
- private static final String DEF_CHANNEL = "miniProgram";
- private static final String DEF_PLATFORM = "mp-weixin";
- private static final String DEF_QRCODE_PAGE = "pages/public/faceCollect/index";
- private static final String DEF_QRCODE_DIR = "faceCollect/qrcode";
- private static final String DEF_QRCODE_ENV = "release";
- private static final int DEF_QRCODE_EXPIRE_DAYS = 30;
- private static final String URL_WECHAT_QRCODE =
- "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";
- private static final int HK_SYNC_STATUS_UNSYNC = 0;
- private static final int JLZT_EDITING = 1;
- private static final long DUP_REQ_GAP_MS = 1200L;
- private static final long SUBMIT_REQ_GAP_MS = 3000L;
- private static final int RATE_LIMIT_MAP_MAX = 4096;
- private static final long RATE_LIMIT_CLEANUP_MS = 10 * 60 * 1000L;
- private static final ConcurrentHashMap<String, Long> RATE_LIMIT_TS_MAP = new ConcurrentHashMap<>();
- @SuppressWarnings("unused")
- public String chkSceneToken() {
- super.wrJsonByResp(chkSceneTokenResult());
- return ServC.SERV_notByA;
- }
- @SuppressWarnings("unused")
- public String chkDupBySfzh() {
- super.wrJsonByResp(chkDupBySfzhResult());
- return ServC.SERV_notByA;
- }
- @SuppressWarnings("unused")
- public String submit() {
- super.wrJsonByResp(submitResult());
- return ServC.SERV_notByA;
- }
- @SuppressWarnings("unused")
- public String uploadTrace() {
- super.wrJsonByResp(uploadTraceResult());
- return ServC.SERV_notByA;
- }
- @SuppressWarnings("unused")
- public String queryResult() {
- super.wrJsonByResp(queryResultData());
- return ServC.SERV_notByA;
- }
- @SuppressWarnings("unused")
- public String genQrcode() {
- super.wrJsonByResp(genQrcodeResult());
- return ServC.SERV_notByA;
- }
- private Map<String, Object> genQrcodeResult() {
- String batchId = StringUtils.defaultIfBlank(rdReqTrim("batchId"), buildBatchId());
- String remark = StringUtils.left(StringUtils.defaultIfBlank(rdReqTrim("remark"), "匿名人脸采集二维码"), 500);
- String envVersion = normalizeEnvVersion(rdReqTrim("envVersion"));
- boolean checkPath = rdReqBool("checkPath", false);
- Integer maxSubmitNum = rdReqNullableInt("maxSubmitNum");
- Timestamp expireTime;
- try {
- expireTime = resolveReqExpireTime();
- } catch (Exception e) {
- return mkFail("FACE_COLLECT_PARAM_INVALID", rdErrMsg(e, "二维码有效期参数不正确。"));
- }
- if (StringUtils.isBlank(batchId))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "二维码批次不能为空。");
- if (!"release".equals(envVersion) && !"trial".equals(envVersion) && !"develop".equals(envVersion))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "envVersion 仅支持 release、trial、develop。");
- if (expireTime == null || !expireTime.after(new Timestamp(System.currentTimeMillis())))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "二维码过期时间必须大于当前时间。");
- if (maxSubmitNum != null && maxSubmitNum <= 0)
- return mkFail("FACE_COLLECT_PARAM_INVALID", "maxSubmitNum 必须大于 0。");
- if (StringUtils.isBlank(AppB.imgBaseDir))
- return mkFail("FACE_COLLECT_CFG_ERROR", "系统未配置图片根目录,无法保存二维码。");
- String token = StrUuid.makeUuid();
- String sceneValue = token;
- String qrPath = buildQrcodeRelPath(token);
- File qrFile = null;
- try (Db gdba = FaceCollectDb.makeConn()) {
- if (gdba == null)
- return mkFail("FACE_COLLECT_DB_ERROR", "人脸采集数据源不可用。");
- byte[] qrBytes = rdWechatMiniProgramQrcode(sceneValue, envVersion, checkPath);
- qrFile = new File(AppB.imgBaseDir, qrPath.replace("/", File.separator));
- File parent = qrFile.getParentFile();
- if (parent != null && !parent.exists() && !parent.mkdirs())
- throw new RuntimeException("二维码目录创建失败:" + parent.getAbsolutePath());
- FileUtils.writeByteArrayToFile(qrFile, qrBytes);
- long tokenId = gdba.rdNextSeqVal(SEQ_FACE_COLLECT_TOKEN);
- Timestamp now = new Timestamp(System.currentTimeMillis());
- SqlCmd insSql = new SqlCmd("insert into " + TAB_FACE_COLLECT_TOKEN +
- " (TOKEN_ID,TOKEN,SCENE,BATCH_ID,STATUS,EXPIRE_TIME,MAX_SUBMIT_NUM,CUR_SUBMIT_NUM,REMARK,CJSJ)" +
- " values (:tokenId,:token,:scene,:batchId,1,:expireTime,:maxSubmitNum,0,:remark,:cjsj)");
- insSql.wrLongParm("tokenId", tokenId);
- insSql.wrStrParm("token", token);
- insSql.wrStrParm("scene", DEF_SCENE);
- insSql.wrStrParm("batchId", StringUtils.left(batchId, 100));
- insSql.wrTimeParm("expireTime", expireTime);
- insSql.wrIntParm("maxSubmitNum", maxSubmitNum);
- insSql.wrStrParm("remark", remark);
- insSql.wrTimeParm("cjsj", now);
- gdba.doModByC(insSql);
- logOper(gdba, 0L, "", token, "genQrcode", true,
- "二维码生成成功,envVersion=" + envVersion + ",batchId=" + batchId + "。");
- gdba.commit();
- Map<String, Object> result = mkOk("二维码生成成功");
- Map<String, Object> data = castData(result);
- data.put("token", token);
- data.put("scene", DEF_SCENE);
- data.put("sceneValue", sceneValue);
- data.put("page", DEF_QRCODE_PAGE);
- data.put("batchId", batchId);
- data.put("expireTime", fmtTime(expireTime));
- data.put("maxSubmitNum", maxSubmitNum);
- data.put("envVersion", envVersion);
- data.put("checkPath", checkPath);
- data.put("qrPath", qrPath);
- data.put("qrPreviewUrl", buildQrcodePreviewUrl(qrPath));
- data.put("miniProgramAppId", WechatC.WECHATP_appId);
- return result;
- } catch (Exception e) {
- if (qrFile != null && qrFile.exists())
- FileUtils.deleteQuietly(qrFile);
- log4j.error("FaceCollectServ.genQrcodeResult() 异常", e);
- return mkFail("FACE_COLLECT_QRCODE_FAIL", rdErrMsg(e, "生成小程序二维码失败。"));
- }
- }
- private Map<String, Object> chkSceneTokenResult() {
- String token = rdReqTrim("token");
- String scene = rdReqTrim("scene");
- String batchId = rdReqTrim("batchId");
- try (Db gdba = FaceCollectDb.makeConn()) {
- if (gdba == null)
- return mkFail("FACE_COLLECT_DB_ERROR", "人脸采集数据源不可用。");
- TokenChkResult tokenChk = chkToken(gdba, token, scene, batchId, false, false);
- Map<String, Object> result = tokenChk.result;
- logOper(gdba, 0L, "", token, "chkSceneToken", rdBool(result.get("ok")), rdStr(result.get("msg")));
- if (rdBool(result.get("ok")) && tokenChk.tokenRow != null) {
- Map<String, Object> data = castData(result);
- data.put("needMatchStudent", false);
- }
- gdba.commit();
- return result;
- } catch (Exception e) {
- log4j.error("FaceCollectServ.chkSceneTokenResult() 异常", e);
- return mkFail("FACE_COLLECT_TOKEN_INVALID", rdErrMsg(e, "二维码已失效或不存在。"));
- }
- }
- private Map<String, Object> chkDupBySfzhResult() {
- String sfzh = normalizeSfzh(rdReqTrim("sfzh"));
- String token = rdReqTrim("token");
- String scene = rdReqTrim("scene");
- String batchId = rdReqTrim("batchId");
- if (StringUtils.isBlank(sfzh))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "身份证号不能为空。");
- if (!IdcardU.chk(sfzh))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "身份证号格式不正确。");
- if (hitRateLimit("dup:" + sfzh, DUP_REQ_GAP_MS))
- return mkFail("FACE_COLLECT_RATE_LIMIT", "请求过于频繁,请稍后再试。");
- try (Db gdba = FaceCollectDb.makeConn()) {
- if (gdba == null)
- return mkFail("FACE_COLLECT_DB_ERROR", "人脸采集数据源不可用。");
- if (StringUtils.isNotBlank(token)) {
- TokenChkResult tokenChk = chkToken(gdba, token, scene, batchId, false, false);
- if (!rdBool(tokenChk.result.get("ok"))) {
- logOper(gdba, 0L, sfzh, token, "chkDupBySfzh", false, rdStr(tokenChk.result.get("msg")));
- gdba.commit();
- return tokenChk.result;
- }
- }
- Map<String, Object> currentRow = selCurrentFaceCollectRow(gdba, sfzh);
- Map<String, Object> result = mkOk("查询成功");
- Map<String, Object> data = castData(result);
- boolean exists = currentRow != null && !currentRow.isEmpty();
- data.put("exists", exists);
- data.put("needConfirmOnSubmit", exists);
- if (exists) {
- data.put("lastSubmitTime", fmtTime(currentRow.get("cjsj")));
- data.put("lastStudentName", rdStr(currentRow.get("xm")));
- data.put("tipMsg", "该身份证号已提交过人脸图片,再次提交将覆盖当前有效人脸图片。");
- } else {
- data.put("tipMsg", "");
- }
- logOper(gdba, 0L, sfzh, token, "chkDupBySfzh", true, exists ? "已存在当前有效记录。" : "未命中当前有效记录。");
- gdba.commit();
- return result;
- } catch (Exception e) {
- log4j.error("FaceCollectServ.chkDupBySfzhResult() 异常", e);
- return mkFail("FACE_COLLECT_QUERY_FAIL", rdErrMsg(e, "身份证号验重失败。"));
- }
- }
- private Map<String, Object> submitResult() {
- HttpServletRequest request = super.req;
- String xm = StringUtils.trimToEmpty(rdReqTrim("xm"));
- String sfzh = normalizeSfzh(rdReqTrim("sfzh"));
- String imgPath = rdReqTrim("imgPath");
- String rawImgPath = StringUtils.defaultIfBlank(rdReqTrim("rawImgPath"), imgPath);
- String token = rdReqTrim("token");
- String scene = rdReqTrim("scene");
- String batchId = rdReqTrim("batchId");
- boolean confirmCover = rdBoolStr(rdReqTrim("confirmCover"));
- String clientDeviceId = StringUtils.defaultIfBlank(rdReqTrim("clientDeviceId"), rdReqTrim("devId"));
- String clientModel = StringUtils.defaultIfBlank(rdReqTrim("clientModel"), rdReqTrim("sbmc"));
- String clientPlatform = StringUtils.defaultIfBlank(rdReqTrim("clientPlatform"), DEF_PLATFORM);
- String clientIp = rdClientIp(request);
- if (StringUtils.isBlank(xm))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "学生姓名不能为空。");
- if (StringUtils.isBlank(sfzh))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "身份证号不能为空。");
- if (!IdcardU.chk(sfzh))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "身份证号格式不正确。");
- if (StringUtils.isBlank(imgPath))
- return mkFail("FACE_COLLECT_IMG_REQUIRED", "人脸图片不能为空。");
- if (!ifValidUploadPath(imgPath) || !ifValidUploadPath(rawImgPath))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "图片路径不合法,请重新拍照上传。");
- if (StringUtils.isBlank(token))
- return mkFail("FACE_COLLECT_TOKEN_INVALID", "缺少有效的二维码令牌。");
- if (hitRateLimit("submit:" + sfzh, SUBMIT_REQ_GAP_MS))
- return mkFail("FACE_COLLECT_RATE_LIMIT", "提交过于频繁,请稍后再试。");
- try (Db gdba = FaceCollectDb.makeConn()) {
- if (gdba == null)
- return mkFail("FACE_COLLECT_DB_ERROR", "人脸采集数据源不可用。");
- TokenChkResult tokenChk = chkToken(gdba, token, scene, batchId, true, true);
- if (!rdBool(tokenChk.result.get("ok"))) {
- logOper(gdba, 0L, sfzh, token, "submit", false, rdStr(tokenChk.result.get("msg")));
- gdba.commit();
- return tokenChk.result;
- }
- Map<String, Object> currentRow = selCurrentFaceCollectRow(gdba, sfzh);
- boolean isCover = currentRow != null && !currentRow.isEmpty();
- if (isCover && !confirmCover) {
- Map<String, Object> result = mkFail("FACE_COLLECT_NEED_CONFIRM_COVER",
- "该身份证号已提交过人脸图片,本次提交会覆盖上一次当前有效人脸图片,请确认后再提交。");
- Map<String, Object> data = castData(result);
- data.put("needConfirmCover", true);
- data.put("lastSubmitTime", fmtTime(currentRow.get("cjsj")));
- data.put("lastStudentName", rdStr(currentRow.get("xm")));
- logOper(gdba, 0L, sfzh, token, "submit", false, rdStr(result.get("msg")));
- gdba.commit();
- return result;
- }
- int versionNo = rdInt(currentRow == null ? null : currentRow.get("version_no"), 0) + 1;
- long faceCollectId = gdba.rdNextSeqVal(SEQ_FACE_COLLECT);
- Timestamp now = new Timestamp(System.currentTimeMillis());
- long coveredFaceCollectId = rdLong(currentRow == null ? null : currentRow.get("face_collect_id"));
- if (isCover) {
- SqlCmd resetSql = new SqlCmd("update " + TAB_FACE_COLLECT +
- " set IS_CURRENT=0,XGSJ=:xgsj where SFZH=:sfzh and IS_CURRENT=1");
- resetSql.wrTimeParm("xgsj", now);
- resetSql.wrStrParm("sfzh", sfzh);
- gdba.doModByC(resetSql);
- }
- SqlCmd insSql = new SqlCmd("insert into " + TAB_FACE_COLLECT +
- " (FACE_COLLECT_ID,XM,SFZH,IMG_PATH,RAW_IMG_PATH,VERSION_NO,IS_CURRENT,SRC_CHANNEL,QR_TOKEN,BATCH_ID," +
- " CLIENT_DEVICE_ID,CLIENT_MODEL,CLIENT_PLATFORM,CLIENT_IP,SYNC_HK_STATUS,CJSJ,JLZTM)" +
- " values (:faceCollectId,:xm,:sfzh,:imgPath,:rawImgPath,:versionNo,1,:srcChannel,:qrToken,:batchId," +
- " :clientDeviceId,:clientModel,:clientPlatform,:clientIp,:syncHkStatus,:cjsj,:jlztm)");
- insSql.wrLongParm("faceCollectId", faceCollectId);
- insSql.wrStrParm("xm", xm);
- insSql.wrStrParm("sfzh", sfzh);
- insSql.wrStrParm("imgPath", imgPath);
- insSql.wrStrParm("rawImgPath", rawImgPath);
- insSql.wrIntParm("versionNo", versionNo);
- insSql.wrStrParm("srcChannel", DEF_CHANNEL);
- insSql.wrStrParm("qrToken", token);
- insSql.wrStrParm("batchId", rdStr(tokenChk.tokenRow.get("batch_id")));
- insSql.wrStrParm("clientDeviceId", clientDeviceId);
- insSql.wrStrParm("clientModel", clientModel);
- insSql.wrStrParm("clientPlatform", clientPlatform);
- insSql.wrStrParm("clientIp", clientIp);
- insSql.wrIntParm("syncHkStatus", HK_SYNC_STATUS_UNSYNC);
- insSql.wrTimeParm("cjsj", now);
- insSql.wrIntParm("jlztm", JLZT_EDITING);
- gdba.doModByC(insSql);
- SqlCmd updTokenSql = new SqlCmd("update " + TAB_FACE_COLLECT_TOKEN +
- " set CUR_SUBMIT_NUM=nvl(CUR_SUBMIT_NUM,0)+1 where TOKEN_ID=:tokenId");
- updTokenSql.wrLongParm("tokenId", rdLong(tokenChk.tokenRow.get("token_id")));
- gdba.doModByC(updTokenSql);
- String logMsg = isCover
- ? "覆盖提交成功,已将上一次当前有效记录转为历史版本。"
- : "首次提交成功。";
- logOper(gdba, faceCollectId, sfzh, token, "submit", true, logMsg);
- gdba.commit();
- Map<String, Object> result = mkOk(isCover
- ? "提交成功,本次已覆盖上一次当前有效人脸图片"
- : "提交成功");
- Map<String, Object> data = castData(result);
- data.put("faceCollectId", faceCollectId);
- data.put("isCover", isCover);
- data.put("coveredFaceCollectId", isCover ? coveredFaceCollectId : 0L);
- data.put("versionNo", versionNo);
- data.put("submitTime", fmtTime(now));
- data.put("imgPath", imgPath);
- data.put("currentTokenSubmitNum", rdInt(tokenChk.tokenRow.get("cur_submit_num"), 0) + 1);
- return result;
- } catch (Exception e) {
- log4j.error("FaceCollectServ.submitResult() 异常", e);
- return mkFail("FACE_COLLECT_SAVE_FAIL", rdErrMsg(e, "提交失败,请稍后重试。"));
- }
- }
- private Map<String, Object> queryResultData() {
- long faceCollectId = rdReqLong("faceCollectId");
- String sfzh = normalizeSfzh(rdReqTrim("sfzh"));
- if (faceCollectId <= 0 && StringUtils.isBlank(sfzh))
- return mkFail("FACE_COLLECT_PARAM_INVALID", "缺少查询参数。");
- try (Db gdba = FaceCollectDb.makeConn()) {
- if (gdba == null)
- return mkFail("FACE_COLLECT_DB_ERROR", "人脸采集数据源不可用。");
- Map<String, Object> row = faceCollectId > 0
- ? selFaceCollectRowById(gdba, faceCollectId)
- : selCurrentFaceCollectRow(gdba, sfzh);
- if (row == null || row.isEmpty()) {
- logOper(gdba, faceCollectId, sfzh, rdReqTrim("token"), "queryResult", false, "未查询到人脸采集记录。");
- gdba.commit();
- return mkFail("FACE_COLLECT_NOT_FOUND", "未查询到人脸采集记录。");
- }
- Map<String, Object> result = mkOk("查询成功");
- Map<String, Object> data = castData(result);
- data.put("faceCollectId", rdLong(row.get("face_collect_id")));
- data.put("xm", rdStr(row.get("xm")));
- data.put("sfzhMask", maskSfzh(rdStr(row.get("sfzh"))));
- data.put("imgPath", rdStr(row.get("img_path")));
- data.put("rawImgPath", rdStr(row.get("raw_img_path")));
- data.put("isCurrent", rdInt(row.get("is_current"), 0) == 1);
- data.put("versionNo", rdInt(row.get("version_no"), 0));
- data.put("submitTime", fmtTime(row.get("cjsj")));
- data.put("syncHkStatus", rdInt(row.get("sync_hk_status"), 0));
- data.put("syncHkMsg", rdStr(row.get("sync_hk_msg")));
- data.put("batchId", rdStr(row.get("batch_id")));
- logOper(gdba, rdLong(row.get("face_collect_id")), rdStr(row.get("sfzh")),
- rdReqTrim("token"), "queryResult", true, "查询成功。");
- gdba.commit();
- return result;
- } catch (Exception e) {
- log4j.error("FaceCollectServ.queryResultData() 异常", e);
- return mkFail("FACE_COLLECT_QUERY_FAIL", rdErrMsg(e, "查询失败,请稍后再试。"));
- }
- }
- private Map<String, Object> uploadTraceResult() {
- String token = rdReqTrim("token");
- String scene = StringUtils.defaultIfBlank(rdReqTrim("scene"), DEF_SCENE);
- String batchId = rdReqTrim("batchId");
- String uploadReason = StringUtils.left(rdReqTrim("uploadReason"), 100);
- String latestEvent = StringUtils.left(rdReqTrim("latestEvent"), 100);
- String clientPage = StringUtils.left(rdReqTrim("clientPage"), 200);
- String traceSize = rdReqTrim("traceSize");
- String traceJson = rdReqTrim("traceJson");
- String summary = buildTraceUploadSummary(uploadReason, latestEvent, traceSize, clientPage, traceJson);
- String clientIp = rdClientIp(super.req);
- String contentType = rdReqContentType();
- String paramKeys = rdReqParamKeys();
- if (StringUtils.isBlank(token))
- return mkTraceUploadFail("FACE_COLLECT_PARAM_INVALID", "缺少二维码令牌。",
- "missing_token", token, scene, batchId, clientIp, contentType, paramKeys, summary, null);
- if (StringUtils.isBlank(traceJson))
- return mkTraceUploadFail("FACE_COLLECT_PARAM_INVALID", "缺少调试日志内容。",
- "missing_trace_json", token, scene, batchId, clientIp, contentType, paramKeys, summary, null);
- try (Db gdba = FaceCollectDb.makeConn()) {
- if (gdba == null) {
- return mkTraceUploadFail("FACE_COLLECT_TRACE_UPLOAD_FAIL", "调试日志上报失败。",
- "db_unavailable", token, scene, batchId, clientIp, contentType, paramKeys, summary, null);
- }
- JsonElement traceElement = JsonParser.parseString(traceJson);
- String traceCompact = StringUtils.left(traceElement.toString(), 8000);
- log4j.warn("FaceCollectServ.uploadTraceResult() token={}, scene={}, batchId={}, clientIp={}, contentType={}, paramKeys={}, summary={}, trace={}",
- maskToken(token), scene, batchId, clientIp, contentType, paramKeys, summary, traceCompact);
- logOper(gdba, 0L, "", token, "uploadTrace", true, StringUtils.left(summary, 1000));
- gdba.commit();
- Map<String, Object> result = mkOk("调试日志上报成功");
- Map<String, Object> data = castData(result);
- data.put("scene", scene);
- data.put("batchId", batchId);
- data.put("uploadReason", uploadReason);
- data.put("latestEvent", latestEvent);
- data.put("traceSize", traceSize);
- data.put("recvTime", fmtTime(new Timestamp(System.currentTimeMillis())));
- return result;
- } catch (Exception e) {
- return mkTraceUploadFail("FACE_COLLECT_TRACE_UPLOAD_FAIL", rdErrMsg(e, "调试日志上报失败。"),
- "exception", token, scene, batchId, clientIp, contentType, paramKeys, summary, e);
- }
- }
- private String buildTraceUploadSummary(String uploadReason, String latestEvent, String traceSize,
- String clientPage, String traceJson) {
- return "reason=" + StringUtils.defaultIfBlank(uploadReason, "-")
- + ",event=" + StringUtils.defaultIfBlank(latestEvent, "-")
- + ",traceSize=" + StringUtils.defaultIfBlank(traceSize, "-")
- + ",traceJsonLen=" + StringUtils.length(traceJson)
- + ",page=" + StringUtils.defaultIfBlank(clientPage, "-");
- }
- private Map<String, Object> mkTraceUploadFail(String code, String msg, String failReason,
- String token, String scene, String batchId,
- String clientIp, String contentType, String paramKeys,
- String summary, Exception e) {
- if (e == null) {
- log4j.warn("FaceCollectServ.uploadTraceResult() 业务失败: reason={}, token={}, scene={}, batchId={}, clientIp={}, contentType={}, paramKeys={}, summary={}",
- failReason, maskToken(token), scene, batchId, clientIp, contentType, paramKeys, summary);
- } else {
- log4j.error("FaceCollectServ.uploadTraceResult() 异常: reason={}, token={}, scene={}, batchId={}, clientIp={}, contentType={}, paramKeys={}, summary={}",
- failReason, maskToken(token), scene, batchId, clientIp, contentType, paramKeys, summary, e);
- }
- return mkFail(code, msg);
- }
- private TokenChkResult chkToken(Db gdba, String token, String reqScene, String reqBatchId,
- boolean needQuota, boolean forUpdate) throws SQLException {
- if (StringUtils.isBlank(token))
- return new TokenChkResult(mkFail("FACE_COLLECT_TOKEN_INVALID", "二维码已失效或不存在。"), null);
- StringBuilder sql = new StringBuilder("select TOKEN_ID,TOKEN,SCENE,BATCH_ID,STATUS,EXPIRE_TIME,MAX_SUBMIT_NUM,CUR_SUBMIT_NUM" +
- " from " + TAB_FACE_COLLECT_TOKEN + " where TOKEN=:token");
- if (forUpdate)
- sql.append(" for update");
- SqlCmd sqlCmd = new SqlCmd(sql.toString());
- sqlCmd.wrStrParm("token", token);
- Map<String, Object> tokenRow = gdba.doSelMapByC(sqlCmd);
- if (tokenRow == null || tokenRow.isEmpty())
- return new TokenChkResult(mkFail("FACE_COLLECT_TOKEN_INVALID", "二维码已失效或不存在。"), null);
- int status = rdInt(tokenRow.get("status"), 0);
- Timestamp expireTime = rdTime(tokenRow.get("expire_time"));
- Timestamp now = new Timestamp(System.currentTimeMillis());
- if (status == 0)
- return new TokenChkResult(mkFail("FACE_COLLECT_TOKEN_INVALID", "二维码已停用。"), tokenRow);
- if (status == 9 || (expireTime != null && expireTime.before(now)))
- return new TokenChkResult(mkFail("FACE_COLLECT_TOKEN_EXPIRED", "二维码已过期。"), tokenRow);
- String dbScene = StringUtils.defaultIfBlank(rdStr(tokenRow.get("scene")), DEF_SCENE);
- String dbBatchId = rdStr(tokenRow.get("batch_id"));
- if (StringUtils.isNotBlank(reqScene) && !StringUtils.equalsIgnoreCase(reqScene, dbScene))
- return new TokenChkResult(mkFail("FACE_COLLECT_TOKEN_INVALID", "二维码场景不匹配。"), tokenRow);
- if (StringUtils.isNotBlank(reqBatchId) && StringUtils.isNotBlank(dbBatchId)
- && !StringUtils.equals(reqBatchId, dbBatchId))
- return new TokenChkResult(mkFail("FACE_COLLECT_TOKEN_INVALID", "二维码批次不匹配。"), tokenRow);
- if (needQuota) {
- Integer maxSubmitNum = rdNullableInt(tokenRow.get("max_submit_num"));
- int curSubmitNum = rdInt(tokenRow.get("cur_submit_num"), 0);
- if (maxSubmitNum != null && maxSubmitNum > 0 && curSubmitNum >= maxSubmitNum)
- return new TokenChkResult(mkFail("FACE_COLLECT_TOKEN_EXHAUSTED", "当前二维码提交次数已达上限。"), tokenRow);
- }
- Map<String, Object> result = mkOk("校验通过");
- Map<String, Object> data = castData(result);
- data.put("valid", true);
- data.put("scene", dbScene);
- data.put("batchId", dbBatchId);
- data.put("expireTime", fmtTime(expireTime));
- data.put("needMatchStudent", false);
- data.put("curSubmitNum", rdInt(tokenRow.get("cur_submit_num"), 0));
- data.put("maxSubmitNum", rdNullableInt(tokenRow.get("max_submit_num")));
- return new TokenChkResult(result, tokenRow);
- }
- private Map<String, Object> selCurrentFaceCollectRow(Db gdba, String sfzh) throws SQLException {
- SqlCmd sqlCmd = new SqlCmd("select * from (" +
- " select FACE_COLLECT_ID,XM,SFZH,IMG_PATH,RAW_IMG_PATH,VERSION_NO,IS_CURRENT,BATCH_ID,SYNC_HK_STATUS,SYNC_HK_MSG,CJSJ" +
- " from " + TAB_FACE_COLLECT +
- " where SFZH=:sfzh and IS_CURRENT=1 order by VERSION_NO desc, FACE_COLLECT_ID desc" +
- " ) where rownum=1");
- sqlCmd.wrStrParm("sfzh", sfzh);
- Map<String, Object> row = gdba.doSelMapByC(sqlCmd);
- return row == null || row.isEmpty() ? null : row;
- }
- private Map<String, Object> selFaceCollectRowById(Db gdba, long faceCollectId) throws SQLException {
- SqlCmd sqlCmd = new SqlCmd("select FACE_COLLECT_ID,XM,SFZH,IMG_PATH,RAW_IMG_PATH,VERSION_NO,IS_CURRENT,BATCH_ID,SYNC_HK_STATUS,SYNC_HK_MSG,CJSJ" +
- " from " + TAB_FACE_COLLECT + " where FACE_COLLECT_ID=:faceCollectId");
- sqlCmd.wrLongParm("faceCollectId", faceCollectId);
- Map<String, Object> row = gdba.doSelMapByC(sqlCmd);
- return row == null || row.isEmpty() ? null : row;
- }
- private void logOper(Db gdba, long faceCollectId, String sfzh, String token,
- String operType, boolean ok, String operMsg) {
- try {
- long logId = gdba.rdNextSeqVal(SEQ_FACE_COLLECT_LOG);
- SqlCmd sqlCmd = new SqlCmd("insert into " + TAB_FACE_COLLECT_LOG +
- " (LOG_ID,FACE_COLLECT_ID,SFZH,OPER_TYPE,OPER_DESC,CLIENT_IP,CLIENT_DEVICE_ID,CLIENT_MODEL,QR_TOKEN,OPER_RESULT,OPER_MSG,CJSJ)" +
- " values (:logId,:faceCollectId,:sfzh,:operType,:operDesc,:clientIp,:clientDeviceId,:clientModel,:qrToken,:operResult,:operMsg,:cjsj)");
- sqlCmd.wrLongParm("logId", logId);
- sqlCmd.wrLongParm("faceCollectId", faceCollectId > 0 ? faceCollectId : null);
- sqlCmd.wrStrParm("sfzh", sfzh);
- sqlCmd.wrStrParm("operType", operType);
- sqlCmd.wrStrParm("operDesc", operType);
- sqlCmd.wrStrParm("clientIp", rdClientIp(super.req));
- sqlCmd.wrStrParm("clientDeviceId", StringUtils.defaultIfBlank(rdReqTrim("clientDeviceId"), rdReqTrim("devId")));
- sqlCmd.wrStrParm("clientModel", StringUtils.defaultIfBlank(rdReqTrim("clientModel"), rdReqTrim("sbmc")));
- sqlCmd.wrStrParm("qrToken", token);
- sqlCmd.wrIntParm("operResult", ok ? 1 : 0);
- sqlCmd.wrStrParm("operMsg", StringUtils.left(StringUtils.defaultString(operMsg), 1000));
- sqlCmd.wrTimeParm("cjsj", new Timestamp(System.currentTimeMillis()));
- gdba.doModByC(sqlCmd);
- } catch (Exception e) {
- log4j.warn("FaceCollectServ.logOper() 写操作日志失败,operType={}", operType, e);
- }
- }
- private Map<String, Object> mkOk(String msg) {
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", true);
- result.put("code", "0");
- result.put("msg", msg);
- result.put("data", new LinkedHashMap<String, Object>());
- return result;
- }
- private Map<String, Object> mkFail(String code, String msg) {
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("code", code);
- result.put("msg", msg);
- result.put("data", new LinkedHashMap<String, Object>());
- return result;
- }
- @SuppressWarnings("unchecked")
- private Map<String, Object> castData(Map<String, Object> result) {
- Object data = result.get("data");
- if (data instanceof Map)
- return (Map<String, Object>) data;
- Map<String, Object> map = new LinkedHashMap<>();
- result.put("data", map);
- return map;
- }
- private String rdReqTrim(String parmName) {
- return StringUtils.trimToEmpty(super.req == null ? null : super.req.getParameter(parmName));
- }
- private String rdReqContentType() {
- if (super.req == null)
- return "";
- return StringUtils.defaultString(super.req.getContentType());
- }
- private String rdReqParamKeys() {
- if (super.req == null || super.req.getParameterMap() == null || super.req.getParameterMap().isEmpty())
- return "";
- return StringUtils.left(String.join(",", super.req.getParameterMap().keySet()), 500);
- }
- private boolean rdReqBool(String parmName, boolean defVal) {
- String valStr = rdReqTrim(parmName);
- if (StringUtils.isBlank(valStr))
- return defVal;
- return rdBoolStr(valStr);
- }
- private Integer rdReqNullableInt(String parmName) {
- String valStr = rdReqTrim(parmName);
- if (StringUtils.isBlank(valStr))
- return null;
- try {
- return Integer.parseInt(valStr);
- } catch (Exception e) {
- return null;
- }
- }
- private long rdReqLong(String parmName) {
- String valStr = rdReqTrim(parmName);
- if (StringUtils.isBlank(valStr))
- return 0L;
- try {
- return Long.parseLong(valStr);
- } catch (Exception e) {
- return 0L;
- }
- }
- private boolean rdBoolStr(String valStr) {
- return "1".equals(valStr) || "true".equalsIgnoreCase(valStr) || "yes".equalsIgnoreCase(valStr);
- }
- private boolean rdBool(Object valObj) {
- if (valObj instanceof Boolean)
- return (Boolean) valObj;
- if (valObj == null)
- return false;
- return rdBoolStr(String.valueOf(valObj));
- }
- private Integer rdNullableInt(Object valObj) {
- if (valObj == null)
- return null;
- if (valObj instanceof Number)
- return ((Number) valObj).intValue();
- String valStr = String.valueOf(valObj).trim();
- if (valStr.isEmpty())
- return null;
- return Integer.parseInt(valStr);
- }
- private int rdInt(Object valObj, int defVal) {
- Integer val = rdNullableInt(valObj);
- return val == null ? defVal : val;
- }
- private long rdLong(Object valObj) {
- if (valObj == null)
- return 0L;
- if (valObj instanceof Number)
- return ((Number) valObj).longValue();
- try {
- return Long.parseLong(String.valueOf(valObj).trim());
- } catch (Exception e) {
- return 0L;
- }
- }
- private Timestamp rdTime(Object valObj) {
- if (valObj instanceof Timestamp)
- return (Timestamp) valObj;
- return null;
- }
- private String rdStr(Object valObj) {
- return valObj == null ? "" : String.valueOf(valObj);
- }
- private String fmtTime(Object timeObj) {
- Timestamp ts = rdTime(timeObj);
- if (ts == null)
- return "";
- return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(ts);
- }
- private String normalizeSfzh(String sfzh) {
- return StringUtils.upperCase(StringUtils.deleteWhitespace(StringUtils.defaultString(sfzh)));
- }
- private String maskSfzh(String sfzh) {
- String val = normalizeSfzh(sfzh);
- if (val.length() <= 8)
- return val;
- return val.substring(0, 4) + "**********" + val.substring(val.length() - 4);
- }
- private String maskToken(String token) {
- String val = StringUtils.defaultString(token).trim();
- if (val.length() <= 10)
- return val;
- return val.substring(0, 6) + "******" + val.substring(val.length() - 4);
- }
- private boolean ifValidUploadPath(String imgPath) {
- if (StringUtils.isBlank(imgPath))
- return false;
- if (imgPath.contains("..") || imgPath.contains(":") || imgPath.startsWith("/") || imgPath.startsWith("\\"))
- return false;
- return imgPath.matches("^[0-9A-Za-z/_-]+\\.[0-9A-Za-z]{2,10}$");
- }
- private String rdClientIp(HttpServletRequest request) {
- if (request == null)
- return "";
- String[] headerArr = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"};
- for (String headerName : headerArr) {
- String val = request.getHeader(headerName);
- if (StringUtils.isBlank(val) || "unknown".equalsIgnoreCase(val))
- continue;
- if (val.contains(","))
- return StringUtils.trim(val.split(",")[0]);
- return StringUtils.trim(val);
- }
- return StringUtils.defaultString(request.getRemoteAddr());
- }
- private boolean hitRateLimit(String key, long gapMs) {
- long now = System.currentTimeMillis();
- cleanupRateLimitMap(now);
- final boolean[] limited = {false};
- RATE_LIMIT_TS_MAP.compute(key, (k, oldVal) -> {
- if (oldVal != null && now - oldVal < gapMs) {
- limited[0] = true;
- return oldVal;
- }
- return now;
- });
- return limited[0];
- }
- private void cleanupRateLimitMap(long now) {
- if (RATE_LIMIT_TS_MAP.size() < RATE_LIMIT_MAP_MAX)
- return;
- for (Map.Entry<String, Long> entry : RATE_LIMIT_TS_MAP.entrySet()) {
- Long oldVal = entry.getValue();
- if (oldVal != null && now - oldVal > RATE_LIMIT_CLEANUP_MS)
- RATE_LIMIT_TS_MAP.remove(entry.getKey(), oldVal);
- }
- }
- private String rdErrMsg(Exception e, String defMsg) {
- String msg = e == null ? "" : e.getMessage();
- return StringUtils.isBlank(msg) ? defMsg : msg;
- }
- private Timestamp resolveReqExpireTime() throws Exception {
- String expireTimeStr = rdReqTrim("expireTime");
- if (StringUtils.isNotBlank(expireTimeStr)) {
- try {
- return StrDate.toTimestamp(expireTimeStr, "yyyy-MM-dd HH:mm:ss");
- } catch (Exception ignore) {
- return StrDate.toTimestamp(expireTimeStr, "yyyy-MM-dd HH:mm");
- }
- }
- Integer expireDays = rdReqNullableInt("expireDays");
- if (expireDays == null)
- expireDays = DEF_QRCODE_EXPIRE_DAYS;
- if (expireDays <= 0)
- throw new RuntimeException("expireDays 必须大于 0。");
- return new Timestamp(System.currentTimeMillis() + expireDays.longValue() * 24 * 60 * 60 * 1000L);
- }
- private String normalizeEnvVersion(String envVersion) {
- return StringUtils.defaultIfBlank(StringUtils.trimToNull(envVersion), DEF_QRCODE_ENV).toLowerCase();
- }
- private String buildBatchId() {
- return "FC" + new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date());
- }
- private String buildQrcodeRelPath(String token) {
- return DEF_QRCODE_DIR + "/" + new SimpleDateFormat("yyyy/MM/dd").format(new java.util.Date()) + "/" + token + ".jpg";
- }
- private String buildQrcodePreviewUrl(String qrPath) {
- return ServC.SPATH_root + "?" + ServC.URL_ssServ + "=dlByHttp&type=img&path=" +
- URLEncoder.encode(qrPath, StandardCharsets.UTF_8);
- }
- private byte[] rdWechatMiniProgramQrcode(String sceneValue, String envVersion, boolean checkPath) throws Exception {
- String accessToken = rdWechatMiniProgramAccessToken();
- if (StringUtils.isBlank(accessToken))
- throw new RuntimeException("未获取到微信 access_token。");
- JsonObject reqBody = new JsonObject();
- reqBody.addProperty("scene", sceneValue);
- reqBody.addProperty("page", DEF_QRCODE_PAGE);
- reqBody.addProperty("env_version", envVersion);
- reqBody.addProperty("check_path", checkPath);
- try (Response response = HttpU.doPostUrl(String.format(URL_WECHAT_QRCODE, accessToken), reqBody)) {
- if (response == null || response.body() == null)
- throw new RuntimeException("微信小程序码接口无响应。");
- byte[] bodyBytes = response.body().bytes();
- if (bodyBytes.length == 0)
- throw new RuntimeException("微信小程序码接口返回空内容。");
- if (ifJsonBody(bodyBytes))
- throw new RuntimeException(parseWechatErrMsg(bodyBytes));
- return bodyBytes;
- }
- }
- private String rdWechatMiniProgramAccessToken() {
- JsonObject tokenResp = HttpU.getUrl(WechatC.URL_rdWechatpToken);
- if (tokenResp == null)
- return null;
- JsonElement accessToken = tokenResp.get("access_token");
- return accessToken == null ? null : accessToken.getAsString();
- }
- private boolean ifJsonBody(byte[] bodyBytes) {
- for (byte bodyByte : bodyBytes) {
- char ch = (char) (bodyByte & 0xFF);
- if (Character.isWhitespace(ch))
- continue;
- return ch == '{' || ch == '[';
- }
- return false;
- }
- private String parseWechatErrMsg(byte[] bodyBytes) {
- try {
- String bodyStr = new String(bodyBytes, StandardCharsets.UTF_8);
- JsonObject errObj = JsonParser.parseString(bodyStr).getAsJsonObject();
- String errCode = errObj.has("errcode") ? errObj.get("errcode").getAsString() : "";
- String errMsg = errObj.has("errmsg") ? errObj.get("errmsg").getAsString() : bodyStr;
- return "微信小程序码生成失败:errcode=" + errCode + ",errmsg=" + errMsg;
- } catch (Exception e) {
- return "微信小程序码生成失败,且错误返回无法解析。";
- }
- }
- private static class TokenChkResult {
- private final Map<String, Object> result;
- private final Map<String, Object> tokenRow;
- private TokenChkResult(Map<String, Object> result, Map<String, Object> tokenRow) {
- this.result = result;
- this.tokenRow = tokenRow;
- }
- }
- }
|