EmailParseService.java 54 KB

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