EmailParseService.java 38 KB

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