EmailParseService.java 61 KB

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