EmailParseService.java 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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. entityList.add(entity);
  324. }
  325. return entityList;
  326. }
  327. /**
  328. * 上传文件解析并返回解析状态
  329. *
  330. * @param params 上传文件路径
  331. * @return /
  332. */
  333. public List<UploadReportResult> uploadReportResults(UploadReportParams params) {
  334. List<ParseResult<ReportData>> dataList = ListUtil.list(false);
  335. String emailTitle = params.getTitle();
  336. List<UploadReportParams.ReportInfo> reportInfos = params.getReportInfos();
  337. List<EmailZipFileDTO> dtos = ListUtil.list(false);
  338. for (UploadReportParams.ReportInfo e : reportInfos) {
  339. String reportPath = e.getReportPath();
  340. if (ArchiveUtil.isArchive(reportPath)) {
  341. try {
  342. this.handleCompressedFiles(emailTitle, reportPath, e.getReportType(), dtos);
  343. } catch (Exception ex) {
  344. log.warn("报告{} 压缩包解压失败:{}", reportPath, ExceptionUtil.stacktraceToString(ex));
  345. ReportData reportData = new ReportData.DefaultReportData();
  346. dataList.add(new ParseResult<>(ReportParseStatus.ARCHIVE_FAIL, reportData));
  347. }
  348. } else {
  349. dtos.add(new EmailZipFileDTO(emailTitle, e));
  350. }
  351. }
  352. // 重新判断类型
  353. this.recheckEmailType(emailTitle, dtos);
  354. EmailInfoDTO emailInfo = new EmailInfoDTO(emailTitle, dtos);
  355. Long totalSize = dtos.stream().map(EmailZipFileDTO::getFileSize).reduce(0L, Long::sum);
  356. EmailParseInfoDO emailDo = this.buildEmailParseInfo("upload", emailInfo, totalSize);
  357. Integer emailId = this.saveEmailParseInfo(emailDo);
  358. for (EmailZipFileDTO zipFile : dtos) {
  359. EmailFileInfoDO emailFile = this.saveEmailFileInfo(emailId, zipFile.getFilename(), zipFile.getFilepath());
  360. zipFile.setFileId(emailFile.getId());
  361. }
  362. // 解析并处理解析结果
  363. this.parseAndUpdateResult(emailId, emailInfo, dataList);
  364. // 解析结果转换
  365. List<UploadReportResult> resultList = ListUtil.list(false);
  366. for (ParseResult<ReportData> result : dataList) {
  367. ReportData data = result.getData();
  368. resultList.add(new UploadReportResult(data.getBaseInfo().getFileId(),
  369. data.getBaseInfo().getReportName(), result.getStatus(), result.getMsg()));
  370. }
  371. return resultList;
  372. }
  373. private void parseAndUpdateResult(Integer emailId, EmailInfoDTO emailInfo, List<ParseResult<ReportData>> dataList) {
  374. this.parseResults(emailInfo, dataList);
  375. String failReason = null;
  376. int emailParseStatus = EmailParseStatusConst.SUCCESS;
  377. // 报告邮件有一条失败就表示整个邮件解析失败
  378. if (CollUtil.isNotEmpty(dataList)) {
  379. List<EmailFileInfoDO> entityList = this.buildEmailFileInfo(dataList);
  380. this.emailFileInfoMapper.batchUpdateByFileId(entityList);
  381. long failNum = dataList.stream().filter(e -> !Objects.equals(EmailParseStatusConst.SUCCESS, e.getStatus())).count();
  382. if (failNum > 0) {
  383. emailParseStatus = EmailParseStatusConst.FAIL;
  384. failReason = dataList.stream().map(ParseResult::getMsg).collect(Collectors.joining(";"));
  385. }
  386. }
  387. this.emailParseInfoMapper.updateParseStatus(emailId, emailParseStatus, failReason);
  388. }
  389. /**
  390. * 重新校验邮件附件的类型(用邮件主题+附件名称)
  391. *
  392. * @param emailTitle 邮件主题
  393. * @param dtos 所有附件
  394. */
  395. private void recheckEmailType(String emailTitle, List<EmailZipFileDTO> dtos) {
  396. for (EmailZipFileDTO emailFile : dtos) {
  397. if (EmailTypeConst.SUPPORT_NO_OTHER_TYPES.contains(emailFile.getEmailType())) {
  398. continue;
  399. }
  400. Integer type = EmailUtil.getEmailTypeBySubject(emailTitle + emailFile.getFilename());
  401. // 特殊月报
  402. if ((Objects.equals(EmailTypeConst.NAV_EMAIL_TYPE, type) || Objects.equals(EmailTypeConst.REPORT_OTHER_TYPE, type))
  403. && ReportParseUtils.containsAny(emailTitle, ReportParseUtils.MONTHLY_REPORT_KEYWORDS)) {
  404. type = EmailTypeConst.REPORT_EMAIL_TYPE;
  405. }
  406. if (EmailTypeConst.SUPPORT_EMAIL_TYPES.contains(type)) {
  407. emailFile.setEmailType(type);
  408. }
  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. // 解析并保存报告
  492. ParseResult<ReportData> parseResult = this.parseReportAndHandleResult(emailTitle, emailInfo.getSenderEmail(), zipFile);
  493. if (!Objects.equals(1, parseResult.getStatus())) {
  494. log.error(parseResult.getMsg());
  495. }
  496. if (parseResult.getData() == null) {
  497. parseResult.setData(new ReportData.DefaultReportData());
  498. }
  499. resultList.add(parseResult);
  500. }
  501. }
  502. /**
  503. * 解析报告并保存解析结果
  504. *
  505. * @param emailTitle 邮件主题
  506. * @param zipFile 当前报告的路径信息
  507. * @return /
  508. */
  509. private ParseResult<ReportData> parseReportAndHandleResult(String emailTitle,
  510. String senderEmail,
  511. EmailZipFileDTO zipFile) {
  512. Integer fileId = zipFile.getFileId();
  513. Integer emailType = zipFile.getEmailType();
  514. String reportName = zipFile.getFilename();
  515. String filepath = zipFile.getFilepath();
  516. ParseResult<ReportData> result = new ParseResult<>();
  517. boolean reportFlag = emailType == null || !EmailTypeConst.SUPPORT_EMAIL_TYPES.contains(emailType);
  518. if (reportFlag || StrUtil.isBlank(reportName) || reportName.endsWith(Constants.FILE_HTML)) {
  519. return new ParseResult<>(ReportParseStatus.NOT_A_REPORT, null, reportName);
  520. }
  521. // 类型识别---先识别季度报告,没有季度再识别年度报告,最后识别月报
  522. ReportType reportType = ReportParseUtils.matchReportType(emailType, reportName);
  523. if (reportType == null) {
  524. reportType = ReportParseUtils.matchReportType(emailType, emailTitle);
  525. if (log.isDebugEnabled()) {
  526. log.debug("报告{} 根据邮件主题{} 重新识别的类型是:{}", reportName, emailTitle, reportType);
  527. }
  528. }
  529. // 解析器--根据文件后缀获取对应解析器,解析不了就用AI来解析
  530. ReportParserFileType fileType = ReportParserFileType.getBySuffix(zipFile.getExtName());
  531. // 不支持的格式
  532. if (fileType == null) {
  533. ReportData reportData = this.buildNvlReportData(fileId, reportType, reportName);
  534. return new ParseResult<>(ReportParseStatus.NO_SUPPORT_TEMPLATE, reportData, reportName);
  535. }
  536. // 不是定期报告的判断逻辑放在不支持的格式下面
  537. if (reportType == null) {
  538. ReportData reportData = this.buildNvlReportData(fileId, ReportType.OTHER, reportName);
  539. return new ParseResult<>(ReportParseStatus.NOT_A_REPORT, reportData, reportName);
  540. }
  541. // docx转pdf
  542. if (Objects.equals(ReportParserFileType.WORD, fileType)) {
  543. try {
  544. String outputFile = FileUtil.getParent(filepath, 1) + File.separator + FileUtil.mainName(reportName) + ".pdf";
  545. PdfUtil.convertDocxToPdf(filepath, outputFile);
  546. filepath = outputFile;
  547. } catch (Exception e) {
  548. log.warn("报告{} 转换为pdf失败:{}", reportName, 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{}", reportName, images);
  560. }
  561. } catch (Exception e) {
  562. log.warn("报告{} 生成图片失败:{}", reportName, 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("报告{} 图片压缩失败,{}", reportName, ExceptionUtil.stacktraceToString(e));
  570. }
  571. }
  572. // ocr识别月报是否管理人版或协会版
  573. ReportMonthlyType monthlyType = ReportMonthlyType.NO_NEED;
  574. if (ReportType.MONTHLY == reportType) {
  575. monthlyType = this.determineReportType(emailTitle, reportName, 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, reportName, 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(), reportName), 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解析器解析", reportName);
  605. }
  606. try {
  607. if (!isAmac && CollUtil.isNotEmpty(images)) {
  608. filepath = images.get(0);
  609. }
  610. params = new ReportParserParams(fileId, reportName, 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(), reportName), 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. if (reportData == null) {
  624. reportData = this.buildNvlReportData(fileId, reportType, reportName);
  625. }
  626. if (reportData.getBaseInfo() != null) {
  627. // 设置月报类型
  628. reportData.getBaseInfo().setMonthlyType(monthlyType.getType());
  629. // 当报告日期还是空时设置为今天的前一天
  630. if (reportData.getBaseInfo().getReportDate() == null) {
  631. reportData.getBaseInfo().setReportDate(DateUtil.offsetDay(new Date(), -1));
  632. }
  633. }
  634. // ocr信息提取(印章、联系人、基金名称和产品代码)
  635. reportData = this.ocrReportData(fileId, reportType, monthlyType, reportData, reportName, senderEmail, images);
  636. result.setData(reportData);
  637. if (log.isInfoEnabled()) {
  638. log.info("报告{} 解析耗时{}ms,结果是:{}", reportName, (System.currentTimeMillis() - start), reportData);
  639. }
  640. }
  641. // 保存报告解析结果
  642. this.saveReportData(reportData, reportType, reportName);
  643. return result;
  644. }
  645. /**
  646. * 判断月报类型(管理人版还是协会版)
  647. *
  648. * @param emailTitle 邮件主题
  649. * @param fileName 报告名称
  650. * @param filepath 报告路径
  651. * @param images 报告的第一页和尾页图片地址(主要用于ocr提取关键信息)
  652. */
  653. public ReportMonthlyType determineReportType(String emailTitle, String fileName,
  654. String filepath, List<String> images) {
  655. // 1. 优先根据文件名判断
  656. if (ReportParseUtils.containsAny(fileName, AMAC_KEYWORDS)) {
  657. return ReportMonthlyType.AMAC;
  658. }
  659. if (ReportParseUtils.containsAny(fileName, ReportParseUtils.MANAGER_KEYWORDS)) {
  660. return ReportMonthlyType.MANAGER;
  661. }
  662. // if (StrUtil.isNotBlank(ReportParseUtils.matchFundCode(fileName))) {
  663. // return ReportMonthlyType.AMAC;
  664. // }
  665. // 2. 根据文件路径判断
  666. List<String> pathSegments = StrUtil.split(filepath, File.separator);
  667. for (String segment : pathSegments) {
  668. boolean isExcluded = ReportParseUtils.containsAny(segment, EXCLUDE_PATH_KEYWORDS);
  669. if (!isExcluded && ReportParseUtils.containsAny(segment, AMAC_KEYWORDS)) {
  670. return ReportMonthlyType.AMAC;
  671. }
  672. if (!isExcluded && ReportParseUtils.containsAny(segment, ReportParseUtils.MANAGER_KEYWORDS)) {
  673. return ReportMonthlyType.MANAGER;
  674. }
  675. }
  676. // 3. 根据邮件主题判断
  677. boolean isAmacEmail = ReportParseUtils.containsAny(emailTitle, AMAC_KEYWORDS)
  678. && !emailTitle.contains("公司及协会版");
  679. if (isAmacEmail) {
  680. return ReportMonthlyType.AMAC;
  681. }
  682. if (ReportParseUtils.containsAny(emailTitle, ReportParseUtils.MANAGER_KEYWORDS)) {
  683. return ReportMonthlyType.MANAGER;
  684. }
  685. // 4.ocr 提取“曲线”、“基金份额”等关键字,如果有曲线则是管理人,如果有估值日期则是协会
  686. if (CollUtil.isNotEmpty(images)) {
  687. try {
  688. return new OCRReportParser().parseMonthlyType(fileName, this.ocrParserUrl, images.get(0));
  689. } catch (Exception ignored) {
  690. return ReportMonthlyType.FAILED;
  691. }
  692. }
  693. return ReportMonthlyType.FAILED;
  694. }
  695. /**
  696. * ocr 提取信息(包括首页的基金名称或报告日期,尾页的印章或联系人等信息)
  697. *
  698. * @param fileId 文件表ID
  699. * @param reportType 报告类型
  700. * @param monthlyType 月报类型
  701. * @param reportData 报告解析结果
  702. * @param fileName 报告名称
  703. * @param senderEmail 邮件发送人邮箱
  704. * @param images 报告的收益和尾页png图片
  705. */
  706. private ReportData ocrReportData(Integer fileId,
  707. ReportType reportType,
  708. ReportMonthlyType monthlyType,
  709. ReportData reportData,
  710. String fileName,
  711. String senderEmail,
  712. List<String> images) {
  713. if (CollUtil.isEmpty(images)) {
  714. return reportData;
  715. }
  716. // 报告才识别尾页的印章和联系人,确认单不识别尾页
  717. if (ReportType.LETTER != reportType) {
  718. if (log.isInfoEnabled()) {
  719. log.info("报告{} 用ocr补充解析结果。补充前的结果是:{}", fileName, reportData);
  720. }
  721. OCRParseData parseRes = null;
  722. try {
  723. // 首页和尾页相等时只读首页
  724. String imageUrl = images.size() == 1 ? images.get(0) : images.get(1);
  725. parseRes = new OCRReportParser().parse(fileName, this.ocrParserUrl, imageUrl);
  726. } catch (Exception e) {
  727. log.error("报告{} OCR识别印章和联系人出错:{}", fileName, e.getMessage());
  728. }
  729. // ocr识别尾页是否包含印章和联系人信息
  730. if (parseRes != null && reportData.getBaseInfo() != null) {
  731. // 协会报告才设置印章标识
  732. boolean isAmac = reportType == ReportType.ANNUALLY || reportType == ReportType.QUARTERLY
  733. || (reportType == ReportType.MONTHLY && ReportMonthlyType.AMAC == monthlyType);
  734. if (isAmac) {
  735. if (TG_EMAIL_LIST.contains(senderEmail)) {
  736. reportData.getBaseInfo().setWithSeals(true);
  737. } else {
  738. reportData.getBaseInfo().setWithSeals(parseRes.getWithSeals());
  739. if (fileName.contains("用印") && !Objects.equals(true, reportData.getBaseInfo().getWithSeals())) {
  740. reportData.getBaseInfo().setWithSeals(true);
  741. }
  742. }
  743. } else {
  744. // 管理人报告才设置联系人标识
  745. reportData.getBaseInfo().setWithContacts(parseRes.getWithContacts());
  746. }
  747. }
  748. // 首页和尾页不相等时解析首页的数据
  749. if (images.size() != 1 || parseRes == null) {
  750. try {
  751. parseRes = new OCRReportParser().parse(fileName, this.ocrParserUrl, images.get(0));
  752. } catch (Exception e) {
  753. log.error("报告{} OCR识别首页基金名称和报告日期出错:{}", fileName, e.getMessage());
  754. }
  755. }
  756. // 用首页识别基金名称、产品代码和基金管理人
  757. if (reportData.getFundInfo() != null && parseRes != null) {
  758. if (StrUtil.isBlank(reportData.getFundInfo().getFundName())) {
  759. reportData.getFundInfo().setFundName(parseRes.getFundName());
  760. }
  761. if (StrUtil.isBlank(reportData.getFundInfo().getFundCode())) {
  762. reportData.getFundInfo().setFundCode(parseRes.getFundCode());
  763. }
  764. if (StrUtil.isBlank(reportData.getFundInfo().getCompanyName())
  765. || !reportData.getFundInfo().getCompanyName().contains("有限公司")) {
  766. reportData.getFundInfo().setCompanyName(parseRes.getCompanyName());
  767. }
  768. }
  769. reportData.setAiParse(true);
  770. return reportData;
  771. }
  772. // 确认单AI解析失败时重新用OCR识别
  773. if (!reportData.wasFailed()) {
  774. return reportData;
  775. }
  776. if (log.isInfoEnabled()) {
  777. log.info("确认单报告{} 用ocr补充解析结果。补充前的结果是:{}", fileName, reportData);
  778. }
  779. LetterReportData letterReportData = (LetterReportData) reportData;
  780. OCRLetterParseData parseRes = null;
  781. try {
  782. parseRes = new OCRReportParser().parseLetterData(fileName, this.ocrParserUrl, images.get(0));
  783. } catch (Exception e) {
  784. log.error("确认单报告{} OCR提取确认单关键信息出错:{}", fileName, e.getMessage());
  785. }
  786. if (parseRes == null) {
  787. return reportData;
  788. }
  789. if (letterReportData.getFundInfo() != null) {
  790. letterReportData.getFundInfo().setFundName(parseRes.getFundName());
  791. letterReportData.getFundInfo().setFundCode(parseRes.getFundCode());
  792. }
  793. // 投资者信息
  794. if (letterReportData.getInvestorInfo() == null) {
  795. letterReportData.setInvestorInfo(new ReportInvestorInfoDTO(fileId));
  796. }
  797. letterReportData.getInvestorInfo().setInvestorName(parseRes.getInvestorName());
  798. letterReportData.getInvestorInfo().setCertificateNumber(parseRes.getCertificateNumber());
  799. letterReportData.getInvestorInfo().setTradingAccount(parseRes.getTradingAccount());
  800. letterReportData.getInvestorInfo().setFundAccount(parseRes.getFundAccount());
  801. letterReportData.getInvestorInfo().setCertificateType(parseRes.getCertificateType());
  802. // 交易流水
  803. if (letterReportData.getTransaction() == null) {
  804. letterReportData.setTransaction(new ReportFundTransactionDTO(fileId));
  805. }
  806. letterReportData.getTransaction().setTransactionType(parseRes.getTransactionType());
  807. letterReportData.getTransaction().setApplyDate(parseRes.getApplyDate());
  808. letterReportData.getTransaction().setApplyShare(parseRes.getApplyShare());
  809. letterReportData.getTransaction().setApplyAmount(parseRes.getApplyAmount());
  810. letterReportData.getTransaction().setHoldingDate(parseRes.getHoldingDate());
  811. letterReportData.getTransaction().setAmount(parseRes.getAmount());
  812. letterReportData.getTransaction().setShare(parseRes.getShare());
  813. letterReportData.getTransaction().setNav(parseRes.getNav());
  814. letterReportData.setAiParse(true);
  815. return letterReportData;
  816. }
  817. /**
  818. * 当reportData==null时重新构建一个新对象
  819. *
  820. * @param fileId 文件ID
  821. * @param reportType 报告类型
  822. * @param reportName 报告名称
  823. * @return /
  824. */
  825. private ReportData buildNvlReportData(Integer fileId, ReportType reportType, String reportName) {
  826. ReportData reportData = null;
  827. if (reportType == null) {
  828. reportType = ReportType.OTHER;
  829. }
  830. ReportBaseInfoDTO baseInfo = new ReportBaseInfoDTO(fileId);
  831. baseInfo.setReportName(reportName);
  832. baseInfo.setReportType(reportType.name());
  833. String reportDate = ReportParseUtils.matchReportDate(reportType, reportName);
  834. baseInfo.setReportDate(ConvertUtil.toDate(reportDate));
  835. ReportFundInfoDTO fundInfo = new ReportFundInfoDTO(fileId);
  836. if (ReportType.ANNUALLY == reportType) {
  837. reportData = new AnnuallyReportData(baseInfo, fundInfo);
  838. } else if (ReportType.QUARTERLY == reportType) {
  839. reportData = new QuarterlyReportData(baseInfo, fundInfo);
  840. } else if (ReportType.MONTHLY == reportType) {
  841. reportData = new MonthlyReportData(baseInfo, fundInfo);
  842. } else if (ReportType.WEEKLY == reportType) {
  843. reportData = new WeeklyReportData(baseInfo, fundInfo);
  844. } else if (ReportType.OTHER == reportType) {
  845. reportData = new ReportData.DefaultReportData(baseInfo, fundInfo);
  846. } else if (ReportType.LETTER == reportType) {
  847. reportData = new LetterReportData(baseInfo, fundInfo);
  848. }
  849. return reportData;
  850. }
  851. /**
  852. * 保存报告解析结果
  853. *
  854. * @param reportData 报告解析结果
  855. * @param reportType 报告类型
  856. * @param fileName 报告名称
  857. */
  858. private void saveReportData(ReportData reportData, ReportType reportType, String fileName) {
  859. if (reportData == null) {
  860. return;
  861. }
  862. StopWatch writeWatch = new StopWatch();
  863. writeWatch.start();
  864. try {
  865. ReportWriter<ReportData> instance = this.reportWriterFactory.getInstance(reportType);
  866. instance.write(reportData);
  867. } catch (Exception e) {
  868. log.error("报告{} 结果保存失败 {}", fileName, ExceptionUtil.stacktraceToString(e));
  869. } finally {
  870. writeWatch.stop();
  871. if (log.isInfoEnabled()) {
  872. log.info("报告{} 解析结果保存完成,耗时{}ms", fileName, writeWatch.getTotalTimeMillis());
  873. }
  874. }
  875. }
  876. private EmailFileInfoDO saveEmailFileInfo(Integer emailId, String fileName, String filePath) {
  877. EmailFileInfoDO emailFileInfoDO = buildEmailFileInfoDO(emailId, fileName, filePath);
  878. // emailFileInfoDO.setAiFileId(null);
  879. if (emailFileInfoDO.getId() != null) {
  880. this.emailFileInfoMapper.updateTimeById(emailFileInfoDO.getId(), new Date());
  881. return emailFileInfoDO;
  882. }
  883. LambdaQueryWrapper<EmailFileInfoDO> wrapper = Wrappers.lambdaQuery(EmailFileInfoDO.class)
  884. .eq(EmailFileInfoDO::getEmailId, emailId)
  885. .eq(EmailFileInfoDO::getFileName, fileName)
  886. .eq(EmailFileInfoDO::getFilePath, filePath);
  887. List<EmailFileInfoDO> tempList = this.emailFileInfoMapper.selectList(wrapper);
  888. if (CollUtil.isNotEmpty(tempList)) {
  889. return tempList.get(0);
  890. }
  891. this.emailFileInfoMapper.insertById(emailFileInfoDO);
  892. return emailFileInfoDO;
  893. }
  894. private EmailFileInfoDO buildEmailFileInfoDO(Integer emailId, String fileName, String filePath) {
  895. EmailFileInfoDO emailFileInfoDO = new EmailFileInfoDO();
  896. emailFileInfoDO.setId(null);
  897. emailFileInfoDO.setEmailId(emailId);
  898. emailFileInfoDO.setFileName(fileName);
  899. emailFileInfoDO.setFilePath(filePath);
  900. emailFileInfoDO.setIsvalid(1);
  901. emailFileInfoDO.setCreatorId(0);
  902. emailFileInfoDO.setCreateTime(new Date());
  903. emailFileInfoDO.setUpdaterId(0);
  904. emailFileInfoDO.setUpdateTime(new Date());
  905. return emailFileInfoDO;
  906. }
  907. private Integer saveEmailParseInfo(EmailParseInfoDO emailParseInfoDO) {
  908. if (emailParseInfoDO == null) {
  909. return null;
  910. }
  911. // 重新邮件功能 -> 修改解析时间和更新时间
  912. if (emailParseInfoDO.getId() != null) {
  913. this.emailParseInfoMapper.updateParseTime(emailParseInfoDO.getId(), emailParseInfoDO.getParseDate());
  914. return emailParseInfoDO.getId();
  915. }
  916. LambdaQueryWrapper<EmailParseInfoDO> wrapper = Wrappers.lambdaQuery(EmailParseInfoDO.class)
  917. .eq(EmailParseInfoDO::getEmailTitle, emailParseInfoDO.getEmailTitle())
  918. .eq(EmailParseInfoDO::getSenderEmail, emailParseInfoDO.getSenderEmail())
  919. .eq(EmailParseInfoDO::getEmailDate, emailParseInfoDO.getEmailDate())
  920. .eq(EmailParseInfoDO::getEmail, emailParseInfoDO.getEmail())
  921. .orderByDesc(EmailParseInfoDO::getId);
  922. List<EmailParseInfoDO> tempList = this.emailParseInfoMapper.selectList(wrapper);
  923. if (CollUtil.isNotEmpty(tempList)) {
  924. this.emailParseInfoMapper.update(emailParseInfoDO, wrapper);
  925. return tempList.get(0).getId();
  926. }
  927. this.emailParseInfoMapper.insertAndId(emailParseInfoDO);
  928. return emailParseInfoDO.getId();
  929. }
  930. private EmailParseInfoDO buildEmailParseInfo(String emailAddress, EmailInfoDTO emailInfo, long totalSize) {
  931. EmailParseInfoDO emailParseInfoDO = new EmailParseInfoDO();
  932. emailParseInfoDO.setId(null);
  933. emailParseInfoDO.setSenderEmail(emailInfo.getSenderEmail());
  934. emailParseInfoDO.setEmail(emailAddress);
  935. emailParseInfoDO.setEmailDate(DateUtil.parse(emailInfo.getEmailDate(), DateConst.YYYY_MM_DD_HH_MM_SS));
  936. emailParseInfoDO.setParseDate(new Date());
  937. emailParseInfoDO.setEmailTitle(emailInfo.getEmailTitle());
  938. emailParseInfoDO.setParseStatus(EmailParseStatusConst.SUCCESS);
  939. emailParseInfoDO.setAttrSize(totalSize);
  940. emailParseInfoDO.setIsvalid(1);
  941. emailParseInfoDO.setCreatorId(0);
  942. emailParseInfoDO.setCreateTime(new Date());
  943. emailParseInfoDO.setUpdaterId(0);
  944. emailParseInfoDO.setUpdateTime(new Date());
  945. return emailParseInfoDO;
  946. }
  947. /**
  948. * 读取邮件
  949. *
  950. * @param mailboxInfoDTO 邮箱配置信息
  951. * @param startDate 邮件起始日期
  952. * @param endDate 邮件截止日期(为null,将解析邮件日期小于等于startDate的当天邮件)
  953. * @return 读取到的邮件信息
  954. * @throws Exception 异常信息
  955. */
  956. private Map<String, List<EmailContentInfoDTO>> realEmail(MailboxInfoDTO mailboxInfoDTO,
  957. Date startDate, Date endDate,
  958. List<String> folderNames) throws Exception {
  959. if (CollUtil.isEmpty(folderNames)) {
  960. folderNames = ListUtil.toList("INBOX");
  961. }
  962. Store store = EmailUtil.getStoreNew(mailboxInfoDTO);
  963. if (store == null) {
  964. return MapUtil.newHashMap(4);
  965. }
  966. Map<String, List<EmailContentInfoDTO>> result = MapUtil.newHashMap(128);
  967. try {
  968. if (log.isDebugEnabled()) {
  969. Folder[] list = store.getDefaultFolder().list("*");
  970. List<String> names = Arrays.stream(list).map(Folder::getFullName).toList();
  971. log.debug("获取所有邮箱文件夹:{}", names);
  972. }
  973. for (String folderName : folderNames) {
  974. try {
  975. Map<String, List<EmailContentInfoDTO>> temp = this.getFolderEmail(mailboxInfoDTO,
  976. startDate, endDate, store, folderName);
  977. if (MapUtil.isNotEmpty(temp)) {
  978. result.putAll(temp);
  979. }
  980. } catch (Exception e) {
  981. log.warn("文件夹{} 邮件获取失败:{}", folderName, ExceptionUtil.stacktraceToString(e));
  982. }
  983. }
  984. } catch (Exception e) {
  985. log.error("邮件获取失败:{}", ExceptionUtil.stacktraceToString(e));
  986. } finally {
  987. store.close();
  988. }
  989. return result;
  990. }
  991. private Map<String, List<EmailContentInfoDTO>> getFolderEmail(MailboxInfoDTO mailboxInfoDTO,
  992. Date startDate, Date endDate,
  993. Store store, String folderName) throws MessagingException {
  994. // 默认读取收件箱的邮件
  995. Folder folder = store.getFolder(folderName);
  996. folder.open(this.readWriteSeen ? Folder.READ_WRITE : Folder.READ_ONLY);
  997. Message[] messages = getEmailMessage(folder, mailboxInfoDTO.getProtocol(), startDate);
  998. if (messages == null || messages.length == 0) {
  999. log.warn("{} 获取不到邮件 -> 邮箱信息:{},开始时间:{},结束时间:{}", folderName, mailboxInfoDTO, startDate, endDate);
  1000. return MapUtil.newHashMap();
  1001. }
  1002. String emailAddress = mailboxInfoDTO.getAccount();
  1003. Map<String, List<EmailContentInfoDTO>> emailMessageMap = MapUtil.newHashMap();
  1004. for (Message message : messages) {
  1005. long start = System.currentTimeMillis();
  1006. List<EmailContentInfoDTO> dtos = CollUtil.newArrayList();
  1007. String emailTitle = message.getSubject();
  1008. if (this.readWriteSeen && isMessageRead(message)) {
  1009. log.warn("{} 邮件{} 已读,不用重新下载解析!", folderName, emailTitle);
  1010. continue;
  1011. }
  1012. try {
  1013. Date emailDate = message.getSentDate();
  1014. String emailDateStr = DateUtil.format(emailDate, DateConst.YYYY_MM_DD_HH_MM_SS);
  1015. if (log.isInfoEnabled()) {
  1016. log.info("{} 邮件{} 数据获取中,邮件时间:{}", folderName, emailTitle, emailDateStr);
  1017. }
  1018. boolean isNotParseConditionSatisfied = emailDate == null
  1019. || (endDate != null && emailDate.compareTo(endDate) > 0)
  1020. || (startDate != null && emailDate.compareTo(startDate) < 0);
  1021. if (isNotParseConditionSatisfied) {
  1022. String st = DateUtil.formatDateTime(startDate);
  1023. String ed = DateUtil.formatDateTime(endDate);
  1024. log.warn("{} 邮件{} 发送时间{}不在区间内【{} ~ {}】", folderName, emailTitle, emailDateStr, st, ed);
  1025. continue;
  1026. }
  1027. String senderEmail = getSenderEmail(message);
  1028. Integer emailType = EmailUtil.getEmailTypeBySubject(emailTitle);
  1029. if (emailType == null) {
  1030. log.warn("{} 邮件不满足解析条件 -> 邮件主题:{},邮件日期:{}", folderName, emailTitle, emailDateStr);
  1031. continue;
  1032. }
  1033. // // 成功解析的邮件不用重复下载
  1034. // Integer okNum = this.emailParseInfoMapper.countEmailByInfoAndStatus(emailTitle, senderEmail, emailAddress, emailDateStr);
  1035. // if (okNum > 0) {
  1036. // if (log.isInfoEnabled()) {
  1037. // log.info("{} 邮件{} 已经存在解析完成的记录,不要重复下载了。", folderName, emailTitle);
  1038. // }
  1039. // continue;
  1040. // }
  1041. if (log.isInfoEnabled()) {
  1042. log.info("{} 邮件{} 基本信息获取完成,开始下载附件!邮件日期:{}", folderName, emailTitle, emailDateStr);
  1043. }
  1044. Object messageContent = message.getContent();
  1045. String[] contents = new String[]{null};
  1046. if (messageContent instanceof Multipart multipart) {
  1047. this.reMultipart(emailAddress, emailTitle, emailDate, multipart, contents, dtos);
  1048. } else {
  1049. log.warn("{} 邮件{} 获取不了附件", folderName, emailTitle);
  1050. }
  1051. if (CollUtil.isEmpty(dtos)) {
  1052. log.warn("{} 邮件{} 没有获取到附件", folderName, emailTitle);
  1053. continue;
  1054. }
  1055. dtos.forEach(e -> {
  1056. e.setEmailType(emailType);
  1057. e.setSenderEmail(senderEmail);
  1058. e.setEmailContent(contents[0]);
  1059. });
  1060. emailMessageMap.put(IdUtil.simpleUUID(), dtos);
  1061. } catch (Exception e) {
  1062. log.error("{} 邮件{} 下载报错 {}", folderName, emailTitle, ExceptionUtil.stacktraceToString(e));
  1063. } finally {
  1064. if (CollUtil.isNotEmpty(dtos) && log.isInfoEnabled()) {
  1065. log.info("{} 邮件{} 下载完成,总计耗时{} ms,文件内容如下\n {}", folderName,
  1066. emailTitle, System.currentTimeMillis() - start, dtos);
  1067. }
  1068. }
  1069. }
  1070. if (this.readWriteSeen) {
  1071. // 设置已读标志
  1072. folder.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
  1073. }
  1074. folder.close(false);
  1075. return emailMessageMap;
  1076. }
  1077. private void rePart(String account, String subject, Date sendDate, Part part,
  1078. List<EmailContentInfoDTO> emailContentInfoDTOList) throws Exception {
  1079. String fileName = EmailUtil.decodeFileName(part);
  1080. if (StrUtil.isBlank(fileName)) {
  1081. return;
  1082. }
  1083. if (fileName.contains("\"") || fileName.contains("\n")) {
  1084. fileName = fileName.replaceAll("\"", "").replaceAll("\n", "");
  1085. }
  1086. if (fileName.contains("=?")) {
  1087. fileName = MimeUtility.decodeText(fileName);
  1088. }
  1089. String disposition = part.getDisposition();
  1090. String contentType = part.getContentType();
  1091. String[] att_files = new String[]{Constants.ARCHIVE_7Z, Constants.ARCHIVE_RAR, Constants.ARCHIVE_ZIP,
  1092. Constants.FILE_PDF, Constants.FILE_DOCX, Constants.FILE_JPG, Constants.FILE_PNG};
  1093. boolean attachmentFlag = StrUtil.endWithAny(fileName, att_files);
  1094. boolean isAttachment = attachmentFlag
  1095. || Part.ATTACHMENT.equalsIgnoreCase(disposition)
  1096. || (contentType != null && attachmentMimePrefixes.stream().anyMatch(prefix ->
  1097. StrUtil.startWithIgnoreCase(contentType, prefix)
  1098. ));
  1099. if (!isAttachment) {
  1100. log.warn("邮件{} 未检测到{}类型的附件 (fileName={}, disposition={}, contentType={})",
  1101. subject, att_files, fileName, disposition, contentType);
  1102. return;
  1103. }
  1104. File saveFile = this.generateSavePath(account, sendDate, fileName);
  1105. if (!saveFile.exists()) {
  1106. if (!saveFile.getParentFile().exists()) {
  1107. boolean mkdirs = saveFile.getParentFile().mkdirs();
  1108. if (!mkdirs) {
  1109. log.warn("file path mkdir failed.");
  1110. }
  1111. }
  1112. try (InputStream is = part.getInputStream()) {
  1113. Files.copy(is, saveFile.toPath());
  1114. }
  1115. } else {
  1116. if (log.isInfoEnabled()) {
  1117. log.info("邮件{} 已下载过附件:{},不用重新下载了。", subject, saveFile.toPath());
  1118. }
  1119. }
  1120. EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
  1121. emailContentInfoDTO.setFileName(fileName);
  1122. emailContentInfoDTO.setFileSize(part.getSize());
  1123. emailContentInfoDTO.setFilePath(saveFile.getAbsolutePath());
  1124. emailContentInfoDTO.setEmailAddress(account);
  1125. emailContentInfoDTO.setEmailTitle(subject);
  1126. emailContentInfoDTO.setEmailDate(DateUtil.format(sendDate, DateConst.YYYY_MM_DD_HH_MM_SS));
  1127. emailContentInfoDTOList.add(emailContentInfoDTO);
  1128. }
  1129. public File generateSavePath(String account, Date sendDate, String fileName) {
  1130. String emailDateStr = DateUtil.format(sendDate, DateConst.YYYYMMDD);
  1131. String filePath = this.path + File.separator + account + File.separator +
  1132. emailDateStr + File.separator + "original" + File.separator;
  1133. // 压缩包重名时的后面的压缩包会覆盖前面压缩包的问题(不考虑普通文件)
  1134. String emailDate = DateUtil.format(sendDate, DateConst.YYYYMMDDHHMMSS24);
  1135. String realName = ArchiveUtil.isArchive(fileName) ? emailDate + fileName : fileName;
  1136. return FileUtil.file(filePath + realName);
  1137. }
  1138. private void reMultipart(String account, String subject, Date emailDate,
  1139. Multipart multipart, String[] contents,
  1140. List<EmailContentInfoDTO> emailContentInfoDTOList) throws Exception {
  1141. for (int i = 0; i < multipart.getCount(); i++) {
  1142. Part bodyPart = multipart.getBodyPart(i);
  1143. Object bodyPartContent = bodyPart.getContent();
  1144. if (bodyPartContent instanceof String) {
  1145. if (log.isDebugEnabled()) {
  1146. log.debug("邮件{} 获取的正文不做解析,内容是 {}", subject, bodyPartContent);
  1147. }
  1148. if (StrUtil.startWithIgnoreCase(bodyPart.getContentType(), MediaType.TEXT_PLAIN_VALUE)) {
  1149. contents[0] = bodyPartContent.toString();
  1150. }
  1151. continue;
  1152. }
  1153. if (bodyPartContent instanceof Multipart mp) {
  1154. this.reMultipart(account, subject, emailDate, mp, contents, emailContentInfoDTOList);
  1155. } else {
  1156. this.rePart(account, subject, emailDate, bodyPart, emailContentInfoDTOList);
  1157. }
  1158. }
  1159. }
  1160. private String getSenderEmail(Message message) {
  1161. Address[] senderAddress;
  1162. try {
  1163. senderAddress = message.getFrom();
  1164. if (senderAddress == null || senderAddress.length == 0) {
  1165. return null;
  1166. }
  1167. // 此时的address是含有编码(MIME编码方式)后的文本和实际的邮件地址
  1168. String address = "";
  1169. for (Address from : senderAddress) {
  1170. if (StrUtil.isNotBlank(from.toString())) {
  1171. address = from.toString();
  1172. break;
  1173. }
  1174. }
  1175. // 正则表达式匹配邮件地址
  1176. Pattern pattern = Pattern.compile("<(\\S+)>");
  1177. Matcher matcher = pattern.matcher(address);
  1178. if (matcher.find()) {
  1179. return matcher.group(1);
  1180. }
  1181. } catch (MessagingException e) {
  1182. log.error(e.getMessage(), e);
  1183. }
  1184. return null;
  1185. }
  1186. private Message[] getEmailMessage(Folder folder, String protocol, Date startDate) {
  1187. try {
  1188. if (protocol.contains("imap")) {
  1189. // 获取邮件日期大于等于startDate的邮件(搜索条件只支持按天)
  1190. SearchTerm startDateTerm = new ReceivedDateTerm(ComparisonTerm.GE, startDate);
  1191. return folder.search(startDateTerm);
  1192. } else {
  1193. return folder.getMessages();
  1194. }
  1195. } catch (MessagingException e) {
  1196. throw new RuntimeException(e);
  1197. }
  1198. }
  1199. /**
  1200. * 检查邮件是否已读
  1201. *
  1202. * @param message 邮件对象
  1203. * @return true表示已读,false表示未读
  1204. * @throws MessagingException 如果访问邮件标志时出错
  1205. */
  1206. private boolean isMessageRead(Message message) throws MessagingException {
  1207. // 获取邮件的所有标志
  1208. Flags flags = message.getFlags();
  1209. // 检查是否包含 SEEN 标志
  1210. return flags.contains(Flags.Flag.SEEN);
  1211. }
  1212. }