DocumentAuthServiceImpl.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package com.caimei.www.service.page.impl;
  2. import com.aliyun.oss.OSS;
  3. import com.aliyun.oss.OSSClientBuilder;
  4. import com.aliyun.oss.model.GetObjectRequest;
  5. import com.aliyun.oss.model.OSSObject;
  6. import com.caimei.www.mapper.DocumentAuthDao;
  7. import com.caimei.www.pojo.JsonModel;
  8. import com.caimei.www.pojo.document.CookieBuilder;
  9. import com.caimei.www.pojo.document.OssArchive;
  10. import com.caimei.www.pojo.document.OssArchivePdf;
  11. import com.caimei.www.pojo.document.OssAuthorization;
  12. import com.caimei.www.service.page.DocumentAuthService;
  13. import com.caimei.www.service.redis.RedisService;
  14. import com.caimei.www.utils.ImageUtil;
  15. import com.caimei.www.utils.RandomCodeGenerator;
  16. import com.caimei.www.utils.SMSUtils;
  17. import com.caimei.www.utils.VerifyCodeUtils;
  18. import com.github.pagehelper.PageHelper;
  19. import com.github.pagehelper.PageInfo;
  20. import lombok.extern.slf4j.Slf4j;
  21. import org.springframework.beans.factory.annotation.Value;
  22. import org.springframework.http.*;
  23. import org.springframework.http.server.reactive.ServerHttpRequest;
  24. import org.springframework.http.server.reactive.ServerHttpResponse;
  25. import org.springframework.stereotype.Service;
  26. import org.springframework.util.StringUtils;
  27. import reactor.core.publisher.Mono;
  28. import javax.annotation.Resource;
  29. import java.io.BufferedReader;
  30. import java.io.File;
  31. import java.io.IOException;
  32. import java.io.InputStreamReader;
  33. import java.nio.charset.StandardCharsets;
  34. import java.util.Date;
  35. import java.util.HashMap;
  36. import java.util.List;
  37. import java.util.Map;
  38. /**
  39. * Description
  40. *
  41. * @author : plf
  42. * @date : 2020/11/10
  43. */
  44. @Slf4j
  45. @Service
  46. public class DocumentAuthServiceImpl implements DocumentAuthService {
  47. @Resource
  48. private DocumentAuthDao documentAuthDao;
  49. @Resource
  50. private RedisService redisService;
  51. @Value("${caimei.wwwDomain}")
  52. private String domain;
  53. @Value("${aliyun.accessKeyId}")
  54. private String accessKeyId;
  55. @Value("${aliyun.accessKeySecret}")
  56. private String accessKeySecret;
  57. @Value("${aliyun.bucketName}")
  58. private String bucketName;
  59. @Value("${aliyun.endpoint}")
  60. private String endpoint;
  61. @Override
  62. public Boolean getAuthorizationCookie(String authorizationMobile) {
  63. if (!StringUtils.isEmpty(authorizationMobile)) {
  64. OssAuthorization ossAuthorization = documentAuthDao.findOssAuthorizationByMobile(authorizationMobile);
  65. return ossAuthorization != null;
  66. }
  67. return false;
  68. }
  69. @Override
  70. public Mono<JsonModel> getImgVerifyCode() {
  71. Map<String, Object> jsonResult = new HashMap<>(2);
  72. try {
  73. VerifyCodeUtils.VerifyCode verifyCode = null;
  74. String verifyCodeKey = "";
  75. while (true) {
  76. verifyCode = VerifyCodeUtils.createVerifyCode(200, 80, 4);
  77. verifyCodeKey = "www:oss:" + verifyCode.getMd5Code();
  78. boolean exists = redisService.exists(verifyCodeKey);
  79. // 不存在,为了防止重复的图片验证码
  80. if (!exists) {
  81. // 保存5分钟
  82. redisService.set(verifyCodeKey, verifyCode.getCode(), 5 * 60L);
  83. break;
  84. }
  85. }
  86. jsonResult.put("baseImage", verifyCode.getBase64Image());
  87. jsonResult.put("token", verifyCode.getMd5Code());
  88. return Mono.just(JsonModel.success(jsonResult));
  89. } catch (Exception e) {
  90. return Mono.just(JsonModel.error("验证码获取失败"));
  91. }
  92. }
  93. @Override
  94. public Mono<JsonModel> ossNote(String mobile, String imgCode, String token) {
  95. String code = (String) redisService.get("www:oss:" + token);
  96. String mobileCode = RandomCodeGenerator.generateCodeInt(6);
  97. //手机验证码,30分钟有效
  98. redisService.set(mobile + ":mobileCode", mobileCode, 30 * 60L);
  99. String content = "采美资料库访问授权验证码:" + mobileCode + ",30分钟内有效";
  100. if (!StringUtils.isEmpty(code) && code.equalsIgnoreCase(imgCode)) {
  101. log.info("采美资料库访问授权验证码>>>>>" + mobileCode);
  102. boolean sms = SMSUtils.sendSms(mobile, content);
  103. if (sms) {
  104. return Mono.just(JsonModel.success());
  105. }
  106. } else {
  107. boolean exists = redisService.exists(mobile + ":mobileCode");
  108. if (exists) {
  109. redisService.remove(mobile + ":mobileCode");
  110. }
  111. }
  112. return Mono.just(JsonModel.error("验证码不正确"));
  113. }
  114. @Override
  115. public ResponseEntity<JsonModel> mobileCodeLogin(OssAuthorization authorization) {
  116. HttpHeaders headers = new HttpHeaders();
  117. if (StringUtils.isEmpty(authorization.getMobile()) || StringUtils.isEmpty(authorization.getCode())) {
  118. return new ResponseEntity<>(JsonModel.error("参数异常"), headers, HttpStatus.OK);
  119. }
  120. String mobileCode = (String) redisService.get(authorization.getMobile() + ":mobileCode");
  121. if (!StringUtils.isEmpty(mobileCode) && authorization.getCode().equals(mobileCode)) {
  122. OssAuthorization ossAuthorization = documentAuthDao.findOssAuthorizationByMobile(authorization.getMobile());
  123. if (ossAuthorization != null) {
  124. String cookie = new CookieBuilder().setKey("authorizationMobile")
  125. .setValue(authorization.getMobile())
  126. .setMaxAge(60 * 60 * 24 * 30 * 1000L)
  127. .setPath("/")
  128. .build();
  129. headers.add("Set-Cookie", cookie);
  130. return new ResponseEntity<>(JsonModel.success(), headers, HttpStatus.OK);
  131. } else {
  132. return new ResponseEntity<>(JsonModel.error(-2, "登录失败,您可能没有查看资料的权限"), headers, HttpStatus.OK);
  133. }
  134. } else {
  135. return new ResponseEntity<>(JsonModel.error("短信验证码不正确"), headers, HttpStatus.OK);
  136. }
  137. }
  138. @Override
  139. public Mono<JsonModel> dataList(String name, Integer pageNum, Integer pageSize) {
  140. pageNum = pageNum == null ? 1 : pageNum;
  141. pageSize = pageSize == null ? 20 : pageSize;
  142. PageHelper.startPage(pageNum, pageSize);
  143. List<OssArchive> ossArchiveList = documentAuthDao.findOssArchive(name);
  144. PageInfo<OssArchive> pageInfo = null;
  145. if (ossArchiveList != null && ossArchiveList.size() > 0) {
  146. for (OssArchive ossArchive : ossArchiveList) {
  147. if (!StringUtils.isEmpty(ossArchive.getMainImage())) {
  148. ossArchive.setMainImage(ImageUtil.getImageURL("product", ossArchive.getMainImage(), 0, domain));
  149. }
  150. List<OssArchivePdf> pdfList = documentAuthDao.findOssArchivePdf(ossArchive.getId());
  151. if (pdfList != null && pdfList.size() > 0) {
  152. ossArchive.setIsShowDowns(false);
  153. } else {
  154. ossArchive.setIsShowDowns(true);
  155. }
  156. ossArchive.setPdfList(pdfList);
  157. }
  158. pageInfo = new PageInfo<>(ossArchiveList);
  159. }
  160. return Mono.just(JsonModel.success(pageInfo));
  161. }
  162. @Override
  163. public Mono<JsonModel> dataDetails(Integer pdfId) {
  164. Map<String, Object> map = new HashMap<>(2);
  165. OssArchivePdf ossArchivePdf = documentAuthDao.findOssArchivePdfById(pdfId);
  166. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
  167. // 设置URL过期时间为1个小时
  168. Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000);
  169. String url = ossClient.generatePresignedUrl(bucketName, ossArchivePdf.getOssName(), expiration).toString();
  170. ossArchivePdf.setUrl(url);
  171. OssArchive ossArchive = documentAuthDao.getOssArchive(ossArchivePdf.getArchiveId());
  172. if (!StringUtils.isEmpty(ossArchive.getMainImage())) {
  173. ossArchive.setMainImage(ImageUtil.getImageURL("product", ossArchive.getMainImage(), 0, domain));
  174. }
  175. map.put("ossArchivePdf", ossArchivePdf);
  176. map.put("ossArchive", ossArchive);
  177. ossClient.shutdown();
  178. return Mono.just(JsonModel.success(map));
  179. }
  180. @Override
  181. public Mono<JsonModel> moreData(Integer archiveId) {
  182. OssArchive ossArchive = documentAuthDao.getOssArchive(archiveId);
  183. if (ossArchive != null) {
  184. if (!StringUtils.isEmpty(ossArchive.getMainImage())) {
  185. ossArchive.setMainImage(ImageUtil.getImageURL("product", ossArchive.getMainImage(), 0, domain));
  186. }
  187. List<OssArchivePdf> pdfList = documentAuthDao.findOssArchivePdf(ossArchive.getId());
  188. ossArchive.setPdfList(pdfList);
  189. }
  190. return Mono.just(JsonModel.success(ossArchive));
  191. }
  192. @Override
  193. public Mono<Void> downFile(Integer pdfId, ServerHttpRequest request, ServerHttpResponse response) {
  194. try {
  195. OssArchivePdf ossArchivePdf = documentAuthDao.findOssArchivePdfById(pdfId);
  196. // 创建OSSClient实例。
  197. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
  198. File file = new File("src/main/resources/static/file");
  199. if (!file.exists()) {
  200. file.mkdir();
  201. }
  202. // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
  203. ossClient.getObject(new GetObjectRequest(bucketName, ossArchivePdf.getOssName()), new File("src/main/resources/static/file/" + ossArchivePdf.getName()));
  204. // 关闭OSSClient。
  205. ossClient.shutdown();
  206. File pdfFile = new File("src/main/resources/static/file/" + ossArchivePdf.getName());
  207. //输出文件名乱码问题处理
  208. response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION,
  209. "attachment; filename=" + new String(pdfFile.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
  210. ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
  211. response.getHeaders().setContentType(MediaType.APPLICATION_PDF);
  212. return zeroCopyResponse.writeWith(pdfFile, 0, pdfFile.length());
  213. } catch (Exception e) {
  214. e.printStackTrace();
  215. return Mono.error(e);
  216. }
  217. }
  218. @Override
  219. public void deleteFile() {
  220. File file = new File("src/main/resources/static/file");
  221. //取得这个目录下的所有子文件对象
  222. File[] files = file.listFiles();
  223. //遍历该目录下的文件对象
  224. if (files != null && files.length > 0) {
  225. for (File f : files) {
  226. //打印文件名
  227. String name = file.getName();
  228. log.info("定时删除服务器临时文件,文件名>>>>>" + name);
  229. //判断子目录是否存在子目录,如果是文件则删除
  230. f.delete();
  231. }
  232. }
  233. //删除空文件夹
  234. file.delete();
  235. }
  236. @Override
  237. public Mono<JsonModel> downFileAll(Integer pdfId) {
  238. StringBuilder date = new StringBuilder();
  239. try {
  240. OssArchivePdf ossArchivePdf = documentAuthDao.findOssArchivePdfById(pdfId);
  241. // 创建OSSClient实例。
  242. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
  243. // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
  244. OSSObject ossObject = ossClient.getObject(bucketName, ossArchivePdf.getOssName());
  245. // 读取文件内容。
  246. System.out.println("Object content:");
  247. BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
  248. while (true) {
  249. String line = reader.readLine();
  250. if (line == null) {
  251. break;
  252. }
  253. date.append(line);
  254. }
  255. // 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
  256. reader.close();
  257. // 关闭OSSClient。
  258. ossClient.shutdown();
  259. } catch (IOException e) {
  260. e.printStackTrace();
  261. }
  262. return Mono.just(JsonModel.success(JsonModel.success(date)));
  263. }
  264. }