EmailParseService.java 60 KB

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