EmailParseService.java 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. package com.smppw.modaq.domain.service;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.collection.ListUtil;
  4. import cn.hutool.core.date.DateUtil;
  5. import cn.hutool.core.exceptions.ExceptionUtil;
  6. import cn.hutool.core.map.MapUtil;
  7. import cn.hutool.core.util.StrUtil;
  8. import com.smppw.modaq.application.components.ReportParseUtils;
  9. import com.smppw.modaq.application.components.report.parser.ReportParser;
  10. import com.smppw.modaq.application.components.report.parser.ReportParserFactory;
  11. import com.smppw.modaq.application.components.report.writer.ReportWriter;
  12. import com.smppw.modaq.application.components.report.writer.ReportWriterFactory;
  13. import com.smppw.modaq.application.util.EmailUtil;
  14. import com.smppw.modaq.common.conts.DateConst;
  15. import com.smppw.modaq.common.conts.EmailParseStatusConst;
  16. import com.smppw.modaq.common.conts.EmailTypeConst;
  17. import com.smppw.modaq.common.enums.ReportParseStatus;
  18. import com.smppw.modaq.common.enums.ReportParserFileType;
  19. import com.smppw.modaq.common.enums.ReportType;
  20. import com.smppw.modaq.common.exception.NotSupportReportException;
  21. import com.smppw.modaq.common.exception.ReportParseException;
  22. import com.smppw.modaq.domain.dto.EmailContentInfoDTO;
  23. import com.smppw.modaq.domain.dto.EmailZipFileDTO;
  24. import com.smppw.modaq.domain.dto.MailboxInfoDTO;
  25. import com.smppw.modaq.domain.dto.report.ParseResult;
  26. import com.smppw.modaq.domain.dto.report.ReportData;
  27. import com.smppw.modaq.domain.dto.report.ReportParserParams;
  28. import com.smppw.modaq.domain.entity.EmailFileInfoDO;
  29. import com.smppw.modaq.domain.entity.EmailParseInfoDO;
  30. import com.smppw.modaq.domain.mapper.EmailFileInfoMapper;
  31. import com.smppw.modaq.domain.mapper.EmailParseInfoMapper;
  32. import com.smppw.modaq.infrastructure.util.ExcelUtil;
  33. import com.smppw.modaq.infrastructure.util.FileUtil;
  34. import jakarta.mail.*;
  35. import jakarta.mail.internet.MimeUtility;
  36. import jakarta.mail.search.ComparisonTerm;
  37. import jakarta.mail.search.ReceivedDateTerm;
  38. import jakarta.mail.search.SearchTerm;
  39. import org.apache.commons.compress.archivers.ArchiveException;
  40. import org.slf4j.Logger;
  41. import org.slf4j.LoggerFactory;
  42. import org.springframework.beans.factory.annotation.Value;
  43. import org.springframework.stereotype.Service;
  44. import org.springframework.util.StopWatch;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.nio.file.Path;
  48. import java.nio.file.Paths;
  49. import java.util.*;
  50. import java.util.regex.Matcher;
  51. import java.util.regex.Pattern;
  52. import java.util.stream.Collectors;
  53. /**
  54. * @author mozuwen
  55. * @date 2024-09-04
  56. * @description 邮件解析服务
  57. */
  58. @Service
  59. public class EmailParseService {
  60. // public static final int stepSize = 10000;
  61. private static final Logger log = LoggerFactory.getLogger(EmailParseService.class);
  62. // 扩展支持的 MIME 类型
  63. private static final Set<String> attachmentMimePrefixes = Set.of(
  64. "application/pdf",
  65. "application/zip",
  66. "application/x-zip-compressed",
  67. "application/rar",
  68. "application/x-rar-compressed"
  69. // 按需添加其他类型...
  70. );
  71. // private final EmailFieldMappingMapper emailFieldMapper;
  72. private final EmailParseInfoMapper emailParseInfoMapper;
  73. private final EmailFileInfoMapper emailFileInfoMapper;
  74. /* 报告解析和入库的方法 */
  75. private final ReportParserFactory reportParserFactory;
  76. private final ReportWriterFactory reportWriterFactory;
  77. @Value("${email.file.path}")
  78. private String path;
  79. public EmailParseService(EmailParseInfoMapper emailParseInfoMapper,
  80. EmailFileInfoMapper emailFileInfoMapper,
  81. ReportParserFactory reportParserFactory,
  82. ReportWriterFactory reportWriterFactory) {
  83. this.emailParseInfoMapper = emailParseInfoMapper;
  84. this.emailFileInfoMapper = emailFileInfoMapper;
  85. this.reportParserFactory = reportParserFactory;
  86. this.reportWriterFactory = reportWriterFactory;
  87. }
  88. /**
  89. * 解析指定邮箱指定时间范围内的邮件
  90. *
  91. * @param mailboxInfoDTO 邮箱配置信息
  92. * @param startDate 邮件起始日期(yyyy-MM-dd HH:mm:ss)
  93. * @param endDate 邮件截止日期(yyyy-MM-dd HH:mm:ss, 为null,将解析邮件日期小于等于startDate的当天邮件)
  94. * @param emailTypes 当前任务支持的邮件类型,默认支持确认单
  95. */
  96. public void parseEmail(MailboxInfoDTO mailboxInfoDTO,
  97. Date startDate, Date endDate,
  98. List<String> folderNames, List<Integer> emailTypes) {
  99. if (CollUtil.isEmpty(emailTypes)) {
  100. emailTypes = ListUtil.of(EmailTypeConst.REPORT_LETTER_EMAIL_TYPE);
  101. }
  102. if (log.isInfoEnabled()) {
  103. log.info("开始邮件解析 -> 邮箱信息:{},开始时间:{},结束时间:{}", mailboxInfoDTO, DateUtil.format(startDate,
  104. DateConst.YYYY_MM_DD_HH_MM_SS), DateUtil.format(endDate, DateConst.YYYY_MM_DD_HH_MM_SS));
  105. }
  106. Map<String, List<EmailContentInfoDTO>> emailContentMap;
  107. try {
  108. emailContentMap = realEmail(mailboxInfoDTO, startDate, endDate, folderNames);
  109. } catch (Exception e) {
  110. log.error("采集邮件失败 -> 邮箱配置信息:{},堆栈信息:{}", mailboxInfoDTO, ExceptionUtil.stacktraceToString(e));
  111. return;
  112. }
  113. if (MapUtil.isEmpty(emailContentMap)) {
  114. log.warn("未采集到邮件 -> 邮箱配置信息:{},开始时间:{},结束时间:{}", mailboxInfoDTO,
  115. DateUtil.format(startDate, DateConst.YYYY_MM_DD_HH_MM_SS), DateUtil.format(endDate, DateConst.YYYY_MM_DD_HH_MM_SS));
  116. return;
  117. }
  118. for (Map.Entry<String, List<EmailContentInfoDTO>> emailEntry : emailContentMap.entrySet()) {
  119. List<EmailContentInfoDTO> emailContentInfoDTOList = emailEntry.getValue();
  120. if (CollUtil.isEmpty(emailContentInfoDTOList)) {
  121. log.warn("未采集到正文或附件");
  122. continue;
  123. }
  124. log.info("开始解析邮件数据 -> 邮件主题:{},邮件日期:{}", emailContentInfoDTOList.get(0).getEmailTitle(), emailContentInfoDTOList.get(0).getEmailDate());
  125. Map<EmailContentInfoDTO, List<EmailZipFileDTO>> emailZipFileMap = MapUtil.newHashMap();
  126. for (EmailContentInfoDTO emailContentInfoDTO : emailContentInfoDTOList) {
  127. // 正文不用解压附件
  128. if (emailContentInfoDTO.getFileName() != null && emailContentInfoDTO.getFileName().endsWith(".html")) {
  129. emailZipFileMap.put(emailContentInfoDTO, ListUtil.empty());
  130. continue;
  131. }
  132. try {
  133. List<EmailZipFileDTO> fundNavDTOList = parseZipEmail(emailContentInfoDTO);
  134. emailZipFileMap.put(emailContentInfoDTO, fundNavDTOList);
  135. } catch (IOException | ArchiveException e) {
  136. log.error("压缩包解压失败:{}", ExceptionUtil.stacktraceToString(e));
  137. EmailParseInfoDO fail = buildEmailParseInfo(null, mailboxInfoDTO.getAccount(), emailContentInfoDTO);
  138. fail.setFailReason("压缩包解压失败");
  139. fail.setParseStatus(EmailParseStatusConst.FAIL);
  140. fail.setEmailKey(emailEntry.getKey());
  141. this.emailParseInfoMapper.insert(fail);
  142. } catch (Exception e) {
  143. log.error("堆栈信息:{}", ExceptionUtil.stacktraceToString(e));
  144. }
  145. }
  146. Iterator<Map.Entry<EmailContentInfoDTO, List<EmailZipFileDTO>>> entryIterator = emailZipFileMap.entrySet().iterator();
  147. while (entryIterator.hasNext()) {
  148. Map.Entry<EmailContentInfoDTO, List<EmailZipFileDTO>> entry = entryIterator.next();
  149. EmailContentInfoDTO key = entry.getKey();
  150. String emailTitle = key.getEmailTitle();
  151. List<EmailZipFileDTO> dtos = entry.getValue();
  152. List<Integer> types = ListUtil.list(false);
  153. types.add(key.getEmailType());
  154. if (CollUtil.isNotEmpty(dtos)) {
  155. Iterator<EmailZipFileDTO> iterator = dtos.iterator();
  156. while (iterator.hasNext()) {
  157. EmailZipFileDTO dto = iterator.next();
  158. String filename = dto.getFilename();
  159. if (filename != null && filename.contains("复核函")) {
  160. log.warn("邮件{} 附件中的压缩文件{} 是复核函,不用解析上传。", emailTitle, filename);
  161. iterator.remove();
  162. }
  163. }
  164. List<Integer> list = dtos.stream().map(EmailZipFileDTO::getEmailType).distinct().toList();
  165. CollUtil.addAllIfNotContains(types, list);
  166. }
  167. boolean flag = false;
  168. for (Integer type : types) {
  169. if (emailTypes.contains(type)) {
  170. flag = true;
  171. break;
  172. }
  173. }
  174. if (!flag) {
  175. log.warn("当前邮件{} 的类型{} 不在支持的任务类型{} 中,不用执行解析逻辑。", key, types, emailTypes);
  176. entryIterator.remove();
  177. }
  178. }
  179. // 保存相关信息 -> 邮件信息表,邮件文件表,邮件净值表,邮件规模表,基金净值表
  180. saveRelatedTable(emailEntry.getKey(), mailboxInfoDTO.getAccount(), emailZipFileMap);
  181. log.info("结束邮件解析 -> 邮箱信息:{},开始时间:{},结束时间:{}", emailEntry.getValue(),
  182. DateUtil.format(startDate, DateConst.YYYY_MM_DD_HH_MM_SS), DateUtil.format(endDate, DateConst.YYYY_MM_DD_HH_MM_SS));
  183. }
  184. }
  185. public List<EmailZipFileDTO> parseZipEmail(EmailContentInfoDTO emailContentInfoDTO) throws Exception {
  186. List<EmailZipFileDTO> resultList = ListUtil.list(false);
  187. Integer emailType = emailContentInfoDTO.getEmailType();
  188. String filepath = emailContentInfoDTO.getFilePath();
  189. if (ExcelUtil.isZip(filepath)) {
  190. handleCompressedFiles(filepath, ".zip", emailType, resultList);
  191. } else if (ExcelUtil.isRAR(filepath)) {
  192. handleCompressedFiles(filepath, ".rar", emailType, resultList);
  193. }
  194. // 文件中的类型判断
  195. if (emailType == null || !EmailTypeConst.SUPPORT_EMAIL_TYPES.contains(emailType)) {
  196. emailType = EmailUtil.getEmailTypeBySubject(emailContentInfoDTO.getFileName(), this.getEmailType());
  197. emailContentInfoDTO.setEmailType(emailType);
  198. }
  199. return resultList;
  200. }
  201. private void handleCompressedFiles(String filepath, String extension, Integer emailType, List<EmailZipFileDTO> resultList) throws Exception {
  202. String destPath = getDestinationPath(filepath, extension);
  203. log.info("压缩包地址:{}, 解压后文件地址:{}", filepath, destPath);
  204. File destFile = new File(destPath);
  205. if (!destFile.exists()) {
  206. if (!destFile.mkdirs()) {
  207. throw new IOException("无法创建目标目录: " + destPath);
  208. }
  209. }
  210. List<String> extractedDirs;
  211. if (ExcelUtil.isZip(filepath)) {
  212. extractedDirs = ExcelUtil.extractCompressedFiles(filepath, destPath);
  213. } else if (ExcelUtil.isRAR(filepath)) {
  214. extractedDirs = ExcelUtil.extractRar5(filepath, destPath);
  215. } else {
  216. return;
  217. }
  218. for (String dir : extractedDirs) {
  219. // 如果邮件类型不满足解析条件则重新根据文件名判断
  220. if (emailType == null || !EmailTypeConst.SUPPORT_EMAIL_TYPES.contains(emailType)) {
  221. emailType = EmailUtil.getEmailTypeBySubject(dir, this.getEmailType());
  222. }
  223. File file = new File(dir);
  224. if (file.isDirectory()) {
  225. String[] subDirs = file.list();
  226. if (subDirs != null) {
  227. for (String subDir : subDirs) {
  228. resultList.add(new EmailZipFileDTO(subDir, emailType));
  229. }
  230. } else {
  231. log.warn("目录 {} 下无文件", dir);
  232. }
  233. } else {
  234. resultList.add(new EmailZipFileDTO(dir, emailType));
  235. }
  236. }
  237. }
  238. private String getDestinationPath(String filepath, String extension) {
  239. Path path = Paths.get(filepath);
  240. String fileName = path.getFileName().toString();
  241. String baseName = fileName.substring(0, fileName.length() - extension.length());
  242. return path.getParent().resolve(baseName).toString();
  243. }
  244. public void saveRelatedTable(String emailKey, String emailAddress,
  245. Map<EmailContentInfoDTO, List<EmailZipFileDTO>> emailZipFileMap) {
  246. // python 报告解析接口结果
  247. List<ParseResult<ReportData>> dataList = ListUtil.list(false);
  248. for (Map.Entry<EmailContentInfoDTO, List<EmailZipFileDTO>> entry : emailZipFileMap.entrySet()) {
  249. EmailContentInfoDTO emailContentInfoDTO = entry.getKey();
  250. if (emailContentInfoDTO.getFileName() != null && emailContentInfoDTO.getFileName().endsWith(".html")) {
  251. continue;
  252. }
  253. // 待解析文件数据处理,不支持已存在的文件重复解析
  254. List<EmailZipFileDTO> dtos = ListUtil.list(false);
  255. List<EmailZipFileDTO> zipFiles = entry.getValue();
  256. if (CollUtil.isEmpty(zipFiles)) {
  257. dtos.add(new EmailZipFileDTO(emailContentInfoDTO.getFilePath(), emailContentInfoDTO.getFileName(), emailContentInfoDTO.getEmailType()));
  258. } else {
  259. dtos.addAll(zipFiles);
  260. }
  261. String emailTitle = emailContentInfoDTO.getEmailTitle();
  262. // 数据库已存在的数据过滤
  263. Iterator<EmailZipFileDTO> iterator = dtos.iterator();
  264. while (iterator.hasNext()) {
  265. EmailZipFileDTO dto = iterator.next();
  266. Integer emailType = dto.getEmailType();
  267. String filename = dto.getFilename();
  268. int count = 0;
  269. if (Objects.equals(emailType, EmailTypeConst.REPORT_LETTER_EMAIL_TYPE)) {
  270. // 确认单
  271. count = this.emailFileInfoMapper.getLetterFilenameSuccessCount(filename);
  272. } else if (Objects.equals(emailType, EmailTypeConst.REPORT_EMAIL_TYPE)) {
  273. // 定期报告
  274. count = this.emailFileInfoMapper.getAmacFilenameSuccessCount(filename);
  275. } else if (Objects.equals(emailType, EmailTypeConst.REPORT_WEEKLY_TYPE)) {
  276. // 管理人周报
  277. count = this.emailFileInfoMapper.getWeeklyFilenameSuccessCount(filename);
  278. } else if (Objects.equals(emailType, EmailTypeConst.REPORT_OTHER_TYPE)) {
  279. // 其他报告
  280. count = this.emailFileInfoMapper.getOtherFilenameSuccessCount(filename);
  281. } else {
  282. log.info("邮件{} 类型{} 不支持解析。", emailTitle, emailType);
  283. iterator.remove();
  284. }
  285. if (count > 0) {
  286. iterator.remove();
  287. log.info("邮件{} 附件{} 已存在解析成功的记录,不用重新解析。", emailTitle, filename);
  288. }
  289. }
  290. if (CollUtil.isEmpty(dtos)) {
  291. log.info("邮件{} 所有文件都已经解析成功过,不能重复解析了", emailTitle);
  292. continue;
  293. }
  294. Integer emailId = emailContentInfoDTO.getEmailId();
  295. EmailParseInfoDO emailParseInfoDO = buildEmailParseInfo(emailId, emailAddress, emailContentInfoDTO);
  296. emailParseInfoDO.setEmailKey(emailKey);
  297. emailId = saveEmailParseInfo(emailParseInfoDO);
  298. if (emailId == null) {
  299. continue;
  300. }
  301. for (EmailZipFileDTO zipFile : dtos) {
  302. EmailFileInfoDO emailFile = saveEmailFileInfo(emailId, zipFile.getFilename(), zipFile.getFilepath());
  303. // 解析并保存报告
  304. ParseResult<ReportData> parseResult = this.parseReportAndHandleResult(emailTitle, emailFile, zipFile);
  305. dataList.add(parseResult);
  306. }
  307. String failReason = null;
  308. int emailParseStatus = EmailParseStatusConst.SUCCESS;
  309. // 报告邮件有一条失败就表示整个邮件解析失败
  310. if (CollUtil.isNotEmpty(dataList)) {
  311. // ai解析结果
  312. List<ReportData> aiParaseList = dataList.stream().map(ParseResult::getData)
  313. .filter(Objects::nonNull).filter(e -> Objects.equals(true, e.getAiParse())).toList();
  314. if (CollUtil.isNotEmpty(aiParaseList)) {
  315. for (ReportData data : aiParaseList) {
  316. this.emailFileInfoMapper.updateAiParseByFileId(data.getBaseInfo().getFileId(), data.getAiParse(), data.getAiFileId());
  317. }
  318. }
  319. long failNum = dataList.stream().filter(e -> !Objects.equals(EmailParseStatusConst.SUCCESS, e.getStatus())).count();
  320. if (failNum > 0) {
  321. emailParseStatus = EmailParseStatusConst.FAIL;
  322. failReason = dataList.stream().map(ParseResult::getMsg).collect(Collectors.joining(";"));
  323. }
  324. }
  325. emailParseInfoMapper.updateParseStatus(emailId, emailParseStatus, failReason);
  326. }
  327. }
  328. private ParseResult<ReportData> parseReportAndHandleResult(String emailTitle, EmailFileInfoDO emailFileInfo, EmailZipFileDTO zipFile) {
  329. Integer emailType = zipFile.getEmailType();
  330. String fileName = zipFile.getFilename();
  331. String filepath = zipFile.getFilepath();
  332. ParseResult<ReportData> result = new ParseResult<>();
  333. boolean reportFlag = emailType == null || !EmailTypeConst.SUPPORT_EMAIL_TYPES.contains(emailType);
  334. if (reportFlag || StrUtil.isBlank(fileName) || fileName.endsWith(".html")) {
  335. result.setStatus(ReportParseStatus.NOT_A_REPORT.getCode());
  336. result.setMsg(StrUtil.format(ReportParseStatus.NOT_A_REPORT.getMsg(), fileName));
  337. log.error(result.getMsg());
  338. return result;
  339. }
  340. // 基金代码、备案编码
  341. String registerNumber = ReportParseUtils.matchFundCode(fileName);
  342. // 类型识别---先识别季度报告,没有季度再识别年度报告,最后识别月报
  343. ReportType reportType = ReportParseUtils.matchReportType(emailType, fileName);
  344. if (reportType == null) {
  345. reportType = ReportParseUtils.matchReportType(emailType, emailTitle);
  346. if (log.isDebugEnabled()) {
  347. log.debug("报告{} 根据邮件主题{} 重新识别的类型是:{}", fileName, emailTitle, reportType);
  348. }
  349. }
  350. // 解析器--根据文件后缀获取对应解析器,解析不了就用AI来解析
  351. ReportParserFileType fileType;
  352. String fileSuffix = StrUtil.subAfter(fileName, ".", true);
  353. fileType = ReportParserFileType.getBySuffix(fileSuffix);
  354. // 不支持的格式
  355. if (fileType == null) {
  356. result.setStatus(ReportParseStatus.NO_SUPPORT_TEMPLATE.getCode());
  357. result.setMsg(StrUtil.format(ReportParseStatus.NO_SUPPORT_TEMPLATE.getMsg(), fileName));
  358. log.error(result.getMsg());
  359. return result;
  360. }
  361. // 不是定期报告的判断逻辑放在不支持的格式下面
  362. if (reportType == null) {
  363. result.setStatus(ReportParseStatus.NOT_A_REPORT.getCode());
  364. result.setMsg(StrUtil.format(ReportParseStatus.NOT_A_REPORT.getMsg(), fileName));
  365. log.error(result.getMsg());
  366. return result;
  367. }
  368. Integer fileId = emailFileInfo.getId();
  369. String aiFileId = emailFileInfo.getAiFileId();
  370. // 不支持解析的格式文件
  371. boolean notSupportFile = false;
  372. // 解析报告
  373. ReportData reportData = null;
  374. StopWatch parserWatch = new StopWatch();
  375. parserWatch.start();
  376. try {
  377. if (StrUtil.isBlank(aiFileId) && reportType != ReportType.OTHER && reportType != ReportType.WEEKLY) {
  378. ReportParserParams params = ReportParserParams.builder().fileId(fileId).filename(fileName).filepath(filepath)
  379. .registerNumber(registerNumber).reportType(reportType).build();
  380. ReportParser<ReportData> instance = this.reportParserFactory.getInstance(reportType, fileType);
  381. reportData = instance.parse(params);
  382. result.setStatus(1);
  383. result.setMsg("报告解析成功");
  384. result.setData(reportData);
  385. } else {
  386. if (reportType == ReportType.OTHER || reportType == ReportType.WEEKLY) {
  387. if (log.isInfoEnabled()) {
  388. log.info("报告{} 是周报或其他类型,直接用AI解析器解析", fileName);
  389. }
  390. } else {
  391. if (log.isInfoEnabled()) {
  392. log.info("报告{} 是已经存在ai解析记录,上传过文件{},直接跳转到AI解析器进行解析", fileName, aiFileId);
  393. }
  394. }
  395. }
  396. } catch (ReportParseException e) {
  397. log.error("解析失败:{}", StrUtil.format(e.getMsg(), fileName));
  398. result.setStatus(e.getCode());
  399. result.setMsg(StrUtil.format(e.getMsg(), fileName));
  400. if (e instanceof NotSupportReportException) {
  401. notSupportFile = true;
  402. }
  403. } catch (Exception e) {
  404. log.error("解析错误:{}", ExceptionUtil.stacktraceToString(e));
  405. result.setStatus(ReportParseStatus.PARSE_FAIL.getCode());
  406. result.setMsg(StrUtil.format(ReportParseStatus.PARSE_FAIL.getMsg(), e.getMessage()));
  407. } finally {
  408. // 如果解析结果是空的就用AI工具解析一次
  409. if (reportData == null && !notSupportFile) {
  410. if (log.isInfoEnabled()) {
  411. log.info("报告{} 开始AI解析......", fileName);
  412. }
  413. ReportParserParams params = ReportParserParams.builder().fileId(fileId).filename(fileName).filepath(filepath)
  414. .registerNumber(registerNumber).reportType(reportType).aiFileId(aiFileId).build();
  415. ReportParser<ReportData> instance = this.reportParserFactory.getInstance(reportType, ReportParserFileType.AI);
  416. try {
  417. reportData = instance.parse(params);
  418. result.setStatus(1);
  419. result.setMsg("报告解析成功--AI");
  420. result.setData(reportData);
  421. } catch (ReportParseException e) {
  422. log.error("AI解析失败:{}", StrUtil.format(e.getMsg(), fileName));
  423. result.setStatus(e.getCode());
  424. result.setMsg(StrUtil.format(e.getMsg(), fileName));
  425. } catch (Exception e) {
  426. log.error("AI解析错误:{}", ExceptionUtil.stacktraceToString(e));
  427. result.setStatus(ReportParseStatus.PARSE_FAIL.getCode());
  428. result.setMsg(StrUtil.format(ReportParseStatus.PARSE_FAIL.getMsg(), e.getMessage()));
  429. }
  430. if (log.isInfoEnabled()) {
  431. log.info("报告{} AI解析结束!", fileName);
  432. }
  433. }
  434. parserWatch.stop();
  435. if (log.isInfoEnabled()) {
  436. log.info("报告{}解析结果为{},耗时{}ms", fileName, reportData, parserWatch.getTotalTimeMillis());
  437. }
  438. }
  439. // 保存报告解析结果
  440. if (reportData != null) {
  441. StopWatch writeWatch = new StopWatch();
  442. writeWatch.start();
  443. try {
  444. ReportWriter<ReportData> instance = this.reportWriterFactory.getInstance(reportType);
  445. instance.write(reportData);
  446. } catch (Exception e) {
  447. log.error("报告{}结果保存失败\n{}", fileName, ExceptionUtil.stacktraceToString(e));
  448. } finally {
  449. writeWatch.stop();
  450. if (log.isInfoEnabled()) {
  451. log.info("报告{}解析结果保存完成,耗时{}ms", fileName, writeWatch.getTotalTimeMillis());
  452. }
  453. }
  454. }
  455. return result;
  456. }
  457. private EmailFileInfoDO saveEmailFileInfo(Integer emailId, String fileName, String filePath) {
  458. EmailFileInfoDO emailFileInfoDO = buildEmailFileInfoDO(emailId, fileName, filePath);
  459. emailFileInfoDO.setAiFileId(null);
  460. if (emailFileInfoDO.getId() != null) {
  461. emailFileInfoMapper.updateTimeById(null, new Date());
  462. return emailFileInfoDO;
  463. }
  464. emailFileInfoMapper.insert(emailFileInfoDO);
  465. return emailFileInfoDO;
  466. }
  467. private EmailFileInfoDO buildEmailFileInfoDO(Integer emailId, String fileName, String filePath) {
  468. EmailFileInfoDO emailFileInfoDO = new EmailFileInfoDO();
  469. emailFileInfoDO.setId(null);
  470. emailFileInfoDO.setEmailId(emailId);
  471. emailFileInfoDO.setFileName(fileName);
  472. emailFileInfoDO.setFilePath(filePath);
  473. emailFileInfoDO.setIsvalid(1);
  474. emailFileInfoDO.setCreatorId(0);
  475. emailFileInfoDO.setCreateTime(new Date());
  476. emailFileInfoDO.setUpdaterId(0);
  477. emailFileInfoDO.setUpdateTime(new Date());
  478. return emailFileInfoDO;
  479. }
  480. private Integer saveEmailParseInfo(EmailParseInfoDO emailParseInfoDO) {
  481. if (emailParseInfoDO == null) {
  482. return null;
  483. }
  484. // 重新邮件功能 -> 修改解析时间和更新时间
  485. if (emailParseInfoDO.getId() != null) {
  486. emailParseInfoMapper.updateParseTime(emailParseInfoDO.getId(), emailParseInfoDO.getParseDate());
  487. return emailParseInfoDO.getId();
  488. }
  489. // // 根据邮件发送人、邮件地址、邮箱日期、主题找到是否已经存在的记录(不管是否成功),已存在就不解析了
  490. // EmailParseInfoDO temp = this.emailParseInfoMapper.searchEmail(emailParseInfoDO);
  491. // if (temp != null) {
  492. // return null;
  493. // }
  494. emailParseInfoMapper.insert(emailParseInfoDO);
  495. return emailParseInfoDO.getId();
  496. }
  497. private EmailParseInfoDO buildEmailParseInfo(Integer emailId, String emailAddress, EmailContentInfoDTO emailContentInfoDTO) {
  498. EmailParseInfoDO emailParseInfoDO = new EmailParseInfoDO();
  499. emailParseInfoDO.setId(emailId);
  500. emailParseInfoDO.setSenderEmail(emailContentInfoDTO.getSenderEmail());
  501. emailParseInfoDO.setEmail(emailAddress);
  502. emailParseInfoDO.setEmailDate(DateUtil.parse(emailContentInfoDTO.getEmailDate(), DateConst.YYYY_MM_DD_HH_MM_SS));
  503. emailParseInfoDO.setParseDate(emailContentInfoDTO.getParseDate() == null ? null : DateUtil.parseDate(emailContentInfoDTO.getParseDate()));
  504. emailParseInfoDO.setEmailTitle(emailContentInfoDTO.getEmailTitle());
  505. emailParseInfoDO.setEmailType(emailContentInfoDTO.getEmailType());
  506. emailParseInfoDO.setParseStatus(EmailParseStatusConst.SUCCESS);
  507. emailParseInfoDO.setAttrSize(emailContentInfoDTO.getFileSize());
  508. emailParseInfoDO.setIsvalid(1);
  509. emailParseInfoDO.setCreatorId(0);
  510. emailParseInfoDO.setCreateTime(new Date());
  511. emailParseInfoDO.setUpdaterId(0);
  512. emailParseInfoDO.setUpdateTime(new Date());
  513. return emailParseInfoDO;
  514. }
  515. public Map<Integer, List<String>> getEmailType() {
  516. Map<Integer, List<String>> emailTypeMap = MapUtil.newHashMap(3, true);
  517. // 1.确认函
  518. emailTypeMap.put(EmailTypeConst.REPORT_LETTER_EMAIL_TYPE,
  519. ListUtil.toList(ReportType.LETTER.getPatterns()));
  520. // 2.周报
  521. emailTypeMap.put(EmailTypeConst.REPORT_WEEKLY_TYPE,
  522. ListUtil.toList(ReportType.WEEKLY.getPatterns()));
  523. // 3.定期报告的类型判断
  524. List<String> types = ListUtil.list(true);
  525. CollUtil.addAll(types, ReportType.QUARTERLY.getPatterns());
  526. CollUtil.addAll(types, ReportType.ANNUALLY.getPatterns());
  527. CollUtil.addAll(types, ReportType.MONTHLY.getPatterns());
  528. emailTypeMap.put(EmailTypeConst.REPORT_EMAIL_TYPE, types);
  529. // 4.其他
  530. emailTypeMap.put(EmailTypeConst.REPORT_OTHER_TYPE,
  531. ListUtil.toList(ReportType.OTHER.getPatterns()));
  532. return emailTypeMap;
  533. }
  534. /**
  535. * 读取邮件
  536. *
  537. * @param mailboxInfoDTO 邮箱配置信息
  538. * @param startDate 邮件起始日期
  539. * @param endDate 邮件截止日期(为null,将解析邮件日期小于等于startDate的当天邮件)
  540. * @return 读取到的邮件信息
  541. * @throws Exception 异常信息
  542. */
  543. private Map<String, List<EmailContentInfoDTO>> realEmail(MailboxInfoDTO mailboxInfoDTO,
  544. Date startDate, Date endDate,
  545. List<String> folderNames) throws Exception {
  546. if (CollUtil.isEmpty(folderNames)) {
  547. folderNames = ListUtil.toList("INBOX");
  548. }
  549. Store store = EmailUtil.getStoreNew(mailboxInfoDTO);
  550. if (store == null) {
  551. return MapUtil.newHashMap(4);
  552. }
  553. Map<String, List<EmailContentInfoDTO>> result = MapUtil.newHashMap(128);
  554. try {
  555. if (log.isInfoEnabled()) {
  556. Folder[] list = store.getDefaultFolder().list("*");
  557. List<String> names = Arrays.stream(list).map(Folder::getFullName).toList();
  558. log.info("获取所有邮箱文件夹:{}", names);
  559. }
  560. for (String folderName : folderNames) {
  561. try {
  562. Map<String, List<EmailContentInfoDTO>> temp = this.getFolderEmail(mailboxInfoDTO,
  563. startDate, endDate, store, folderName);
  564. if (MapUtil.isNotEmpty(temp)) {
  565. result.putAll(temp);
  566. }
  567. } catch (Exception e) {
  568. log.warn("文件夹{} 邮件获取失败:{}", folderName, ExceptionUtil.stacktraceToString(e));
  569. }
  570. }
  571. } catch (Exception e) {
  572. log.error("邮件获取失败:{}", ExceptionUtil.stacktraceToString(e));
  573. } finally {
  574. store.close();
  575. }
  576. return result;
  577. }
  578. private Map<String, List<EmailContentInfoDTO>> getFolderEmail(MailboxInfoDTO mailboxInfoDTO,
  579. Date startDate, Date endDate,
  580. Store store, String folderName) throws MessagingException {
  581. // 默认读取收件箱的邮件
  582. Folder folder = store.getFolder(folderName);
  583. folder.open(Folder.READ_ONLY);
  584. Message[] messages = getEmailMessage(folder, mailboxInfoDTO.getProtocol(), startDate);
  585. if (messages == null || messages.length == 0) {
  586. log.warn("{} 获取不到邮件 -> 邮箱信息:{},开始时间:{},结束时间:{}", folderName, mailboxInfoDTO, startDate, endDate);
  587. return MapUtil.newHashMap();
  588. }
  589. Map<String, List<EmailContentInfoDTO>> emailMessageMap = MapUtil.newHashMap();
  590. for (Message message : messages) {
  591. long start = System.currentTimeMillis();
  592. List<EmailContentInfoDTO> emailContentInfoDTOList = CollUtil.newArrayList();
  593. String uuidKey = UUID.randomUUID().toString().replaceAll("-", "");
  594. Integer emailType;
  595. String senderEmail;
  596. String emailTitle = null;
  597. try {
  598. emailTitle = message.getSubject();
  599. Date emailDate = message.getSentDate();
  600. String emailDateStr = DateUtil.format(emailDate, DateConst.YYYY_MM_DD_HH_MM_SS);
  601. if (log.isInfoEnabled()) {
  602. log.info("{} 邮件{} 数据获取中,邮件时间:{}", folderName, emailTitle, emailDateStr);
  603. }
  604. boolean isNotParseConditionSatisfied = emailDate == null
  605. || (endDate != null && emailDate.compareTo(endDate) > 0)
  606. || (startDate != null && emailDate.compareTo(startDate) < 0);
  607. if (isNotParseConditionSatisfied) {
  608. log.warn("{} 邮件{} 没有日期{} 或者 邮件日期不在区间内【{} ~ {}】", folderName, emailTitle, emailDate, startDate, endDate);
  609. continue;
  610. }
  611. senderEmail = getSenderEmail(message);
  612. emailType = EmailUtil.getEmailTypeBySubject(emailTitle, this.getEmailType());
  613. if (emailType == null) {
  614. log.warn("{} 邮件不满足解析条件 -> 邮件主题:{},邮件日期:{}", folderName, emailTitle, emailDateStr);
  615. continue;
  616. }
  617. if (log.isInfoEnabled()) {
  618. log.info("{} 邮件{} 基本信息获取完成,开始下载附件!邮件日期:{}", folderName, emailTitle, emailDateStr);
  619. }
  620. Object content = message.getContent();
  621. if (content instanceof Multipart multipart) {
  622. this.reMultipart(mailboxInfoDTO.getAccount(), emailTitle, emailDate, multipart, emailContentInfoDTOList);
  623. } else if (content instanceof Part part) {
  624. this.rePart(mailboxInfoDTO.getAccount(), emailTitle, emailDate, part, emailContentInfoDTOList);
  625. } else {
  626. log.warn("{} 不支持的邮件数据 {}", folderName, emailTitle);
  627. }
  628. if (CollUtil.isNotEmpty(emailContentInfoDTOList)) {
  629. emailContentInfoDTOList.forEach(e -> {
  630. e.setEmailType(emailType);
  631. e.setSenderEmail(senderEmail);
  632. });
  633. emailMessageMap.put(uuidKey, emailContentInfoDTOList);
  634. }
  635. if (log.isInfoEnabled() && emailTitle != null) {
  636. log.info("{} 邮件{} 下载完成,总计耗时{} ms,文件内容如下\n {}", folderName,
  637. emailTitle, System.currentTimeMillis() - start, emailContentInfoDTOList);
  638. }
  639. } catch (Exception e) {
  640. log.error("{} 获取邮箱的邮件{} 报错,堆栈信息:{}", folderName, emailTitle, ExceptionUtil.stacktraceToString(e));
  641. }
  642. }
  643. folder.close(false);
  644. return emailMessageMap;
  645. }
  646. private void rePart(String account, String subject, Date sendDate, Part part,
  647. List<EmailContentInfoDTO> emailContentInfoDTOList) throws Exception {
  648. String fileName = EmailUtil.decodeFileName(part);
  649. if (StrUtil.isBlank(fileName)) {
  650. log.warn("邮件{} 附件文件名是空的,不做下载!", subject);
  651. return;
  652. }
  653. if (fileName.contains("=?")) {
  654. fileName = MimeUtility.decodeText(fileName);
  655. }
  656. String disposition = part.getDisposition();
  657. String contentType = part.getContentType();
  658. boolean isAttachment = Part.ATTACHMENT.equalsIgnoreCase(disposition)
  659. || (contentType != null && attachmentMimePrefixes.stream().anyMatch(prefix ->
  660. StrUtil.startWithIgnoreCase(contentType, prefix)
  661. ));
  662. if (!isAttachment) {
  663. log.warn("邮件 {} 未检测到pdf/zip/rar类型的附件 (fileName={}, disposition={}, contentType={})",
  664. subject, fileName, disposition, contentType);
  665. return;
  666. }
  667. String emailDate = DateUtil.format(sendDate, DateConst.YYYYMMDDHHMMSS24);
  668. String emailDateStr = DateUtil.format(sendDate, DateConst.YYYYMMDD);
  669. String filePath = path + File.separator + account + File.separator + emailDateStr + File.separator;
  670. String realPath = filePath + emailDate + fileName;
  671. File saveFile = cn.hutool.core.io.FileUtil.file(realPath);
  672. if (!saveFile.exists()) {
  673. if (!saveFile.getParentFile().exists()) {
  674. boolean mkdirs = saveFile.getParentFile().mkdirs();
  675. if (!mkdirs) {
  676. log.warn("file path mkdir failed.");
  677. }
  678. }
  679. FileUtil.saveFile(saveFile, part);
  680. } else {
  681. cn.hutool.core.io.FileUtil.del(saveFile);
  682. FileUtil.saveFile(saveFile, part);
  683. }
  684. EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
  685. emailContentInfoDTO.setFileName(fileName);
  686. emailContentInfoDTO.setFileSize(part.getSize());
  687. emailContentInfoDTO.setFilePath(saveFile.getAbsolutePath());
  688. emailContentInfoDTO.setEmailAddress(account);
  689. emailContentInfoDTO.setEmailTitle(subject);
  690. emailContentInfoDTO.setEmailDate(DateUtil.format(sendDate, DateConst.YYYY_MM_DD_HH_MM_SS));
  691. emailContentInfoDTOList.add(emailContentInfoDTO);
  692. }
  693. private void reMultipart(String account, String subject, Date emailDate, Multipart multipart,
  694. List<EmailContentInfoDTO> emailContentInfoDTOList) throws Exception {
  695. for (int i = 0; i < multipart.getCount(); i++) {
  696. Part bodyPart = multipart.getBodyPart(i);
  697. Object content = bodyPart.getContent();
  698. if (content instanceof String) {
  699. if (log.isDebugEnabled()) {
  700. log.debug("邮件{} 获取的正文不做解析,内容是 {}", subject, content);
  701. }
  702. continue;
  703. }
  704. if (content instanceof Multipart mp) {
  705. this.reMultipart(account, subject, emailDate, mp, emailContentInfoDTOList);
  706. } else {
  707. this.rePart(account, subject, emailDate, bodyPart, emailContentInfoDTOList);
  708. }
  709. }
  710. }
  711. private String getSenderEmail(Message message) {
  712. Address[] senderAddress;
  713. try {
  714. senderAddress = message.getFrom();
  715. if (senderAddress == null || senderAddress.length == 0) {
  716. return null;
  717. }
  718. // 此时的address是含有编码(MIME编码方式)后的文本和实际的邮件地址
  719. String address = "";
  720. for (Address from : senderAddress) {
  721. if (StrUtil.isNotBlank(from.toString())) {
  722. address = from.toString();
  723. break;
  724. }
  725. }
  726. // 正则表达式匹配邮件地址
  727. Pattern pattern = Pattern.compile("<(\\S+)>");
  728. Matcher matcher = pattern.matcher(address);
  729. if (matcher.find()) {
  730. return matcher.group(1);
  731. }
  732. // //说明匹配不到,直接获取sender
  733. // Address sender = message.getSender();
  734. // if (sender == null) {
  735. // return address;
  736. // }
  737. // String senderEmail = sender.toString();
  738. // log.info("senderEmail:" + senderEmail + "====================");
  739. // if (senderEmail.contains("<") && senderEmail.contains(">") && senderEmail.indexOf("<") < senderEmail.indexOf(">")) {
  740. // senderEmail = senderEmail.substring(senderEmail.indexOf("<") + 1, senderEmail.length() - 1);
  741. // }
  742. // return senderEmail;
  743. } catch (MessagingException e) {
  744. log.error(e.getMessage(), e);
  745. }
  746. return null;
  747. }
  748. private Message[] getEmailMessage(Folder folder, String protocol, Date startDate) {
  749. try {
  750. if (protocol.contains("imap")) {
  751. // 获取邮件日期大于等于startDate的邮件(搜索条件只支持按天)
  752. SearchTerm startDateTerm = new ReceivedDateTerm(ComparisonTerm.GE, startDate);
  753. return folder.search(startDateTerm);
  754. } else {
  755. return folder.getMessages();
  756. }
  757. } catch (MessagingException e) {
  758. throw new RuntimeException(e);
  759. }
  760. }
  761. }