EmailParseService.java 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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.io.FileUtil;
  7. import cn.hutool.core.map.MapUtil;
  8. import cn.hutool.core.util.IdUtil;
  9. import cn.hutool.core.util.StrUtil;
  10. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  11. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  12. import com.smppw.modaq.application.components.OCRReportParser;
  13. import com.smppw.modaq.application.components.ReportParseUtils;
  14. import com.smppw.modaq.application.components.report.parser.ReportParser;
  15. import com.smppw.modaq.application.components.report.parser.ReportParserFactory;
  16. import com.smppw.modaq.application.components.report.writer.ReportWriter;
  17. import com.smppw.modaq.application.components.report.writer.ReportWriterFactory;
  18. import com.smppw.modaq.application.util.EmailUtil;
  19. import com.smppw.modaq.common.conts.Constants;
  20. import com.smppw.modaq.common.conts.DateConst;
  21. import com.smppw.modaq.common.conts.EmailParseStatusConst;
  22. import com.smppw.modaq.common.conts.EmailTypeConst;
  23. import com.smppw.modaq.common.enums.ReportMonthlyType;
  24. import com.smppw.modaq.common.enums.ReportParseStatus;
  25. import com.smppw.modaq.common.enums.ReportParserFileType;
  26. import com.smppw.modaq.common.enums.ReportType;
  27. import com.smppw.modaq.common.exception.NotSupportReportException;
  28. import com.smppw.modaq.common.exception.ReportParseException;
  29. import com.smppw.modaq.domain.dto.*;
  30. import com.smppw.modaq.domain.dto.report.*;
  31. import com.smppw.modaq.domain.dto.report.ocr.OCRLetterParseData;
  32. import com.smppw.modaq.domain.dto.report.ocr.OCRParseData;
  33. import com.smppw.modaq.domain.entity.EmailFileInfoDO;
  34. import com.smppw.modaq.domain.entity.EmailParseInfoDO;
  35. import com.smppw.modaq.domain.entity.TgEmailConfigDO;
  36. import com.smppw.modaq.domain.mapper.EmailFileInfoMapper;
  37. import com.smppw.modaq.domain.mapper.EmailParseInfoMapper;
  38. import com.smppw.modaq.domain.mapper.TgEmailConfigMapper;
  39. import com.smppw.modaq.infrastructure.util.ArchiveUtil;
  40. import com.smppw.modaq.infrastructure.util.ConvertUtil;
  41. import com.smppw.modaq.infrastructure.util.PdfUtil;
  42. import jakarta.mail.*;
  43. import jakarta.mail.internet.MimeUtility;
  44. import jakarta.mail.search.ComparisonTerm;
  45. import jakarta.mail.search.ReceivedDateTerm;
  46. import jakarta.mail.search.SearchTerm;
  47. import org.slf4j.Logger;
  48. import org.slf4j.LoggerFactory;
  49. import org.springframework.beans.factory.annotation.Value;
  50. import org.springframework.http.MediaType;
  51. import org.springframework.stereotype.Service;
  52. import org.springframework.util.StopWatch;
  53. import java.io.File;
  54. import java.io.IOException;
  55. import java.io.InputStream;
  56. import java.nio.file.Files;
  57. import java.util.*;
  58. import java.util.regex.Matcher;
  59. import java.util.regex.Pattern;
  60. import java.util.stream.Collectors;
  61. /**
  62. * @author mozuwen
  63. * @date 2024-09-04
  64. * @description 邮件解析服务
  65. */
  66. @Service
  67. public class EmailParseService {
  68. // public static final int stepSize = 10000;
  69. private static final Logger log = LoggerFactory.getLogger(EmailParseService.class);
  70. // 常量定义:统一管理关键词
  71. private static final Set<String> AMAC_KEYWORDS = Set.of("协会", "信披");
  72. private static final Set<String> EXCLUDE_PATH_KEYWORDS = Set.of("公司及协会版", "公司和协会版");
  73. // 扩展支持的 MIME 类型
  74. private static final Set<String> attachmentMimePrefixes = Set.of(
  75. "application/pdf",
  76. "application/zip",
  77. "application/x-zip-compressed",
  78. "application/rar",
  79. "application/x-rar-compressed",
  80. "application/octet-stream"
  81. // 按需添加其他类型...
  82. );
  83. private static final List<String> TG_EMAIL_LIST = ListUtil.list(false);
  84. private final TgEmailConfigMapper tgEmailConfigMapper;
  85. private final EmailParseInfoMapper emailParseInfoMapper;
  86. private final EmailFileInfoMapper emailFileInfoMapper;
  87. /* 报告解析和入库的方法 */
  88. private final ReportParserFactory reportParserFactory;
  89. private final ReportWriterFactory reportWriterFactory;
  90. @Value("${email.file.path}")
  91. private String path;
  92. @Value("${email.report.ocr-parser-url}")
  93. private String ocrParserUrl;
  94. @Value("${email.read-write-seen:true}")
  95. private boolean readWriteSeen;
  96. public EmailParseService(TgEmailConfigMapper tgEmailConfigMapper,
  97. EmailParseInfoMapper emailParseInfoMapper,
  98. EmailFileInfoMapper emailFileInfoMapper,
  99. ReportParserFactory reportParserFactory,
  100. ReportWriterFactory reportWriterFactory) {
  101. this.tgEmailConfigMapper = tgEmailConfigMapper;
  102. this.emailParseInfoMapper = emailParseInfoMapper;
  103. this.emailFileInfoMapper = emailFileInfoMapper;
  104. this.reportParserFactory = reportParserFactory;
  105. this.reportWriterFactory = reportWriterFactory;
  106. this.init();
  107. }
  108. public void init() {
  109. LambdaQueryWrapper<TgEmailConfigDO> wrapper = Wrappers.lambdaQuery(TgEmailConfigDO.class);
  110. List<TgEmailConfigDO> dataList = this.tgEmailConfigMapper.selectList(wrapper);
  111. for (TgEmailConfigDO temp : dataList) {
  112. TG_EMAIL_LIST.add(temp.getEmail());
  113. }
  114. }
  115. /**
  116. * 解析指定邮箱指定时间范围内的邮件
  117. *
  118. * @param mailboxInfoDTO 邮箱配置信息
  119. * @param startDate 邮件起始日期(yyyy-MM-dd HH:mm:ss)
  120. * @param endDate 邮件截止日期(yyyy-MM-dd HH:mm:ss, 为null,将解析邮件日期小于等于startDate的当天邮件)
  121. * @param emailTypes 当前任务支持的邮件类型,默认支持确认单
  122. */
  123. public void parseEmail(MailboxInfoDTO mailboxInfoDTO,
  124. Date startDate, Date endDate,
  125. List<String> folderNames,
  126. List<Integer> emailTypes) {
  127. if (CollUtil.isEmpty(emailTypes)) {
  128. emailTypes = ListUtil.of(EmailTypeConst.REPORT_LETTER_EMAIL_TYPE);
  129. }
  130. if (log.isInfoEnabled()) {
  131. log.info("开始邮件解析 -> 邮箱信息:{},开始时间:{},结束时间:{}", mailboxInfoDTO,
  132. DateUtil.formatDateTime(startDate), DateUtil.formatDateTime(endDate));
  133. }
  134. Map<String, List<EmailContentInfoDTO>> emailContentMap;
  135. try {
  136. emailContentMap = this.realEmail(mailboxInfoDTO, startDate, endDate, folderNames);
  137. } catch (Exception e) {
  138. log.error("采集邮件失败 -> 邮箱配置信息:{},堆栈信息:{}", mailboxInfoDTO, ExceptionUtil.stacktraceToString(e));
  139. return;
  140. }
  141. if (MapUtil.isEmpty(emailContentMap)) {
  142. log.warn("未采集到邮件 -> 邮箱配置信息:{},开始时间:{},结束时间:{}", mailboxInfoDTO,
  143. DateUtil.formatDateTime(startDate), DateUtil.formatDateTime(endDate));
  144. return;
  145. }
  146. for (Map.Entry<String, List<EmailContentInfoDTO>> emailEntry : emailContentMap.entrySet()) {
  147. List<EmailContentInfoDTO> dtoList = emailEntry.getValue();
  148. if (CollUtil.isEmpty(dtoList)) {
  149. log.warn("未采集到正文或附件");
  150. continue;
  151. }
  152. EmailContentInfoDTO dto = dtoList.get(0);
  153. String emailTitle = dto.getEmailTitle();
  154. if (log.isInfoEnabled()) {
  155. log.info("开始解析邮件数据 -> 邮件主题:{},邮件日期:{}", emailTitle, dto.getEmailDate());
  156. }
  157. Long totalSize = dtoList.stream().map(EmailContentInfoDTO::getFileSize).reduce(0L, Long::sum);
  158. String errMsg = null;
  159. int status = 1;
  160. List<EmailZipFileDTO> emailFileList = ListUtil.list(false);
  161. EmailInfoDTO emailInfo = new EmailInfoDTO(dto, emailFileList);
  162. if (dto.getEmailContent() != null && dto.getEmailContent().contains("超大附件列表")) {
  163. status = 0;
  164. errMsg = "邮件中存在超大附件,需要手动处理该邮件";
  165. } else {
  166. for (EmailContentInfoDTO emailDto : dtoList) {
  167. // 正文不用解压附件
  168. if (emailDto.getFileName() != null && emailDto.getFileName().endsWith(Constants.FILE_HTML)) {
  169. continue;
  170. }
  171. try {
  172. emailFileList.addAll(this.parseZipEmail(emailDto));
  173. } catch (IOException e) {
  174. log.error("邮件{} 压缩包解压失败:{}", emailTitle, ExceptionUtil.stacktraceToString(e));
  175. EmailZipFileDTO zipFileDTO = new EmailZipFileDTO(emailTitle, emailDto);
  176. zipFileDTO.setParseStatus(0);
  177. zipFileDTO.setFailReason("压缩包解压失败");
  178. emailFileList.add(zipFileDTO);
  179. } catch (Exception e) {
  180. log.error("邮件{} 堆栈信息:{}", emailTitle, ExceptionUtil.stacktraceToString(e));
  181. }
  182. }
  183. // 重新判断类型
  184. this.recheckEmailType(emailTitle, emailFileList);
  185. Iterator<EmailZipFileDTO> entryIterator = emailFileList.iterator();
  186. while (entryIterator.hasNext()) {
  187. EmailZipFileDTO entry = entryIterator.next();
  188. if (!emailTypes.contains(entry.getEmailType())) {
  189. log.warn("当前邮件{} 中的报告{} 的类型{} 不在支持的任务类型{} 中,不用执行解析逻辑。",
  190. entry.getEmailTitle(), entry.getFilename(), entry.getEmailType(), emailTypes);
  191. entryIterator.remove();
  192. }
  193. ReportParserFileType fileType = ReportParserFileType.getBySuffix(entry.getExtName());
  194. if (fileType == null) {
  195. log.warn("当前邮件{} 中的文件{} 是不支持的文件格式{} 中,不用执行解析逻辑。",
  196. entry.getEmailTitle(), entry.getFilepath(), entry.getExtName());
  197. entryIterator.remove();
  198. }
  199. }
  200. }
  201. // 保存邮件信息
  202. EmailParseInfoDO emailDo = this.buildEmailParseInfo(mailboxInfoDTO.getAccount(), emailInfo, totalSize);
  203. emailDo.setEmailKey(emailEntry.getKey());
  204. emailDo.setParseStatus(status);
  205. emailDo.setFailReason(errMsg);
  206. Integer emailId = this.saveEmailParseInfo(emailDo);
  207. // 保存附件(解压后的)
  208. for (EmailZipFileDTO zipFile : emailFileList) {
  209. EmailFileInfoDO emailFile = this.saveEmailFileInfo(emailId, zipFile);
  210. if (!Objects.equals(1, zipFile.getParseStatus()) || StrUtil.isNotBlank(zipFile.getFailReason())) {
  211. emailFile.setParseStatus(zipFile.getParseStatus());
  212. emailFile.setFailReason(zipFile.getFailReason());
  213. }
  214. zipFile.setFileId(emailFile.getId());
  215. }
  216. if (CollUtil.isNotEmpty(emailFileList)) {
  217. // 保存相关信息 -> 邮件信息表,邮件文件表,邮件净值表,邮件规模表,基金净值表
  218. this.saveRelatedTable(emailId, emailInfo);
  219. log.info("结束邮件解析 -> 邮箱信息:{},开始时间:{},结束时间:{}", emailEntry.getValue(),
  220. DateUtil.formatDateTime(startDate), DateUtil.formatDateTime(endDate));
  221. }
  222. }
  223. }
  224. /**
  225. * 解压压缩包,如果不是压缩包需转换
  226. *
  227. * @param emailContentInfoDTO 邮件信息
  228. * @return 解压后的文件列表
  229. * @throws IOException /
  230. */
  231. public List<EmailZipFileDTO> parseZipEmail(EmailContentInfoDTO emailContentInfoDTO) throws IOException {
  232. List<EmailZipFileDTO> resultList = ListUtil.list(false);
  233. Integer emailType = emailContentInfoDTO.getEmailType();
  234. String filepath = emailContentInfoDTO.getFilePath();
  235. String emailTitle = emailContentInfoDTO.getEmailTitle();
  236. if (ArchiveUtil.isArchive(filepath)) {
  237. this.handleCompressedFiles(emailTitle, filepath, emailType, resultList);
  238. } else {
  239. // 不是压缩包时
  240. EmailZipFileDTO dto = new EmailZipFileDTO(emailTitle, emailContentInfoDTO);
  241. resultList.add(dto);
  242. }
  243. // 文件中的类型判断
  244. if (emailType == null || !EmailTypeConst.SUPPORT_NO_OTHER_TYPES.contains(emailType)) {
  245. emailType = EmailUtil.getEmailTypeBySubject(emailContentInfoDTO.getFileName());
  246. emailContentInfoDTO.setEmailType(emailType);
  247. }
  248. if (CollUtil.isNotEmpty(resultList)) {
  249. for (EmailZipFileDTO dto : resultList) {
  250. dto.setEmailType(emailType);
  251. }
  252. }
  253. return resultList;
  254. }
  255. /**
  256. * 解压压缩包并把压缩包里面的所有文件放在resultList中
  257. *
  258. * @param emailTitle 邮件主题
  259. * @param filepath 压缩包路径
  260. * @param emailType 邮件解析类型
  261. * @param resultList 解压结果列表
  262. * @throws IOException /
  263. */
  264. private void handleCompressedFiles(String emailTitle,
  265. String filepath,
  266. Integer emailType,
  267. List<EmailZipFileDTO> resultList) throws IOException {
  268. if (!ArchiveUtil.isArchive(filepath)) {
  269. return;
  270. }
  271. String output = filepath.replaceAll("original", "archive");
  272. String destPath = FileUtil.getParent(output, 1) + File.separator + FileUtil.mainName(output);
  273. File destFile = FileUtil.file(destPath);
  274. if (!destFile.exists()) {
  275. if (!destFile.mkdirs()) {
  276. throw new IOException("无法创建目标目录: " + destPath);
  277. }
  278. }
  279. List<String> extractedDirs;
  280. if (ArchiveUtil.isZip(filepath)) {
  281. extractedDirs = ArchiveUtil.extractCompressedFiles(filepath, destPath);
  282. } else if (ArchiveUtil.isRAR(filepath) || ArchiveUtil.is7z(filepath)) {
  283. // 7z和rar压缩包解压
  284. extractedDirs = ArchiveUtil.extractRar5(filepath, destPath);
  285. } else {
  286. return;
  287. }
  288. for (String dir : extractedDirs) {
  289. // 如果邮件类型不满足解析条件则重新根据文件名判断
  290. if (emailType == null || !EmailTypeConst.SUPPORT_EMAIL_TYPES.contains(emailType)) {
  291. emailType = EmailUtil.getEmailTypeBySubject(dir);
  292. }
  293. File file = new File(dir);
  294. if (file.isDirectory()) {
  295. String[] subDirs = file.list();
  296. if (subDirs != null) {
  297. for (String subDir : subDirs) {
  298. resultList.add(new EmailZipFileDTO(emailTitle, subDir, emailType));
  299. }
  300. } else {
  301. log.warn("目录 {} 下无文件", dir);
  302. }
  303. } else {
  304. resultList.add(new EmailZipFileDTO(emailTitle, dir, emailType));
  305. }
  306. }
  307. }
  308. /**
  309. * 邮件附件解析并保存结果数据
  310. *
  311. * @param emailId 邮件数据ID
  312. * @param emailInfo 邮件信息
  313. */
  314. public void saveRelatedTable(Integer emailId, EmailInfoDTO emailInfo) {
  315. // 解析并保存数据
  316. List<ParseResult<ReportData>> dataList = ListUtil.list(true);
  317. this.parseAndUpdateResult(emailId, emailInfo, dataList);
  318. }
  319. private List<EmailFileInfoDO> buildEmailFileInfo(List<ParseResult<ReportData>> dataList) {
  320. List<EmailFileInfoDO> entityList = ListUtil.list(false);
  321. for (ParseResult<ReportData> result : dataList) {
  322. EmailFileInfoDO entity = new EmailFileInfoDO();
  323. entity.setId(result.getData().getBaseInfo().getFileId());
  324. entity.setParseStatus(result.getStatus());
  325. entity.setFailReason(result.getMsg());
  326. entity.setAiParse(result.getData().getAiParse());
  327. entityList.add(entity);
  328. }
  329. return entityList;
  330. }
  331. /**
  332. * 上传文件解析并返回解析状态
  333. *
  334. * @param params 上传文件路径
  335. * @return /
  336. */
  337. public List<UploadReportResult> uploadReportResults(UploadReportParams params) {
  338. String emailTitle = params.getTitle();
  339. List<UploadReportParams.ReportInfo> reportInfos = params.getReportInfos();
  340. List<EmailZipFileDTO> dtos = ListUtil.list(false);
  341. for (UploadReportParams.ReportInfo e : reportInfos) {
  342. EmailZipFileDTO zipFileDTO = new EmailZipFileDTO(emailTitle, e);
  343. String reportPath = e.getReportPath();
  344. if (ArchiveUtil.isArchive(reportPath)) {
  345. try {
  346. this.handleCompressedFiles(emailTitle, reportPath, e.getReportType(), dtos);
  347. } catch (Exception ex) {
  348. log.warn("报告{} 压缩包解压失败:{}", reportPath, ExceptionUtil.stacktraceToString(ex));
  349. zipFileDTO.setParseStatus(0);
  350. zipFileDTO.setFailReason("压缩包解压失败");
  351. dtos.add(zipFileDTO);
  352. }
  353. } else {
  354. dtos.add(zipFileDTO);
  355. }
  356. }
  357. // 重新判断类型
  358. this.recheckEmailType(emailTitle, dtos);
  359. EmailInfoDTO emailInfo = new EmailInfoDTO(emailTitle, dtos);
  360. Long totalSize = dtos.stream().map(EmailZipFileDTO::getFileSize).reduce(0L, Long::sum);
  361. EmailParseInfoDO emailDo = this.buildEmailParseInfo("upload", emailInfo, totalSize);
  362. Integer emailId = this.saveEmailParseInfo(emailDo);
  363. for (EmailZipFileDTO zipFile : dtos) {
  364. EmailFileInfoDO emailFile = this.saveEmailFileInfo(emailId, zipFile);
  365. zipFile.setFileId(emailFile.getId());
  366. }
  367. // 解析并处理解析结果
  368. List<ParseResult<ReportData>> dataList = ListUtil.list(false);
  369. this.parseAndUpdateResult(emailId, emailInfo, dataList);
  370. // 解析结果转换
  371. List<UploadReportResult> resultList = ListUtil.list(false);
  372. for (ParseResult<ReportData> result : dataList) {
  373. ReportData data = result.getData();
  374. resultList.add(new UploadReportResult(data.getBaseInfo().getFileId(),
  375. data.getBaseInfo().getReportName(), result.getStatus(), result.getMsg()));
  376. }
  377. return resultList;
  378. }
  379. private void parseAndUpdateResult(Integer emailId,
  380. EmailInfoDTO emailInfo,
  381. List<ParseResult<ReportData>> dataList) {
  382. this.parseResults(emailInfo, dataList);
  383. String failReason = null;
  384. int emailParseStatus = EmailParseStatusConst.SUCCESS;
  385. // 报告邮件有一条失败就表示整个邮件解析失败
  386. if (CollUtil.isNotEmpty(dataList)) {
  387. List<EmailFileInfoDO> entityList = this.buildEmailFileInfo(dataList);
  388. this.emailFileInfoMapper.batchUpdateByFileId(entityList);
  389. long failNum = dataList.stream().filter(e -> !Objects.equals(EmailParseStatusConst.SUCCESS, e.getStatus())).count();
  390. if (failNum > 0) {
  391. emailParseStatus = EmailParseStatusConst.FAIL;
  392. failReason = dataList.stream().map(ParseResult::getMsg).collect(Collectors.joining(";"));
  393. }
  394. }
  395. this.emailParseInfoMapper.updateParseStatus(emailId, emailParseStatus, failReason);
  396. }
  397. /**
  398. * 重新校验邮件附件的类型(用邮件主题+附件名称)
  399. *
  400. * @param emailTitle 邮件主题
  401. * @param dtos 所有附件
  402. */
  403. private void recheckEmailType(String emailTitle, List<EmailZipFileDTO> dtos) {
  404. for (EmailZipFileDTO emailFile : dtos) {
  405. if (EmailTypeConst.SUPPORT_NO_OTHER_TYPES.contains(emailFile.getEmailType())
  406. || !Objects.equals(1, emailFile.getParseStatus())) {
  407. continue;
  408. }
  409. Integer type = EmailUtil.getEmailTypeBySubject(emailTitle + emailFile.getFilename());
  410. // 特殊月报
  411. if ((Objects.equals(EmailTypeConst.NAV_EMAIL_TYPE, type) || Objects.equals(EmailTypeConst.REPORT_OTHER_TYPE, type))
  412. && ReportParseUtils.containsAny(emailTitle, ReportParseUtils.MONTHLY_REPORT_KEYWORDS)) {
  413. type = EmailTypeConst.REPORT_EMAIL_TYPE;
  414. }
  415. if (EmailTypeConst.SUPPORT_EMAIL_TYPES.contains(type)) {
  416. emailFile.setEmailType(type);
  417. }
  418. }
  419. }
  420. /**
  421. * 邮件信息前置处理,在解析操作执行之前的过滤逻辑和校验逻辑。返回所有附件大小汇总
  422. *
  423. * @param emailTitle 邮件信息(包含所有解压后的文件)
  424. * @param dtos 邮件信息(包含所有解压后的文件)
  425. */
  426. private void checkEmailFileInfo(String emailTitle, List<EmailZipFileDTO> dtos) {
  427. // 如果压缩包里面既有pdf又有其他格式的文件,说明其他格式的文件是不需要解析的
  428. List<String> exts = dtos.stream().map(EmailZipFileDTO::getExtName).distinct().toList();
  429. if (exts.contains(Constants.FILE_PDF) && exts.size() > 1) {
  430. dtos.removeIf(e -> !Objects.equals(Constants.FILE_PDF, e.getExtName()));
  431. }
  432. // 移除逻辑
  433. Iterator<EmailZipFileDTO> removeIterator = dtos.iterator();
  434. while (removeIterator.hasNext()) {
  435. EmailZipFileDTO dto = removeIterator.next();
  436. String filename = dto.getFilename();
  437. // 删除复核函或基金合同
  438. if (filename.contains("复核函") || (filename.contains("基金合同") && !filename.contains("合同变更"))) {
  439. log.warn("邮件{} 中的报告{} 是复核函或基金合同,不用解析上传。", emailTitle, filename);
  440. removeIterator.remove();
  441. }
  442. // 不支持的类型
  443. Integer type = dto.getEmailType();
  444. if (!EmailTypeConst.SUPPORT_EMAIL_TYPES.contains(type)) {
  445. log.info("邮件{} 类型{} 不支持解析。", emailTitle, type);
  446. removeIterator.remove();
  447. }
  448. }
  449. // 数据库已存在的数据过滤(邮件主题+报告名称+附件大小,压缩包文件大小汇总)
  450. long totalSize = dtos.stream().map(EmailZipFileDTO::getFileSize).reduce(0L, Long::sum);
  451. Iterator<EmailZipFileDTO> iterator = dtos.iterator();
  452. while (iterator.hasNext()) {
  453. EmailZipFileDTO dto = iterator.next();
  454. String filename = dto.getFilename();
  455. Integer type = dto.getEmailType();
  456. int count = 0;
  457. if (Objects.equals(type, EmailTypeConst.REPORT_LETTER_EMAIL_TYPE)) {
  458. // 确认单
  459. count = this.emailFileInfoMapper.getLetterFilenameSuccessCount(emailTitle, filename);
  460. } else if (Objects.equals(type, EmailTypeConst.REPORT_EMAIL_TYPE)) {
  461. // 定期报告
  462. count = this.emailFileInfoMapper.getAmacFilenameSuccessCount(emailTitle, filename, totalSize);
  463. } else if (Objects.equals(type, EmailTypeConst.REPORT_WEEKLY_TYPE)) {
  464. // 管理人周报
  465. count = this.emailFileInfoMapper.getWeeklyFilenameSuccessCount(emailTitle, filename, totalSize);
  466. } else if (Objects.equals(type, EmailTypeConst.REPORT_OTHER_TYPE)) {
  467. // 其他报告
  468. count = this.emailFileInfoMapper.getOtherFilenameSuccessCount(emailTitle, filename, totalSize);
  469. }
  470. if (count > 0) {
  471. iterator.remove();
  472. log.info("邮件{} 报告{} 已存在解析成功的记录,不用重新解析。", emailTitle, filename);
  473. }
  474. }
  475. if (CollUtil.isEmpty(dtos)) {
  476. log.info("邮件{} 经校验没有需要解析的报告文件。", emailTitle);
  477. return;
  478. }
  479. if (log.isInfoEnabled()) {
  480. log.info("邮件{} 还有报告待解析:\n{}", emailTitle, dtos);
  481. }
  482. }
  483. /**
  484. * 邮件信息保存+附件解析
  485. *
  486. * @param emailInfo 邮件信息,包含附件
  487. * @param resultList 解析结果
  488. */
  489. private void parseResults(EmailInfoDTO emailInfo,
  490. List<ParseResult<ReportData>> resultList) {
  491. String emailTitle = emailInfo.getEmailTitle();
  492. // 拷贝一个新的集合,方便操作不影响原集合
  493. List<EmailZipFileDTO> dtos = ListUtil.toList(emailInfo.getEmailFileList());
  494. if (CollUtil.isEmpty(dtos)) {
  495. return;
  496. }
  497. // 附件文件检查
  498. this.checkEmailFileInfo(emailTitle, dtos);
  499. // 解析邮件报告
  500. for (EmailZipFileDTO zipFile : dtos) {
  501. // 解析并保存报告
  502. ParseResult<ReportData> parseResult = this.parseReportAndHandleResult(emailTitle, emailInfo.getSenderEmail(), zipFile);
  503. if (!Objects.equals(1, parseResult.getStatus())) {
  504. log.error(parseResult.getMsg());
  505. }
  506. if (parseResult.getData() == null) {
  507. parseResult.setData(new ReportData.DefaultReportData());
  508. }
  509. resultList.add(parseResult);
  510. }
  511. }
  512. /**
  513. * 解析报告并保存解析结果
  514. *
  515. * @param emailTitle 邮件主题
  516. * @param zipFile 当前报告的路径信息
  517. * @return /
  518. */
  519. private ParseResult<ReportData> parseReportAndHandleResult(String emailTitle,
  520. String senderEmail,
  521. EmailZipFileDTO zipFile) {
  522. Integer fileId = zipFile.getFileId();
  523. Integer emailType = zipFile.getEmailType();
  524. String reportName = zipFile.getFilename();
  525. String filepath = zipFile.getFilepath();
  526. ParseResult<ReportData> result = new ParseResult<>();
  527. boolean reportFlag = emailType == null || !EmailTypeConst.SUPPORT_EMAIL_TYPES.contains(emailType);
  528. if (reportFlag || StrUtil.isBlank(reportName) || reportName.endsWith(Constants.FILE_HTML)) {
  529. return new ParseResult<>(ReportParseStatus.NOT_A_REPORT, null, reportName);
  530. }
  531. // 类型识别---先识别季度报告,没有季度再识别年度报告,最后识别月报
  532. ReportType reportType = ReportParseUtils.matchReportType(emailType, reportName);
  533. if (reportType == null) {
  534. reportType = ReportParseUtils.matchReportType(emailType, emailTitle);
  535. if (log.isDebugEnabled()) {
  536. log.debug("报告{} 根据邮件主题{} 重新识别的类型是:{}", reportName, emailTitle, reportType);
  537. }
  538. }
  539. // 解析器--根据文件后缀获取对应解析器,解析不了就用AI来解析
  540. ReportParserFileType fileType = ReportParserFileType.getBySuffix(zipFile.getExtName());
  541. // 不支持的格式
  542. if (fileType == null) {
  543. ReportData reportData = this.buildNvlReportData(fileId, reportType, reportName);
  544. return new ParseResult<>(ReportParseStatus.NO_SUPPORT_TEMPLATE, reportData, reportName);
  545. }
  546. // 不是定期报告的判断逻辑放在不支持的格式下面
  547. if (reportType == null) {
  548. ReportData reportData = this.buildNvlReportData(fileId, ReportType.OTHER, reportName);
  549. return new ParseResult<>(ReportParseStatus.NOT_A_REPORT, reportData, reportName);
  550. }
  551. // docx转pdf
  552. if (Objects.equals(ReportParserFileType.WORD, fileType)) {
  553. try {
  554. String outputFile = FileUtil.getParent(filepath, 1) + File.separator + FileUtil.mainName(reportName) + ".pdf";
  555. PdfUtil.convertDocxToPdf(filepath, outputFile);
  556. filepath = outputFile;
  557. } catch (Exception e) {
  558. log.warn("报告{} 转换为pdf失败:{}", reportName, ExceptionUtil.stacktraceToString(e));
  559. }
  560. }
  561. // 首页和尾页转为png图片,首页用来识别基金名称和基金代码、尾页用来识别印章和联系人
  562. List<String> images = ListUtil.list(true);
  563. if (Objects.equals(ReportParserFileType.PDF, fileType)) {
  564. try {
  565. String output = filepath.replaceAll("archive|original", "image");
  566. File outputFile = FileUtil.file(FileUtil.getParent(output, 1));
  567. images = PdfUtil.convertFirstAndLastPagesToPng(filepath, outputFile, 300, zipFile.getPdfPwd());
  568. if (log.isDebugEnabled()) {
  569. log.debug("报告{} 生成的图片地址是:\n{}", reportName, images);
  570. }
  571. } catch (Exception e) {
  572. log.warn("报告{} 生成图片失败:{}", reportName, ExceptionUtil.stacktraceToString(e));
  573. }
  574. } else if (Objects.equals(ReportParserFileType.IMG, fileType)) {
  575. try {
  576. String outputFile = PdfUtil.compressAndSave(filepath);
  577. images.add(outputFile);
  578. } catch (IOException e) {
  579. log.error("报告{} 图片压缩失败,{}", reportName, ExceptionUtil.stacktraceToString(e));
  580. }
  581. }
  582. // ocr识别月报是否管理人版或协会版
  583. ReportMonthlyType monthlyType = ReportMonthlyType.NO_NEED;
  584. if (ReportType.MONTHLY == reportType) {
  585. monthlyType = this.determineReportType(emailTitle, reportName, filepath, images);
  586. }
  587. boolean isAmac = reportType == ReportType.ANNUALLY || reportType == ReportType.QUARTERLY
  588. || (reportType == ReportType.MONTHLY && ReportMonthlyType.AMAC == monthlyType);
  589. // 不支持解析的格式文件
  590. boolean notSupportFile = false;
  591. // 解析报告
  592. ReportData reportData = null;
  593. ReportParserParams params = new ReportParserParams(fileId, reportName, filepath, reportType);
  594. long start = System.currentTimeMillis();
  595. try {
  596. if (isAmac || reportType == ReportType.LETTER) {
  597. ReportParser<ReportData> instance = this.reportParserFactory.getInstance(reportType, fileType);
  598. reportData = instance.parse(params);
  599. result = new ParseResult<>(1, "报告解析成功", reportData);
  600. }
  601. } catch (ReportParseException e) {
  602. result = new ParseResult<>(e.getCode(), StrUtil.format(e.getMsg(), reportName), null);
  603. log.warn("解析失败:{}", result.getMsg());
  604. if (e instanceof NotSupportReportException) {
  605. notSupportFile = true;
  606. }
  607. } catch (Exception e) {
  608. log.warn("解析错误:{}", ExceptionUtil.stacktraceToString(e));
  609. result = new ParseResult<>(ReportParseStatus.PARSE_FAIL, null, e.getMessage());
  610. } finally {
  611. // 如果解析结果是空的就用AI工具解析一次
  612. if (reportData == null && !notSupportFile) {
  613. if (log.isInfoEnabled()) {
  614. log.info("报告{} 是周报或管理人月报或其他类型或解析失败,用AI解析器解析", reportName);
  615. }
  616. try {
  617. if (!isAmac && CollUtil.isNotEmpty(images)) {
  618. filepath = images.get(0);
  619. }
  620. params = new ReportParserParams(fileId, reportName, filepath, reportType);
  621. ReportParser<ReportData> instance = this.reportParserFactory.getInstance(reportType, ReportParserFileType.AI);
  622. reportData = instance.parse(params);
  623. result = new ParseResult<>(1, "报告解析成功--AI", reportData);
  624. } catch (ReportParseException e) {
  625. result = new ParseResult<>(e.getCode(), StrUtil.format(e.getMsg(), reportName), null);
  626. log.warn("AI解析失败:{}", result.getMsg());
  627. } catch (Exception e) {
  628. log.warn("AI解析错误:{}", ExceptionUtil.stacktraceToString(e));
  629. result = new ParseResult<>(ReportParseStatus.PARSE_FAIL, null, e.getMessage());
  630. }
  631. }
  632. // 当reportData==null时重新构建一个reportData对象
  633. if (reportData == null) {
  634. reportData = this.buildNvlReportData(fileId, reportType, reportName);
  635. }
  636. if (reportData.getBaseInfo() != null) {
  637. // 设置月报类型
  638. reportData.getBaseInfo().setMonthlyType(monthlyType.getType());
  639. // 当报告日期还是空时设置为今天的前一天
  640. if (reportData.getBaseInfo().getReportDate() == null) {
  641. reportData.getBaseInfo().setReportDate(DateUtil.offsetDay(new Date(), -1));
  642. }
  643. }
  644. // ocr信息提取(印章、联系人、基金名称和产品代码)
  645. reportData = this.ocrReportData(fileId, reportType, monthlyType, reportData, reportName, senderEmail, images);
  646. result.setData(reportData);
  647. if (log.isInfoEnabled()) {
  648. log.info("报告{} 解析耗时{}ms,结果是:{}", reportName, (System.currentTimeMillis() - start), reportData);
  649. }
  650. }
  651. // 保存报告解析结果
  652. this.saveReportData(reportData, reportType, reportName);
  653. return result;
  654. }
  655. /**
  656. * 判断月报类型(管理人版还是协会版)
  657. *
  658. * @param emailTitle 邮件主题
  659. * @param fileName 报告名称
  660. * @param filepath 报告路径
  661. * @param images 报告的第一页和尾页图片地址(主要用于ocr提取关键信息)
  662. */
  663. public ReportMonthlyType determineReportType(String emailTitle, String fileName,
  664. String filepath, List<String> images) {
  665. // 1. 优先根据文件名判断
  666. if (ReportParseUtils.containsAny(fileName, AMAC_KEYWORDS)) {
  667. return ReportMonthlyType.AMAC;
  668. }
  669. if (ReportParseUtils.containsAny(fileName, ReportParseUtils.MANAGER_KEYWORDS)) {
  670. return ReportMonthlyType.MANAGER;
  671. }
  672. // if (StrUtil.isNotBlank(ReportParseUtils.matchFundCode(fileName))) {
  673. // return ReportMonthlyType.AMAC;
  674. // }
  675. // 2. 根据文件路径判断
  676. List<String> pathSegments = StrUtil.split(filepath, File.separator);
  677. for (String segment : pathSegments) {
  678. boolean isExcluded = ReportParseUtils.containsAny(segment, EXCLUDE_PATH_KEYWORDS);
  679. if (!isExcluded && ReportParseUtils.containsAny(segment, AMAC_KEYWORDS)) {
  680. return ReportMonthlyType.AMAC;
  681. }
  682. if (!isExcluded && ReportParseUtils.containsAny(segment, ReportParseUtils.MANAGER_KEYWORDS)) {
  683. return ReportMonthlyType.MANAGER;
  684. }
  685. }
  686. // 3. 根据邮件主题判断
  687. boolean isAmacEmail = ReportParseUtils.containsAny(emailTitle, AMAC_KEYWORDS)
  688. && !emailTitle.contains("公司及协会版");
  689. if (isAmacEmail) {
  690. return ReportMonthlyType.AMAC;
  691. }
  692. if (ReportParseUtils.containsAny(emailTitle, ReportParseUtils.MANAGER_KEYWORDS)) {
  693. return ReportMonthlyType.MANAGER;
  694. }
  695. // 4.ocr 提取“曲线”、“基金份额”等关键字,如果有曲线则是管理人,如果有估值日期则是协会
  696. if (CollUtil.isNotEmpty(images)) {
  697. try {
  698. return new OCRReportParser().parseMonthlyType(fileName, this.ocrParserUrl, images.get(0));
  699. } catch (Exception ignored) {
  700. return ReportMonthlyType.FAILED;
  701. }
  702. }
  703. return ReportMonthlyType.FAILED;
  704. }
  705. /**
  706. * ocr 提取信息(包括首页的基金名称或报告日期,尾页的印章或联系人等信息)
  707. *
  708. * @param fileId 文件表ID
  709. * @param reportType 报告类型
  710. * @param monthlyType 月报类型
  711. * @param reportData 报告解析结果
  712. * @param fileName 报告名称
  713. * @param senderEmail 邮件发送人邮箱
  714. * @param images 报告的收益和尾页png图片
  715. */
  716. private ReportData ocrReportData(Integer fileId,
  717. ReportType reportType,
  718. ReportMonthlyType monthlyType,
  719. ReportData reportData,
  720. String fileName,
  721. String senderEmail,
  722. List<String> images) {
  723. if (CollUtil.isEmpty(images)) {
  724. return reportData;
  725. }
  726. // 报告才识别尾页的印章和联系人,确认单不识别尾页
  727. if (ReportType.LETTER != reportType) {
  728. if (log.isInfoEnabled()) {
  729. log.info("报告{} 用ocr补充解析结果。补充前的结果是:{}", fileName, reportData);
  730. }
  731. OCRParseData parseRes = null;
  732. try {
  733. // 首页和尾页相等时只读首页
  734. String imageUrl = images.size() == 1 ? images.get(0) : images.get(1);
  735. parseRes = new OCRReportParser().parse(fileName, this.ocrParserUrl, imageUrl);
  736. } catch (Exception e) {
  737. log.error("报告{} OCR识别印章和联系人出错:{}", fileName, e.getMessage());
  738. }
  739. // ocr识别尾页是否包含印章和联系人信息
  740. if (parseRes != null && reportData.getBaseInfo() != null) {
  741. // 协会报告才设置印章标识
  742. boolean isAmac = reportType == ReportType.ANNUALLY || reportType == ReportType.QUARTERLY
  743. || (reportType == ReportType.MONTHLY && ReportMonthlyType.AMAC == monthlyType);
  744. if (isAmac) {
  745. if (TG_EMAIL_LIST.contains(senderEmail)) {
  746. reportData.getBaseInfo().setWithSeals(true);
  747. } else {
  748. reportData.getBaseInfo().setWithSeals(parseRes.getWithSeals());
  749. if (fileName.contains("用印") && !Objects.equals(true, reportData.getBaseInfo().getWithSeals())) {
  750. reportData.getBaseInfo().setWithSeals(true);
  751. }
  752. }
  753. } else {
  754. // 管理人报告才设置联系人标识
  755. reportData.getBaseInfo().setWithContacts(parseRes.getWithContacts());
  756. }
  757. }
  758. // 首页和尾页不相等时解析首页的数据
  759. if (images.size() != 1 || parseRes == null) {
  760. try {
  761. parseRes = new OCRReportParser().parse(fileName, this.ocrParserUrl, images.get(0));
  762. } catch (Exception e) {
  763. log.error("报告{} OCR识别首页基金名称和报告日期出错:{}", fileName, e.getMessage());
  764. }
  765. }
  766. // 用首页识别基金名称、产品代码和基金管理人
  767. if (reportData.getFundInfo() != null && parseRes != null) {
  768. if (StrUtil.isBlank(reportData.getFundInfo().getFundName())) {
  769. reportData.getFundInfo().setFundName(parseRes.getFundName());
  770. }
  771. if (StrUtil.isBlank(reportData.getFundInfo().getFundCode())) {
  772. reportData.getFundInfo().setFundCode(parseRes.getFundCode());
  773. }
  774. if (StrUtil.isBlank(reportData.getFundInfo().getCompanyName())
  775. || !reportData.getFundInfo().getCompanyName().contains("有限公司")) {
  776. reportData.getFundInfo().setCompanyName(parseRes.getCompanyName());
  777. }
  778. }
  779. reportData.setAiParse(true);
  780. return reportData;
  781. }
  782. // 确认单AI解析失败时重新用OCR识别
  783. if (!reportData.wasFailed()) {
  784. return reportData;
  785. }
  786. if (log.isInfoEnabled()) {
  787. log.info("确认单报告{} 用ocr补充解析结果。补充前的结果是:{}", fileName, reportData);
  788. }
  789. LetterReportData letterReportData = (LetterReportData) reportData;
  790. OCRLetterParseData parseRes = null;
  791. try {
  792. parseRes = new OCRReportParser().parseLetterData(fileName, this.ocrParserUrl, images.get(0));
  793. } catch (Exception e) {
  794. log.error("确认单报告{} OCR提取确认单关键信息出错:{}", fileName, e.getMessage());
  795. }
  796. if (parseRes == null) {
  797. return reportData;
  798. }
  799. if (letterReportData.getFundInfo() != null) {
  800. letterReportData.getFundInfo().setFundName(parseRes.getFundName());
  801. letterReportData.getFundInfo().setFundCode(parseRes.getFundCode());
  802. }
  803. // 投资者信息
  804. if (letterReportData.getInvestorInfo() == null) {
  805. letterReportData.setInvestorInfo(new ReportInvestorInfoDTO(fileId));
  806. }
  807. letterReportData.getInvestorInfo().setInvestorName(parseRes.getInvestorName());
  808. letterReportData.getInvestorInfo().setCertificateNumber(parseRes.getCertificateNumber());
  809. letterReportData.getInvestorInfo().setTradingAccount(parseRes.getTradingAccount());
  810. letterReportData.getInvestorInfo().setFundAccount(parseRes.getFundAccount());
  811. letterReportData.getInvestorInfo().setCertificateType(parseRes.getCertificateType());
  812. // 交易流水
  813. if (letterReportData.getTransaction() == null) {
  814. letterReportData.setTransaction(new ReportFundTransactionDTO(fileId));
  815. }
  816. letterReportData.getTransaction().setTransactionType(parseRes.getTransactionType());
  817. letterReportData.getTransaction().setApplyDate(parseRes.getApplyDate());
  818. letterReportData.getTransaction().setApplyShare(parseRes.getApplyShare());
  819. letterReportData.getTransaction().setApplyAmount(parseRes.getApplyAmount());
  820. letterReportData.getTransaction().setHoldingDate(parseRes.getHoldingDate());
  821. letterReportData.getTransaction().setAmount(parseRes.getAmount());
  822. letterReportData.getTransaction().setShare(parseRes.getShare());
  823. letterReportData.getTransaction().setNav(parseRes.getNav());
  824. letterReportData.setAiParse(true);
  825. return letterReportData;
  826. }
  827. /**
  828. * 当reportData==null时重新构建一个新对象
  829. *
  830. * @param fileId 文件ID
  831. * @param reportType 报告类型
  832. * @param reportName 报告名称
  833. * @return /
  834. */
  835. private ReportData buildNvlReportData(Integer fileId, ReportType reportType, String reportName) {
  836. ReportData reportData = null;
  837. if (reportType == null) {
  838. reportType = ReportType.OTHER;
  839. }
  840. ReportBaseInfoDTO baseInfo = new ReportBaseInfoDTO(fileId);
  841. baseInfo.setReportName(reportName);
  842. baseInfo.setReportType(reportType.name());
  843. String reportDate = ReportParseUtils.matchReportDate(reportType, reportName);
  844. baseInfo.setReportDate(ConvertUtil.toDate(reportDate));
  845. ReportFundInfoDTO fundInfo = new ReportFundInfoDTO(fileId);
  846. if (ReportType.ANNUALLY == reportType) {
  847. reportData = new AnnuallyReportData(baseInfo, fundInfo);
  848. } else if (ReportType.QUARTERLY == reportType) {
  849. reportData = new QuarterlyReportData(baseInfo, fundInfo);
  850. } else if (ReportType.MONTHLY == reportType) {
  851. reportData = new MonthlyReportData(baseInfo, fundInfo);
  852. } else if (ReportType.WEEKLY == reportType) {
  853. reportData = new WeeklyReportData(baseInfo, fundInfo);
  854. } else if (ReportType.OTHER == reportType) {
  855. reportData = new ReportData.DefaultReportData(baseInfo, fundInfo);
  856. } else if (ReportType.LETTER == reportType) {
  857. reportData = new LetterReportData(baseInfo, fundInfo);
  858. }
  859. return reportData;
  860. }
  861. /**
  862. * 保存报告解析结果
  863. *
  864. * @param reportData 报告解析结果
  865. * @param reportType 报告类型
  866. * @param fileName 报告名称
  867. */
  868. private void saveReportData(ReportData reportData, ReportType reportType, String fileName) {
  869. if (reportData == null) {
  870. return;
  871. }
  872. StopWatch writeWatch = new StopWatch();
  873. writeWatch.start();
  874. try {
  875. ReportWriter<ReportData> instance = this.reportWriterFactory.getInstance(reportType);
  876. instance.write(reportData);
  877. } catch (Exception e) {
  878. log.error("报告{} 结果保存失败 {}", fileName, ExceptionUtil.stacktraceToString(e));
  879. } finally {
  880. writeWatch.stop();
  881. if (log.isInfoEnabled()) {
  882. log.info("报告{} 解析结果保存完成,耗时{}ms", fileName, writeWatch.getTotalTimeMillis());
  883. }
  884. }
  885. }
  886. private EmailFileInfoDO saveEmailFileInfo(Integer emailId, EmailZipFileDTO zipFile) {
  887. String filename = zipFile.getFilename();
  888. String filepath = zipFile.getFilepath();
  889. EmailFileInfoDO emailFileInfoDO = this.buildEmailFileInfoDO(emailId, filename, filepath);
  890. if (!Objects.equals(1, zipFile.getParseStatus()) || StrUtil.isNotBlank(zipFile.getFailReason())) {
  891. emailFileInfoDO.setParseStatus(zipFile.getParseStatus());
  892. emailFileInfoDO.setFailReason(zipFile.getFailReason());
  893. }
  894. if (emailFileInfoDO.getId() != null) {
  895. this.emailFileInfoMapper.updateTimeById(emailFileInfoDO.getId(), new Date());
  896. return emailFileInfoDO;
  897. }
  898. LambdaQueryWrapper<EmailFileInfoDO> wrapper = Wrappers.lambdaQuery(EmailFileInfoDO.class)
  899. .eq(EmailFileInfoDO::getEmailId, emailId)
  900. .eq(EmailFileInfoDO::getFileName, filename)
  901. .eq(EmailFileInfoDO::getFilePath, filepath);
  902. List<EmailFileInfoDO> tempList = this.emailFileInfoMapper.selectList(wrapper);
  903. if (CollUtil.isNotEmpty(tempList)) {
  904. return tempList.get(0);
  905. }
  906. this.emailFileInfoMapper.insertById(emailFileInfoDO);
  907. return emailFileInfoDO;
  908. }
  909. private EmailFileInfoDO buildEmailFileInfoDO(Integer emailId, String fileName, String filePath) {
  910. EmailFileInfoDO emailFileInfoDO = new EmailFileInfoDO();
  911. emailFileInfoDO.setId(null);
  912. emailFileInfoDO.setEmailId(emailId);
  913. emailFileInfoDO.setFileName(fileName);
  914. emailFileInfoDO.setFilePath(filePath);
  915. emailFileInfoDO.setIsvalid(1);
  916. emailFileInfoDO.setCreatorId(0);
  917. emailFileInfoDO.setCreateTime(new Date());
  918. emailFileInfoDO.setUpdaterId(0);
  919. emailFileInfoDO.setUpdateTime(new Date());
  920. return emailFileInfoDO;
  921. }
  922. private Integer saveEmailParseInfo(EmailParseInfoDO emailParseInfoDO) {
  923. if (emailParseInfoDO == null) {
  924. return null;
  925. }
  926. // 重新邮件功能 -> 修改解析时间和更新时间
  927. if (emailParseInfoDO.getId() != null) {
  928. this.emailParseInfoMapper.updateParseTime(emailParseInfoDO.getId(), emailParseInfoDO.getParseDate());
  929. return emailParseInfoDO.getId();
  930. }
  931. LambdaQueryWrapper<EmailParseInfoDO> wrapper = Wrappers.lambdaQuery(EmailParseInfoDO.class)
  932. .eq(EmailParseInfoDO::getEmailTitle, emailParseInfoDO.getEmailTitle())
  933. .eq(EmailParseInfoDO::getSenderEmail, emailParseInfoDO.getSenderEmail())
  934. .eq(EmailParseInfoDO::getEmailDate, emailParseInfoDO.getEmailDate())
  935. .eq(EmailParseInfoDO::getEmail, emailParseInfoDO.getEmail())
  936. .orderByDesc(EmailParseInfoDO::getId);
  937. List<EmailParseInfoDO> tempList = this.emailParseInfoMapper.selectList(wrapper);
  938. if (CollUtil.isNotEmpty(tempList)) {
  939. this.emailParseInfoMapper.update(emailParseInfoDO, wrapper);
  940. return tempList.get(0).getId();
  941. }
  942. this.emailParseInfoMapper.insertAndId(emailParseInfoDO);
  943. return emailParseInfoDO.getId();
  944. }
  945. private EmailParseInfoDO buildEmailParseInfo(String emailAddress, EmailInfoDTO emailInfo, long totalSize) {
  946. EmailParseInfoDO emailParseInfoDO = new EmailParseInfoDO();
  947. emailParseInfoDO.setId(null);
  948. emailParseInfoDO.setSenderEmail(emailInfo.getSenderEmail());
  949. emailParseInfoDO.setEmail(emailAddress);
  950. emailParseInfoDO.setEmailDate(DateUtil.parse(emailInfo.getEmailDate(), DateConst.YYYY_MM_DD_HH_MM_SS));
  951. emailParseInfoDO.setParseDate(new Date());
  952. emailParseInfoDO.setEmailTitle(emailInfo.getEmailTitle());
  953. emailParseInfoDO.setEmailContent(emailInfo.getEmailContent());
  954. emailParseInfoDO.setParseStatus(EmailParseStatusConst.SUCCESS);
  955. emailParseInfoDO.setAttrSize(totalSize);
  956. emailParseInfoDO.setIsvalid(1);
  957. emailParseInfoDO.setCreatorId(0);
  958. emailParseInfoDO.setCreateTime(new Date());
  959. emailParseInfoDO.setUpdaterId(0);
  960. emailParseInfoDO.setUpdateTime(new Date());
  961. return emailParseInfoDO;
  962. }
  963. /**
  964. * 读取邮件
  965. *
  966. * @param mailboxInfoDTO 邮箱配置信息
  967. * @param startDate 邮件起始日期
  968. * @param endDate 邮件截止日期(为null,将解析邮件日期小于等于startDate的当天邮件)
  969. * @return 读取到的邮件信息
  970. * @throws Exception 异常信息
  971. */
  972. private Map<String, List<EmailContentInfoDTO>> realEmail(MailboxInfoDTO mailboxInfoDTO,
  973. Date startDate, Date endDate,
  974. List<String> folderNames) throws Exception {
  975. if (CollUtil.isEmpty(folderNames)) {
  976. folderNames = ListUtil.toList("INBOX");
  977. }
  978. Store store = EmailUtil.getStoreNew(mailboxInfoDTO);
  979. if (store == null) {
  980. return MapUtil.newHashMap(4);
  981. }
  982. Map<String, List<EmailContentInfoDTO>> result = MapUtil.newHashMap(128);
  983. try {
  984. if (log.isDebugEnabled()) {
  985. Folder[] list = store.getDefaultFolder().list("*");
  986. List<String> names = Arrays.stream(list).map(Folder::getFullName).toList();
  987. log.debug("获取所有邮箱文件夹:{}", names);
  988. }
  989. for (String folderName : folderNames) {
  990. try {
  991. Map<String, List<EmailContentInfoDTO>> temp = this.getFolderEmail(mailboxInfoDTO,
  992. startDate, endDate, store, folderName);
  993. if (MapUtil.isNotEmpty(temp)) {
  994. result.putAll(temp);
  995. }
  996. } catch (Exception e) {
  997. log.warn("文件夹{} 邮件获取失败:{}", folderName, ExceptionUtil.stacktraceToString(e));
  998. }
  999. }
  1000. } catch (Exception e) {
  1001. log.error("邮件获取失败:{}", ExceptionUtil.stacktraceToString(e));
  1002. } finally {
  1003. store.close();
  1004. }
  1005. return result;
  1006. }
  1007. private Map<String, List<EmailContentInfoDTO>> getFolderEmail(MailboxInfoDTO mailboxInfoDTO,
  1008. Date startDate, Date endDate,
  1009. Store store, String folderName) throws MessagingException {
  1010. // 默认读取收件箱的邮件
  1011. Folder folder = store.getFolder(folderName);
  1012. folder.open(this.readWriteSeen ? Folder.READ_WRITE : Folder.READ_ONLY);
  1013. Message[] messages = getEmailMessage(folder, mailboxInfoDTO.getProtocol(), startDate);
  1014. if (messages == null || messages.length == 0) {
  1015. log.warn("{} 获取不到邮件 -> 邮箱信息:{},开始时间:{},结束时间:{}", folderName, mailboxInfoDTO, startDate, endDate);
  1016. return MapUtil.newHashMap();
  1017. }
  1018. String emailAddress = mailboxInfoDTO.getAccount();
  1019. Map<String, List<EmailContentInfoDTO>> emailMessageMap = MapUtil.newHashMap();
  1020. for (Message message : messages) {
  1021. long start = System.currentTimeMillis();
  1022. List<EmailContentInfoDTO> dtos = CollUtil.newArrayList();
  1023. String emailTitle = message.getSubject();
  1024. if (this.readWriteSeen && isMessageRead(message)) {
  1025. log.warn("{} 邮件{} 已读,不用重新下载解析!", folderName, emailTitle);
  1026. continue;
  1027. }
  1028. try {
  1029. Date emailDate = message.getSentDate();
  1030. String emailDateStr = DateUtil.format(emailDate, DateConst.YYYY_MM_DD_HH_MM_SS);
  1031. if (log.isInfoEnabled()) {
  1032. log.info("{} 邮件{} 数据获取中,邮件时间:{}", folderName, emailTitle, emailDateStr);
  1033. }
  1034. boolean isNotParseConditionSatisfied = emailDate == null
  1035. || (endDate != null && emailDate.compareTo(endDate) > 0)
  1036. || (startDate != null && emailDate.compareTo(startDate) < 0);
  1037. if (isNotParseConditionSatisfied) {
  1038. String st = DateUtil.formatDateTime(startDate);
  1039. String ed = DateUtil.formatDateTime(endDate);
  1040. log.warn("{} 邮件{} 发送时间{}不在区间内【{} ~ {}】", folderName, emailTitle, emailDateStr, st, ed);
  1041. continue;
  1042. }
  1043. String senderEmail = getSenderEmail(message);
  1044. Integer emailType = EmailUtil.getEmailTypeBySubject(emailTitle);
  1045. if (emailType == null) {
  1046. log.warn("{} 邮件不满足解析条件 -> 邮件主题:{},邮件日期:{}", folderName, emailTitle, emailDateStr);
  1047. continue;
  1048. }
  1049. // // 成功解析的邮件不用重复下载
  1050. // Integer okNum = this.emailParseInfoMapper.countEmailByInfoAndStatus(emailTitle, senderEmail, emailAddress, emailDateStr);
  1051. // if (okNum > 0) {
  1052. // if (log.isInfoEnabled()) {
  1053. // log.info("{} 邮件{} 已经存在解析完成的记录,不要重复下载了。", folderName, emailTitle);
  1054. // }
  1055. // continue;
  1056. // }
  1057. if (log.isInfoEnabled()) {
  1058. log.info("{} 邮件{} 基本信息获取完成,开始下载附件!邮件日期:{}", folderName, emailTitle, emailDateStr);
  1059. }
  1060. Object messageContent = message.getContent();
  1061. String[] contents = new String[]{null};
  1062. if (messageContent instanceof Multipart multipart) {
  1063. this.reMultipart(emailAddress, emailTitle, emailDate, multipart, contents, dtos);
  1064. } else {
  1065. log.warn("{} 邮件{} 获取不了附件", folderName, emailTitle);
  1066. }
  1067. if (CollUtil.isEmpty(dtos)) {
  1068. log.warn("{} 邮件{} 没有获取到附件", folderName, emailTitle);
  1069. continue;
  1070. }
  1071. dtos.forEach(e -> {
  1072. e.setEmailType(emailType);
  1073. e.setSenderEmail(senderEmail);
  1074. e.setEmailContent(contents[0]);
  1075. });
  1076. emailMessageMap.put(IdUtil.simpleUUID(), dtos);
  1077. } catch (Exception e) {
  1078. log.error("{} 邮件{} 下载报错 {}", folderName, emailTitle, ExceptionUtil.stacktraceToString(e));
  1079. } finally {
  1080. if (CollUtil.isNotEmpty(dtos) && log.isInfoEnabled()) {
  1081. log.info("{} 邮件{} 下载完成,总计耗时{} ms,文件内容如下\n {}", folderName,
  1082. emailTitle, System.currentTimeMillis() - start, dtos);
  1083. }
  1084. }
  1085. }
  1086. if (this.readWriteSeen) {
  1087. // 设置已读标志
  1088. folder.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
  1089. }
  1090. folder.close(false);
  1091. return emailMessageMap;
  1092. }
  1093. private void rePart(String account, String subject, Date sendDate, Part part,
  1094. List<EmailContentInfoDTO> emailContentInfoDTOList) throws Exception {
  1095. String fileName = EmailUtil.decodeFileName(part);
  1096. if (StrUtil.isBlank(fileName)) {
  1097. return;
  1098. }
  1099. if (fileName.contains("\"") || fileName.contains("\n")) {
  1100. fileName = fileName.replaceAll("\"", "").replaceAll("\n", "");
  1101. }
  1102. if (fileName.contains("=?")) {
  1103. fileName = MimeUtility.decodeText(fileName);
  1104. }
  1105. String disposition = part.getDisposition();
  1106. String contentType = part.getContentType();
  1107. String[] att_files = new String[]{Constants.ARCHIVE_7Z, Constants.ARCHIVE_RAR, Constants.ARCHIVE_ZIP,
  1108. Constants.FILE_PDF, Constants.FILE_DOCX, Constants.FILE_JPG, Constants.FILE_PNG};
  1109. boolean attachmentFlag = StrUtil.endWithAny(fileName, att_files);
  1110. boolean isAttachment = attachmentFlag
  1111. || Part.ATTACHMENT.equalsIgnoreCase(disposition)
  1112. || (contentType != null && attachmentMimePrefixes.stream().anyMatch(prefix ->
  1113. StrUtil.startWithIgnoreCase(contentType, prefix)
  1114. ));
  1115. if (!isAttachment) {
  1116. log.warn("邮件{} 未检测到{}类型的附件 (fileName={}, disposition={}, contentType={})",
  1117. subject, att_files, fileName, disposition, contentType);
  1118. return;
  1119. }
  1120. File saveFile = this.generateSavePath(account, sendDate, fileName);
  1121. if (!saveFile.exists()) {
  1122. if (!saveFile.getParentFile().exists()) {
  1123. boolean mkdirs = saveFile.getParentFile().mkdirs();
  1124. if (!mkdirs) {
  1125. log.warn("file path mkdir failed.");
  1126. }
  1127. }
  1128. try (InputStream is = part.getInputStream()) {
  1129. Files.copy(is, saveFile.toPath());
  1130. }
  1131. } else {
  1132. if (log.isInfoEnabled()) {
  1133. log.info("邮件{} 已下载过附件:{},不用重新下载了。", subject, saveFile.toPath());
  1134. }
  1135. }
  1136. EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
  1137. emailContentInfoDTO.setFileName(fileName);
  1138. emailContentInfoDTO.setFileSize(part.getSize());
  1139. emailContentInfoDTO.setFilePath(saveFile.getAbsolutePath());
  1140. emailContentInfoDTO.setEmailAddress(account);
  1141. emailContentInfoDTO.setEmailTitle(subject);
  1142. emailContentInfoDTO.setEmailDate(DateUtil.format(sendDate, DateConst.YYYY_MM_DD_HH_MM_SS));
  1143. emailContentInfoDTOList.add(emailContentInfoDTO);
  1144. }
  1145. public File generateSavePath(String account, Date sendDate, String fileName) {
  1146. String emailDateStr = DateUtil.format(sendDate, DateConst.YYYYMMDD);
  1147. String filePath = this.path + File.separator + account + File.separator +
  1148. emailDateStr + File.separator + "original" + File.separator;
  1149. // 压缩包重名时的后面的压缩包会覆盖前面压缩包的问题(不考虑普通文件)
  1150. String emailDate = DateUtil.format(sendDate, DateConst.YYYYMMDDHHMMSS24);
  1151. String realName = ArchiveUtil.isArchive(fileName) ? emailDate + fileName : fileName;
  1152. return FileUtil.file(filePath + realName);
  1153. }
  1154. private void reMultipart(String account, String subject, Date emailDate,
  1155. Multipart multipart, String[] contents,
  1156. List<EmailContentInfoDTO> emailContentInfoDTOList) throws Exception {
  1157. for (int i = 0; i < multipart.getCount(); i++) {
  1158. Part bodyPart = multipart.getBodyPart(i);
  1159. Object bodyPartContent = bodyPart.getContent();
  1160. if (bodyPartContent instanceof String) {
  1161. if (log.isDebugEnabled()) {
  1162. log.debug("邮件{} 获取的正文不做解析,内容是 {}", subject, bodyPartContent);
  1163. }
  1164. if (StrUtil.startWithIgnoreCase(bodyPart.getContentType(), MediaType.TEXT_HTML_VALUE)) {
  1165. contents[0] = bodyPartContent.toString();
  1166. }
  1167. continue;
  1168. }
  1169. if (bodyPartContent instanceof Multipart mp) {
  1170. this.reMultipart(account, subject, emailDate, mp, contents, emailContentInfoDTOList);
  1171. } else {
  1172. this.rePart(account, subject, emailDate, bodyPart, emailContentInfoDTOList);
  1173. }
  1174. }
  1175. }
  1176. private String getSenderEmail(Message message) {
  1177. Address[] senderAddress;
  1178. try {
  1179. senderAddress = message.getFrom();
  1180. if (senderAddress == null || senderAddress.length == 0) {
  1181. return null;
  1182. }
  1183. // 此时的address是含有编码(MIME编码方式)后的文本和实际的邮件地址
  1184. String address = "";
  1185. for (Address from : senderAddress) {
  1186. if (StrUtil.isNotBlank(from.toString())) {
  1187. address = from.toString();
  1188. break;
  1189. }
  1190. }
  1191. // 正则表达式匹配邮件地址
  1192. Pattern pattern = Pattern.compile("<(\\S+)>");
  1193. Matcher matcher = pattern.matcher(address);
  1194. if (matcher.find()) {
  1195. return matcher.group(1);
  1196. }
  1197. } catch (MessagingException e) {
  1198. log.error(e.getMessage(), e);
  1199. }
  1200. return null;
  1201. }
  1202. private Message[] getEmailMessage(Folder folder, String protocol, Date startDate) {
  1203. try {
  1204. if (protocol.contains("imap")) {
  1205. // 获取邮件日期大于等于startDate的邮件(搜索条件只支持按天)
  1206. SearchTerm startDateTerm = new ReceivedDateTerm(ComparisonTerm.GE, startDate);
  1207. return folder.search(startDateTerm);
  1208. } else {
  1209. return folder.getMessages();
  1210. }
  1211. } catch (MessagingException e) {
  1212. throw new RuntimeException(e);
  1213. }
  1214. }
  1215. /**
  1216. * 检查邮件是否已读
  1217. *
  1218. * @param message 邮件对象
  1219. * @return true表示已读,false表示未读
  1220. * @throws MessagingException 如果访问邮件标志时出错
  1221. */
  1222. private boolean isMessageRead(Message message) throws MessagingException {
  1223. // 获取邮件的所有标志
  1224. Flags flags = message.getFlags();
  1225. // 检查是否包含 SEEN 标志
  1226. return flags.contains(Flags.Flag.SEEN);
  1227. }
  1228. }