AuthServiceImpl.java 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. package com.caimei.service.auth.impl;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.caimei.components.RedisService;
  6. import com.caimei.config.FastDfsClient;
  7. import com.caimei.mapper.cmMapper.AuthMapper;
  8. import com.caimei.mapper.cmMapper.AuthProductMapper;
  9. import com.caimei.mapper.ldmMapper.LdmMapper;
  10. import com.caimei.model.ResponseJson;
  11. import com.caimei.model.po.*;
  12. import com.caimei.model.vo.*;
  13. import com.caimei.service.auth.AuthProductService;
  14. import com.caimei.service.auth.AuthService;
  15. import com.caimei.service.auth.ShopService;
  16. import com.caimei.service.auth.UploadService;
  17. import com.caimei.utils.*;
  18. import com.github.pagehelper.PageHelper;
  19. import com.github.pagehelper.PageInfo;
  20. import lombok.extern.slf4j.Slf4j;
  21. import lombok.val;
  22. import org.apache.commons.lang3.ObjectUtils;
  23. import org.apache.commons.lang3.StringUtils;
  24. import org.apache.http.Consts;
  25. import org.apache.http.HttpEntity;
  26. import org.apache.http.NameValuePair;
  27. import org.apache.http.client.entity.UrlEncodedFormEntity;
  28. import org.apache.http.client.methods.CloseableHttpResponse;
  29. import org.apache.http.client.methods.HttpGet;
  30. import org.apache.http.client.methods.HttpPost;
  31. import org.apache.http.client.utils.URIBuilder;
  32. import org.apache.http.entity.ContentType;
  33. import org.apache.http.entity.mime.MultipartEntityBuilder;
  34. import org.apache.http.impl.client.CloseableHttpClient;
  35. import org.apache.http.impl.client.HttpClients;
  36. import org.apache.http.message.BasicNameValuePair;
  37. import org.apache.http.util.EntityUtils;
  38. import org.apache.poi.ss.usermodel.*;
  39. import org.apache.poi.xssf.usermodel.*;
  40. import org.springframework.beans.factory.annotation.Autowired;
  41. import org.springframework.beans.factory.annotation.Value;
  42. import org.springframework.core.io.ClassPathResource;
  43. import org.springframework.stereotype.Service;
  44. import org.springframework.transaction.annotation.Transactional;
  45. import org.springframework.transaction.interceptor.TransactionAspectSupport;
  46. import org.springframework.util.Assert;
  47. import org.springframework.web.bind.annotation.PostMapping;
  48. import org.springframework.web.bind.annotation.RequestBody;
  49. import org.springframework.web.bind.annotation.RequestMapping;
  50. import org.springframework.web.bind.annotation.ResponseBody;
  51. import org.springframework.web.multipart.MultipartFile;
  52. import javax.annotation.Resource;
  53. import javax.imageio.ImageIO;
  54. import javax.servlet.ServletOutputStream;
  55. import javax.servlet.http.HttpServletRequest;
  56. import javax.servlet.http.HttpServletResponse;
  57. import javax.swing.*;
  58. import java.awt.*;
  59. import java.awt.Font;
  60. import java.io.*;
  61. import java.math.BigDecimal;
  62. import java.net.URISyntaxException;
  63. import java.net.URL;
  64. import java.nio.charset.StandardCharsets;
  65. import java.text.SimpleDateFormat;
  66. import java.util.*;
  67. import java.util.List;
  68. import java.util.regex.Matcher;
  69. import java.util.regex.Pattern;
  70. import java.util.stream.Collectors;
  71. import java.util.stream.Stream;
  72. /**
  73. * Description
  74. *
  75. * @author : Aslee
  76. * @date : 2021/5/11
  77. */
  78. @Slf4j
  79. @Service
  80. public class AuthServiceImpl implements AuthService {
  81. @Resource
  82. private AuthMapper authMapper;
  83. @Resource
  84. private LdmMapper ldmMapper;
  85. @Value("${caimei.zpapi}")
  86. private String zpServer;
  87. private AuthProductService authProductService;
  88. @Autowired
  89. public void setAuthProductService(AuthProductService authProductService) {
  90. this.authProductService = authProductService;
  91. }
  92. private ShopService shopService;
  93. @Autowired
  94. public void setShopService(ShopService shopService) {
  95. this.shopService = shopService;
  96. }
  97. private UploadService uploadService;
  98. @Autowired
  99. public void setUploadService(UploadService uploadService) {
  100. this.uploadService = uploadService;
  101. }
  102. @Value("${spring.profiles.active}")
  103. private String active;
  104. @Autowired
  105. private FastDfsClient client;
  106. @Value("${caimei.imageDomain}")
  107. private String imageDomain;
  108. @Resource
  109. private RedisService redisService;
  110. @Override
  111. public ResponseJson<PageInfo<AuthVo>> getAuthList(Integer listType, Integer authUserId, String authParty,
  112. String mobile, Integer status, Integer starFlag, Integer auditStatus,
  113. Integer lowerAuditStatus, Integer shopAuditStatus, Integer sendStatus,String authCode, Integer pageNum, Integer pageSize) {
  114. listType = null == listType ? 1 : listType;
  115. PageHelper.startPage(pageNum, pageSize);
  116. List<AuthVo> authList = authMapper.getAuthList(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus,authCode);
  117. PageInfo<AuthVo> pageData = new PageInfo<>(authList);
  118. return ResponseJson.success(pageData);
  119. }
  120. @Override
  121. public ResponseJson<PageInfo<AuthVo>> getAuthListAll(Integer listType, Integer authUserId, String authParty,
  122. String mobile, Integer status, Integer starFlag, Integer auditStatus,
  123. Integer lowerAuditStatus, Integer shopAuditStatus, Integer sendStatus, String name, String snCode, Integer pageNum, Integer pageSize) {
  124. listType = null == listType ? 1 : listType;
  125. PageHelper.startPage(pageNum, pageSize);
  126. List<AuthVo> authList = authMapper.getAuthListAll(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus, name, snCode);
  127. PageInfo<AuthVo> pageData = new PageInfo<>(authList);
  128. return ResponseJson.success(pageData);
  129. }
  130. @Override
  131. public ResponseJson updateAuthStatus(Integer authId, Integer status) {
  132. if (null == authId) {
  133. return ResponseJson.error("请输入授权id");
  134. }
  135. if (null == status) {
  136. return ResponseJson.error("请输入要更新的状态值");
  137. }
  138. authMapper.updateAuthStatusByAuthId(authId, status);
  139. if (0 == status) {
  140. return ResponseJson.success("下线品牌授权成功");
  141. } else {
  142. return ResponseJson.success("上线品牌授权成功");
  143. }
  144. }
  145. @Override
  146. public ResponseJson deleteAuth(Integer authId) {
  147. if (null == authId) {
  148. return ResponseJson.error("参数异常,请输入授权id");
  149. }
  150. // 删除品牌授权
  151. authMapper.deleteAuthByAuthId(authId);
  152. // 删除轮播图
  153. authMapper.deleteBanner(authId);
  154. // 删除商品及商品参数
  155. List<Integer> productIdList = authProductService.getProductIdsByAuthId(authId);
  156. productIdList.forEach(productId -> {
  157. if (null != productId) {
  158. authProductService.deleteProduct(productId);
  159. }
  160. });
  161. return ResponseJson.success("删除品牌授权成功");
  162. }
  163. @Override
  164. public ResponseJson<AuthFormVo> getAuthFormData(Integer authId) {
  165. if (null == authId) {
  166. return ResponseJson.error("参数异常,机构id不能为空", null);
  167. }
  168. AuthFormVo authFormVo = authMapper.getAuthFormById(authId);
  169. //该机构关联机构用集合形式返回便于前端赋值
  170. if (null != authFormVo.getRelationId() && !"".equals(authFormVo.getRelationId())) {
  171. String[] relationIdList = authFormVo.getRelationId().split(",");
  172. List<AuthFormVo> authIdList = authMapper.getAuthIdList(relationIdList);
  173. authFormVo.setReleationClubList(authIdList);
  174. }
  175. if (null != authFormVo.getLng()) {
  176. authFormVo.setLngAndLat(authFormVo.getLng() + "," + authFormVo.getLat());
  177. }
  178. List<String> bannerList = authMapper.getBannerList(authId);
  179. authFormVo.setBannerList(bannerList);
  180. return ResponseJson.success(authFormVo);
  181. }
  182. @Override
  183. public ResponseJson<List<AuthVo>> getAuthSelectList(Integer authUserId) {
  184. List<AuthVo> authList = authMapper.getAuthList(1, authUserId, null, null, null, null, null, null, null, null,null);
  185. return ResponseJson.success(authList);
  186. }
  187. @Override
  188. public ResponseJson importLdmImage(Integer authUserId) {
  189. List<LdmDataPo> ldmClubData = ldmMapper.getLdmClubData(null, 0);
  190. ldmClubData.forEach(ldmClub -> {
  191. String pic2 = ldmClub.getPic2();
  192. String pic3 = ldmClub.getPic3();
  193. String pic4 = ldmClub.getPic4();
  194. List<AuthVo> authList = authMapper.getAuthByNameAndAddress(ldmClub.getAuthParty(), ldmClub.getAddress());
  195. if (null != authList && authList.size() > 0) {
  196. if (authList.size() > 1) {
  197. log.info(">>>>>>>>>>>>>>>>>>>>>导入ldm门店图错误:对应门店过多,门店名称:" + ldmClub.getAuthParty());
  198. } else {
  199. AuthVo auth = authList.get(0);
  200. Integer authId = auth.getAuthId();
  201. if (StringUtils.isNotEmpty(pic2) || StringUtils.isNotEmpty(pic3) || StringUtils.isNotEmpty(pic4)) {
  202. authMapper.deleteBanner(authId);
  203. insertBanner(pic2, authId);
  204. insertBanner(pic3, authId);
  205. insertBanner(pic4, authId);
  206. }
  207. if (StringUtils.isNotEmpty(ldmClub.getRemarks())) {
  208. authMapper.updateRemarks(authId, ldmClub.getRemarks());
  209. }
  210. }
  211. } else {
  212. log.info(">>>>>>>>>>>>>>>>>>>>>导入ldm门店图错误:找不到对应门店,门店名称:" + ldmClub.getAuthParty());
  213. }
  214. });
  215. return ResponseJson.success();
  216. }
  217. @Override
  218. public ResponseJson checkAuth(Integer authId) {
  219. authMapper.checkAuth(authId);
  220. return ResponseJson.success();
  221. }
  222. @Override
  223. public ResponseJson starAuth(Integer authId, Integer starFlag, String starNum) {
  224. authMapper.starAuth(authId, starFlag, starNum);
  225. return ResponseJson.success();
  226. }
  227. private void insertBanner(String pic, Integer authId) {
  228. if (StringUtils.isNotEmpty(pic)) {
  229. String imagePath = "https://wangdian.skinovachina.com" + pic;
  230. String fileName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
  231. try {
  232. String banner = uploadService.saveFileByUrl(imagePath, fileName);
  233. authMapper.insertBanner(authId, banner);
  234. } catch (Exception e) {
  235. e.printStackTrace();
  236. }
  237. }
  238. }
  239. @Override
  240. public ResponseJson saveAuth(CmBrandAuthPo auth, List<String> bannerList, boolean importFlag, Integer source) {
  241. Integer authId = auth.getId();
  242. boolean insertFlag = null == authId;
  243. AuthVo dbAuth = null;
  244. if (!insertFlag) {
  245. dbAuth = authMapper.getAuthById(authId);
  246. }
  247. String authParty = auth.getAuthParty();
  248. if (StringUtils.isBlank(authParty)) {
  249. return ResponseJson.error("参数异常,请输入授权机构名称");
  250. }
  251. if (null == auth.getFirstClubType()) {
  252. return ResponseJson.error("请勾选机构类型");
  253. }
  254. if ((1 == auth.getFirstClubType() || 2 == auth.getFirstClubType()) && null == auth.getSecondClubType()) {
  255. return ResponseJson.error("请勾选二级机构类型");
  256. }
  257. if (1 == auth.getFirstClubType() && StringUtils.isEmpty(auth.getMedicalLicenseImage())) {
  258. return ResponseJson.error("请上传医疗许可证");
  259. }
  260. if (null == auth.getEmpNum()) {
  261. return ResponseJson.error("请输入员工人数");
  262. }
  263. if (1 == source) {
  264. if (null == auth.getCreateBy()) {
  265. return ResponseJson.error("参数异常,请输入创建人id");
  266. }
  267. /*if (1 == auth.getAuthImageType() && StringUtils.isEmpty(auth.getAuthImageLogo())) {
  268. return ResponseJson.error("授权牌logo不能为空");
  269. }*/
  270. if (2 == auth.getAuthImageType() && StringUtils.isEmpty(auth.getAuthImage())) {
  271. return ResponseJson.error("授权牌不能为空");
  272. }
  273. } else {
  274. // 机构添加默认模板库生成
  275. auth.setAuthImageType(1);
  276. }
  277. if (!importFlag) {
  278. if (null == auth.getProvinceId() || null == auth.getCityId() || null == auth.getTownId() || StringUtils.isEmpty(auth.getAddress()) || null == auth.getLng() || null == auth.getLat()) {
  279. return ResponseJson.error("参数异常,地址信息异常");
  280. }
  281. if (StringUtils.isEmpty(auth.getLogo())) {
  282. return ResponseJson.error("参数异常,请上传机构logo");
  283. }
  284. if (null == bannerList || bannerList.size() <= 0) {
  285. return ResponseJson.error("参数异常,请上传轮播图");
  286. }
  287. }
  288. // 供应商保存,直接上线;机构保存,需要供应商审核通过后才上线
  289. if (null != dbAuth && 1 != dbAuth.getAuditStatus()) {
  290. // 被驳回的数据,编辑变为待审核状态
  291. auth.setStatus(2);
  292. auth.setAuditStatus(2);
  293. } else {
  294. auth.setStatus(1 == source ? 1 : 2);
  295. auth.setAuditStatus(1 == source ? 1 : 2);
  296. }
  297. Integer adminUserId = authMapper.getAdminUserId();
  298. auth.setAuditBy(adminUserId);
  299. auth.setAuditTime(new Date());
  300. if (1 == source) {
  301. auth.setShopAuditBy(auth.getCreateBy());
  302. auth.setShopAuditTime(new Date());
  303. }
  304. auth.setDelFlag(0);
  305. auth.setCheckFlag(0);
  306. auth.setShopAuditStatus(1 == source ? 1 : 2);
  307. /*
  308. 保存授权
  309. */
  310. if (insertFlag) {
  311. authMapper.insertAuth(auth);
  312. } else {
  313. authMapper.updateAuthByAuthId(auth);
  314. // 删除原有的轮播图
  315. authMapper.deleteBanner(auth.getId());
  316. }
  317. // 保存之后生成授权牌和水印授权牌
  318. String authImage = null;
  319. if (1 == auth.getAuthImageType()) {
  320. // 模板库生成
  321. // 获取对应模板
  322. TemplateVo authTemplate = authMapper.getAuthTemplate(auth.getId(), null, 1);
  323. authImage = generateAuthImage(authTemplate, auth);
  324. auth.setAuthImage(authImage);
  325. }
  326. // 添加水印
  327. if (StringUtils.isNotEmpty(auth.getAuthImage())) {
  328. auth.setPcAuthImage(addWaterMark(auth.getAuthImage(), 1));
  329. auth.setAppletsAuthImage(addWaterMark(auth.getAuthImage(), 2));
  330. authMapper.updateAuthImage(auth);
  331. }
  332. // 保存轮播图
  333. if (null != bannerList) {
  334. bannerList.forEach(banner -> authMapper.insertBanner(auth.getId(), banner));
  335. }
  336. return ResponseJson.success("保存品牌授权成功", auth);
  337. }
  338. @Override
  339. public String addWaterMark(String image, Integer type) {
  340. try {
  341. //type:1pc,2applets
  342. ClassPathResource classPathResource = new ClassPathResource("/images/newPcWaterMark.png");
  343. InputStream inputStreamImg = classPathResource.getInputStream();
  344. Image pcWaterMarkImg = ImageIO.read(inputStreamImg);
  345. classPathResource = new ClassPathResource("/images/newAppletsWaterMark.png");
  346. inputStreamImg = classPathResource.getInputStream();
  347. Image appletsWaterMarkImg = ImageIO.read(inputStreamImg);
  348. String img = ImageUtils.markImageByIcon(type == 1 ? pcWaterMarkImg : appletsWaterMarkImg, image, null);
  349. String imagePath = null;
  350. if (StringUtils.isNotEmpty(img)) {
  351. MultipartFile imgFile = Base64Util.base64ToMultipart(img);
  352. if (null != imgFile) {
  353. imagePath = uploadService.saveFile(imgFile);
  354. }
  355. log.info(">>>>>>>>>>>>>>>>水印图片上传成功:" + imagePath);
  356. } else {
  357. log.info(">>>>>>>>>>>>>>>>水印图片上传失败");
  358. }
  359. return imagePath;
  360. } catch (Exception e) {
  361. e.printStackTrace();
  362. }
  363. return null;
  364. }
  365. @Override
  366. public String generateAuthImage(TemplateVo authTemplate, CmBrandAuthPo auth) {
  367. if (null != authTemplate) {
  368. // 根据模板id设置相关数据
  369. Map<String, Object> templateInfo = getTemplateInfo(authTemplate, auth);
  370. Object templateImage = templateInfo.get("templateImage");
  371. if (null != templateImage) {
  372. String authImage = ImageUtils.generateAuthImage(templateInfo);
  373. log.info("【图片上传】>>>>>>>>>>>>>>>>图片临时路径:" + authImage);
  374. // 临时图片
  375. File tempFile = new File(authImage);
  376. String imageUrl = null;
  377. try {
  378. imageUrl = imageDomain + "/" + client.uploadFile(authImage);
  379. } catch (Exception e) {
  380. e.printStackTrace();
  381. }
  382. // 删除临时图片
  383. boolean delete = tempFile.delete();
  384. log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时图片:" + delete);
  385. return imageUrl;
  386. } else {
  387. return null;
  388. }
  389. }
  390. return null;
  391. }
  392. private Map<String, Object> getTemplateInfo(TemplateVo template, CmBrandAuthPo auth) {
  393. HashMap<String, Object> map = new HashMap<>();
  394. Integer templateId = template.getTemplateId();
  395. if (1 == templateId) {
  396. map.put("templateImage", template.getTemplateImage());
  397. double rate = 0.15;
  398. if (StringUtils.isNotEmpty(auth.getAuthImageLogo())) {
  399. // 获取授权牌logo位置
  400. try {
  401. ImageIcon imageIcon = new ImageIcon(new URL(template.getTemplateImage()));
  402. Image srcImg = imageIcon.getImage();
  403. int srcWidth = srcImg.getWidth(null);
  404. ImageIcon authImageLogo = new ImageIcon(new URL(auth.getAuthImageLogo()));
  405. Image authLogo = authImageLogo.getImage();
  406. int authLogoWidth = authLogo.getWidth(null);
  407. int x = (srcWidth - (int) Math.round(238 * rate) - authLogoWidth) / 2 + (int) Math.round(238 * rate);
  408. int y = (int) Math.round(1230 * rate);
  409. map.put("addImage1_x", x);
  410. map.put("addImage1_y", y);
  411. map.put("addImage1_image", auth.getAuthImageLogo());
  412. } catch (Exception e) {
  413. e.printStackTrace();
  414. }
  415. }
  416. // 添加认证编号信息
  417. if (StringUtils.isNotEmpty(auth.getAuthCode())) {
  418. map.put("addWord1_content", auth.getAuthCode());
  419. map.put("addWord1_color", "218,185,107");
  420. map.put("addWord1_type", "思源宋体");
  421. map.put("addWord1_style", Font.BOLD);
  422. map.put("addWord1_size", (int) Math.round(90 * rate));
  423. map.put("addWord1_x", (int) Math.round(2168 * rate));
  424. map.put("addWord1_y", (int) Math.round(3157 * rate));
  425. }
  426. // 添加认证日期信息
  427. if (null != auth.getAuthDate()) {
  428. SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
  429. map.put("addWord2_content", format.format(auth.getAuthDate()));
  430. map.put("addWord2_color", "218,185,107");
  431. map.put("addWord2_type", "思源宋体");
  432. map.put("addWord2_style", Font.PLAIN);
  433. map.put("addWord2_size", (int) Math.round(90 * rate));
  434. map.put("addWord2_x", (int) Math.round(2085 * rate));
  435. map.put("addWord2_y", (int) Math.round(3289 * rate));
  436. }
  437. // 添加二维码信息
  438. if (StringUtils.isNotEmpty(template.getQrPosition())) {
  439. String qrCodeLink = zpServer + "/" + auth.getAuthUserId() + "/" + authMapper.getPrefix(auth.getAuthUserId()) + "/approve/club/detail?id=" + auth.getId();
  440. map.put("addQr1_link", qrCodeLink);
  441. map.put("addQr1_size", template.getQrSize());
  442. String[] split = template.getQrPosition().split(",");
  443. if (split.length == 2) {
  444. map.put("addQr1_x", Integer.parseInt(split[0]));
  445. map.put("addQr1_y", Integer.parseInt(split[1]));
  446. }
  447. }
  448. }
  449. return map;
  450. }
  451. @Override
  452. public ResponseJson auditAuth(Integer authId, Integer auditStatus, String invalidReason, Integer auditBy, Integer source) {
  453. if (authId == null) {
  454. return ResponseJson.error("请输入授权id");
  455. }
  456. if (auditStatus == null) {
  457. return ResponseJson.error("请输入审核结果");
  458. }
  459. if (auditStatus == 0 && StringUtils.isEmpty(invalidReason)) {
  460. return ResponseJson.error("请输入审核不通过的原因");
  461. }
  462. source = null == source ? 1 : source;
  463. Date auditTime = new Date();
  464. // 授权状态更新
  465. Integer status = null;
  466. if (auditStatus == 0) {
  467. // 审核不通过,下线授权
  468. status = 0;
  469. } else {
  470. // 审核通过,上线授权
  471. status = 1;
  472. }
  473. if (1 == source) {
  474. authMapper.updateAuthAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime);
  475. }
  476. if (2 == source) {
  477. authMapper.updateAuthShopAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime);
  478. }
  479. return ResponseJson.success("审核机构认证成功");
  480. }
  481. @Override
  482. @Transactional(rollbackFor = Exception.class)
  483. public ResponseJson importDataByExcel(MultipartFile file, Integer authUserId, Integer createBy) {
  484. String originalFilename = file.getOriginalFilename();
  485. String randomStr = UUID.randomUUID().toString();
  486. assert originalFilename != null;
  487. int index = originalFilename.lastIndexOf(".");
  488. String extName = originalFilename.substring(index);
  489. String filePath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/";
  490. if ("dev".equals(active)) {
  491. filePath = "D:\\WorkSpace\\file\\tempImport\\";
  492. }
  493. filePath += randomStr + extName;
  494. try {
  495. File tempFile = new File(filePath);
  496. if (!tempFile.exists()) {
  497. tempFile.mkdirs();
  498. }
  499. file.transferTo(tempFile);
  500. return saveExcelData(filePath, authUserId, createBy);
  501. } catch (IOException e) {
  502. e.printStackTrace();
  503. }
  504. log.info(">>>>>>>>>>>>>>>>文件临时路径:" + filePath);
  505. return null;
  506. }
  507. private ResponseJson saveExcelData(String filePath, Integer authUserId, Integer createBy) {
  508. //判断是否为excel类型文件
  509. if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
  510. System.out.println("文件不是excel类型");
  511. }
  512. // 获取供应商品牌
  513. List<String> shopBrands = shopService.getShopBrands(authUserId);
  514. // 授权列表
  515. List<CmBrandAuthPo> authImportList = new ArrayList<>();
  516. try {
  517. FileInputStream fis = new FileInputStream(filePath);
  518. // 得到表格数据
  519. XSSFWorkbook workbook = new XSSFWorkbook(fis);
  520. //得到第一个工作表(机构表)
  521. XSSFSheet authPartySheet = workbook.getSheetAt(0);
  522. //获得表头
  523. Row rowHead = authPartySheet.getRow(0);
  524. //判断表头是否正确
  525. if (9 != rowHead.getLastCellNum() || !"机构名称".equals(rowHead.getCell(0).getStringCellValue())) {
  526. return ResponseJson.error("授权机构表格式错误");
  527. }
  528. // 获得数据的总行数
  529. int authPartyRowNum = authPartySheet.getLastRowNum();
  530. //获得所有数据
  531. for (int i = 1; i <= authPartyRowNum; i++) {
  532. //获得第i行对象
  533. Row authPartyRow = authPartySheet.getRow(i);
  534. if (null == authPartyRow) {
  535. break;
  536. }
  537. Cell cell = null;
  538. // 校验机构名称
  539. cell = authPartyRow.getCell(0);
  540. cell.setCellType(CellType.STRING);
  541. String authParty = cell.getStringCellValue();
  542. if (StringUtils.isBlank(authParty)) {
  543. return ResponseJson.error("第" + i + 1 + "行机构名称不能为空");
  544. }
  545. // 校验省市区
  546. cell = authPartyRow.getCell(1);
  547. cell.setCellType(CellType.STRING);
  548. String area = cell.getStringCellValue();
  549. if (StringUtils.isBlank(area)) {
  550. return ResponseJson.error("第" + i + 1 + "行所在地区不能为空");
  551. }
  552. String[] areaSplit = area.split("/");
  553. if (areaSplit.length < 2 || areaSplit.length > 3) {
  554. return ResponseJson.error("第" + i + 1 + "行所在地区格式错误");
  555. }
  556. // 省份
  557. String provinceName = areaSplit[0];
  558. if (StringUtils.isBlank(provinceName)) {
  559. return ResponseJson.error("第" + i + 1 + "行省份不能为空");
  560. }
  561. if (provinceName.length() > 2) {
  562. provinceName = provinceName.substring(0, provinceName.length() - 1).trim();
  563. }
  564. Integer provinceId = authMapper.getProvinceId(provinceName);
  565. // 市名
  566. String cityName = areaSplit[1];
  567. if (StringUtils.isBlank(cityName)) {
  568. return ResponseJson.error("第" + i + 1 + "行市名不能为空");
  569. }
  570. if (cityName.length() > 2) {
  571. cityName = cityName.substring(0, cityName.length() - 1).trim();
  572. }
  573. Integer cityId = authMapper.getCityId(cityName);
  574. Integer townId = null;
  575. if (areaSplit.length > 2) {
  576. // 区名
  577. String townName = areaSplit[2];
  578. if (StringUtils.isNotEmpty(townName) && townName.length() > 2) {
  579. townName = townName.substring(0, townName.length() - 1).trim();
  580. }
  581. List<TownPo> townList = authMapper.getTownList(townName);
  582. for (int j = 0; j < townList.size(); j++) {
  583. TownPo town = townList.get(j);
  584. if (null == townId) {
  585. if (null != cityId) {
  586. if (town.getCityId().equals(cityId)) {
  587. townId = town.getTownId();
  588. }
  589. } else {
  590. Integer checkCityId = authMapper.getCityIdByTownId(town.getTownId());
  591. if (null != provinceId && null != checkCityId) {
  592. Integer checkProvinceId = authMapper.getProvinceIdByCityId(cityId);
  593. if (provinceId.equals(checkProvinceId)) {
  594. cityId = checkCityId;
  595. townId = town.getTownId();
  596. }
  597. }
  598. }
  599. }
  600. }
  601. }
  602. // 校验详细地址
  603. cell = authPartyRow.getCell(2);
  604. cell.setCellType(CellType.STRING);
  605. String address = cell.getStringCellValue();
  606. if (StringUtils.isBlank(address)) {
  607. return ResponseJson.error("第" + i + 1 + "行详细地址不能为空");
  608. }
  609. // 校验经纬度
  610. cell = authPartyRow.getCell(3);
  611. cell.setCellType(CellType.STRING);
  612. String lngAndLat = cell.getStringCellValue();
  613. if (StringUtils.isBlank(lngAndLat)) {
  614. return ResponseJson.error("第" + i + 1 + "行经纬度不能为空");
  615. }
  616. String[] split = lngAndLat.split(",");
  617. if (2 != split.length) {
  618. return ResponseJson.error("第" + i + 1 + "行经纬度格式错误");
  619. }
  620. BigDecimal lng = new BigDecimal(split[0]);
  621. BigDecimal lat = new BigDecimal(split[1]);
  622. // 校验联系电话
  623. cell = authPartyRow.getCell(4);
  624. cell.setCellType(CellType.STRING);
  625. String mobile = cell.getStringCellValue();
  626. if (StringUtils.isBlank(mobile)) {
  627. return ResponseJson.error("第" + i + 1 + "行联系电话不能为空");
  628. }
  629. // 认证编号
  630. cell = authPartyRow.getCell(5);
  631. cell.setCellType(CellType.STRING);
  632. String authCode = cell.getStringCellValue();
  633. // 认证日期
  634. Date authDate = null;
  635. cell = authPartyRow.getCell(6);
  636. cell.setCellType(CellType.STRING);
  637. String authDateStr = cell.getStringCellValue();
  638. if (StringUtils.isNotBlank(authDateStr)) {
  639. SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
  640. authDate = format.parse(authDateStr);
  641. }
  642. // 校验员工人数
  643. Integer empNum = null;
  644. cell = authPartyRow.getCell(7);
  645. cell.setCellType(CellType.STRING);
  646. String empNumStr = cell.getStringCellValue();
  647. if (StringUtils.isBlank(empNumStr)) {
  648. return ResponseJson.error("第" + i + 1 + "行员工人数不能为空");
  649. }
  650. try {
  651. empNum = Integer.parseInt(empNumStr);
  652. } catch (Exception e) {
  653. return ResponseJson.error("第" + i + 1 + "行员工人数格式错误");
  654. }
  655. // 校验店铺备注
  656. cell = authPartyRow.getCell(8);
  657. cell.setCellType(CellType.STRING);
  658. String remarks = cell.getStringCellValue();
  659. Integer customFlag = 0;
  660. if (StringUtils.isNotEmpty(remarks)) {
  661. customFlag = 1;
  662. }
  663. CmBrandAuthPo authPo = new CmBrandAuthPo();
  664. authPo.setAuthParty(authParty);
  665. authPo.setProvinceId(provinceId);
  666. authPo.setCityId(cityId);
  667. authPo.setTownId(townId);
  668. authPo.setAddress(address);
  669. authPo.setLng(lng);
  670. authPo.setLat(lat);
  671. authPo.setMobile(mobile);
  672. authPo.setAuthCode(authCode);
  673. authPo.setAuthDate(authDate);
  674. authPo.setAuthImageType(1);
  675. authPo.setEmpNum(empNum);
  676. authPo.setCustomFlag(customFlag);
  677. authPo.setRemarks(remarks);
  678. authImportList.add(authPo);
  679. }
  680. } catch (Exception e) {
  681. e.printStackTrace();
  682. return ResponseJson.error("导入失败,请检查表格数据");
  683. } finally {
  684. // 删除临时数据
  685. File tempFile = new File(filePath);
  686. boolean delete = tempFile.delete();
  687. log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时表格:" + delete);
  688. }
  689. // 保存授权数据
  690. for (int i = 0; i < authImportList.size(); i++) {
  691. CmBrandAuthPo authPo = authImportList.get(i);
  692. // 保存授权机构
  693. authPo.setAuthUserId(authUserId);
  694. authPo.setCreateBy(createBy);
  695. authPo.setCreateSource(1);
  696. authPo.setFirstClubType(5);
  697. // 导入数据
  698. ResponseJson result = saveAuth(authPo, null, true, 1);
  699. if (result.getCode() != 0) {
  700. // 设置手动回滚事务
  701. TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
  702. return ResponseJson.error("导入失败");
  703. }
  704. }
  705. return ResponseJson.success("导入成功");
  706. }
  707. /**
  708. * 获取机构关联的机构信息
  709. * 1.7.4版本:
  710. */
  711. @Override
  712. public ResponseJson<List<AuthFormVo>> getRelationgInfo(String snCode, Integer authUserId) {
  713. //根据sn码获取关联这个产品的机构列表
  714. List<ProductFormVo> relationgList = authMapper.getRelationgList(snCode);
  715. String relationgInfo = null;
  716. List<AuthFormVo> authIdList = null;
  717. if (relationgList.size() > 0) {
  718. for (int i = 0; i < relationgList.size(); i++) {
  719. if (null != relationgInfo) {
  720. relationgInfo += ",";
  721. }
  722. relationgInfo += relationgList.get(i).getRelationId();
  723. }
  724. if (null != relationgInfo) {
  725. String[] relationIdList = relationgInfo.split(",");
  726. authIdList = authMapper.getAuthIdList(relationIdList);
  727. }
  728. }
  729. return ResponseJson.success(authIdList);
  730. }
  731. /**
  732. * 1.7.4版本
  733. * 获取可绑定机构机构信息
  734. **/
  735. @Override
  736. public ResponseJson<List<AuthFormVo>> getClubBindAuth(Integer authUserId) {
  737. List<AuthFormVo> clubBindAuth = authMapper.getClubBindAuth(authUserId);
  738. return ResponseJson.success(clubBindAuth);
  739. }
  740. //------------------------------------------v1.7.5上传视频至抖音---------------------------------------------------------------------------------------
  741. ///用户授权(用于获取数据)
  742. /**
  743. * 用户扫码授权,获取code值
  744. * @param response
  745. * @return true :token没过期 false:token过期需重新授权
  746. * @throws IOException
  747. */
  748. @Override
  749. public ResponseJson getDouYingCode(HttpServletResponse response) throws IOException {
  750. //验证是否是第一次登录(根据redis缓存中的token验证)
  751. // long dYaccessTok = redisService.getExpireTime("DYaccessToken");
  752. // boolean s=redisService.exists("DYaccessToken");
  753. // String s1= redisService.get("DyopenId").toString();
  754. //// if(!redisService.exists("DYaccessToken")){
  755. // //验证token是否过期
  756. // long dYaccessToken = redisService.getExpireTime("DYaccessToken");
  757. // if(dYaccessToken<=0){ //tonken过期
  758. // //判断refreshToken是否过期
  759. // long DyrefreshToken = redisService.getExpireTime("DyrefreshToken");
  760. // if(DyrefreshToken>=0){ //refreshToken
  761. // //根据refreshToken刷新token,重新缓存token
  762. // String refreshToken=redisService.get("DyrefreshToken").toString();
  763. // String accessToken = refreshAccessToken(refreshToken);
  764. // redisService.set("DYaccessToken",accessToken , 60L * 60 * 24 * 15);
  765. // boolean flag= redisService.exists("DYaccessToken");
  766. // return ResponseJson.success(true);
  767. // }else{ //根据refreshToken刷新refreshToken(总共可以刷新3次,次数完后需重新扫码授权)
  768. // String refreshToken=redisService.get("DyrefreshToken").toString();
  769. // String newRefreshToken = resetRefreshAccessToken(refreshToken);
  770. // if(StringUtils.isNotEmpty(newRefreshToken)){
  771. // String accessToken = refreshAccessToken(newRefreshToken);
  772. // redisService.set("DYaccessToken",accessToken,60L * 60 * 24 * 15);
  773. // return ResponseJson.success(true);
  774. // }
  775. // }
  776. // }else {
  777. // return ResponseJson.success(true);
  778. // }
  779. // }
  780. //验证token是否过期
  781. // long dYaccessToken = redisService.getExpireTime("DYaccessToken");
  782. return redisService.getExpireTime("DYaccessToken")<0 ? ResponseJson.success(false): ResponseJson.success(true);
  783. // String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
  784. // String responestype = "code";//写死为'code'即可
  785. // String scope = "video.data,video.list,trial.whitelist,data.external.item";//应用授权作用域,多个授权作用域以英文逗号(,)分隔
  786. // String redirectUrl = "https://www.caimei365.com";//回调地址,应用中配置
  787. // String state = "false";//用于保持请求和回调的状态
  788. // String code = "https://open.douyin.com/platform/oauth/connect/?client_key=" + clintKey
  789. // + "&response_type=" + responestype + "&scope=" + scope + "&redirect_uri=" + redirectUrl + "&state=" + state;
  790. // response.sendRedirect(code);
  791. }
  792. /**
  793. * 根据用户的code值获取AcessToken
  794. * ccode 用户授权登录code
  795. **/
  796. @Override
  797. public ResponseJson getDouYingAcessToken(String code) throws IOException {
  798. String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
  799. String clintSecret = "1dd7446d29e16738787447b771ced2df";//应用唯一标识对应的密钥
  800. String grantType = "authorization_code";//固定值
  801. String requestUrl = "https://open.douyin.com/oauth/access_token/";//请求地址
  802. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  803. //创建httppost对象
  804. HttpPost hp = new HttpPost(requestUrl);
  805. hp.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
  806. // hp.setHeader("Content-Type","application/x-www-form-urlencoded");
  807. //拼接请求参数
  808. List<NameValuePair> list = new ArrayList();
  809. list.add(new BasicNameValuePair("client_key", clintKey));
  810. list.add(new BasicNameValuePair("client_secret", clintSecret));
  811. list.add(new BasicNameValuePair("code", code));
  812. list.add(new BasicNameValuePair("grant_type", grantType));
  813. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
  814. hp.setEntity(entity);
  815. //发送请求
  816. CloseableHttpResponse execute = closeableHttpClient.execute(hp);
  817. HttpEntity he = execute.getEntity();
  818. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  819. //获取access_token,open_id(用于获取视频数据),refresh_token(刷新token)
  820. JSONObject jsonObject =JSONObject.parseObject(result);
  821. String data = jsonObject.getString("data");
  822. JSONObject params =JSONObject.parseObject(data);
  823. String accessToken = params.getString("access_token");
  824. String openId = params.getString("open_id");
  825. String refreshToken = params.getString("refresh_token");
  826. String errorCode = params.getString("error_code");
  827. if(Integer.valueOf(errorCode)>0){return ResponseJson.success("tonken缓存失败",null);}
  828. //用redis缓存access_token,refresh_token
  829. redisService.set("DYaccessToken",accessToken , 60L * 60 * 24 * 15);// * 60 * 24 * 15
  830. redisService.set("DyrefreshToken",refreshToken,60L * 60 * 24 * 30);
  831. redisService.set("DyopenId",openId,60L * 60 * 24 * 30);
  832. EntityUtils.consume(he);
  833. String DYaccessToken=redisService.get("DYaccessToken").toString();
  834. String DyrefreshToken=redisService.get("DyrefreshToken").toString();
  835. String DyopenId=redisService.get("DyopenId").toString();
  836. if (StringUtils.isNotEmpty(DYaccessToken)&&StringUtils.isNotEmpty(DyrefreshToken)&&StringUtils.isNotEmpty(DyopenId)){
  837. return ResponseJson.success();
  838. }else {
  839. return ResponseJson.success("tonken缓存失败",null);
  840. }
  841. }
  842. /**
  843. * 刷新tonken
  844. * @param refreshToken
  845. */
  846. public String refreshAccessToken(String refreshToken){
  847. String requestUrl="https://open.douyin.com/oauth/refresh_token/";
  848. String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
  849. String grantType = "refresh_token";//固定值
  850. String accessToken=null;
  851. //创建httppost对象
  852. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  853. HttpPost hp = new HttpPost(requestUrl);
  854. hp.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
  855. // hp.setHeader("Content-Type","application/x-www-form-urlencoded");
  856. //拼接请求参数
  857. List<NameValuePair> list = new ArrayList();
  858. list.add(new BasicNameValuePair("client_key", clintKey));
  859. list.add(new BasicNameValuePair("grant_type", grantType));
  860. list.add(new BasicNameValuePair("refresh_token", refreshToken));
  861. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
  862. hp.setEntity(entity);
  863. try {
  864. CloseableHttpResponse execute = closeableHttpClient.execute(hp);
  865. HttpEntity he = execute.getEntity();
  866. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  867. JSONObject params=JSONObject.parseObject(result);
  868. String data=params.getString("data");
  869. JSONObject datalist=JSONObject.parseObject(data);
  870. accessToken=datalist.getString("access_token");
  871. EntityUtils.consume(he);
  872. } catch (IOException e) {
  873. e.printStackTrace();
  874. }
  875. hp.setEntity(entity);
  876. return accessToken;
  877. }
  878. /**
  879. * 刷新refreshAccessToken
  880. * @param refreshToken
  881. */
  882. public String resetRefreshAccessToken(String refreshToken){
  883. String requestUrl="https://open.douyin.com/oauth/renew_refresh_token/";
  884. String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
  885. String renewRefreshAccessToken=null;
  886. //创建httppost对象
  887. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  888. HttpPost hp = new HttpPost(requestUrl);
  889. List<NameValuePair> list = new ArrayList();
  890. list.add(new BasicNameValuePair("client_key", clintKey));
  891. list.add(new BasicNameValuePair("refresh_token", refreshToken));
  892. list.add(new BasicNameValuePair("Content-Type", "multipart/form-data"));
  893. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
  894. hp.setEntity(entity);
  895. try {
  896. CloseableHttpResponse execute = closeableHttpClient.execute(hp);
  897. HttpEntity he = execute.getEntity();
  898. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  899. JSONObject jsonObject=JSONObject.parseObject(result);
  900. String data = jsonObject.getString("data");
  901. JSONObject params=JSONObject.parseObject(data);
  902. renewRefreshAccessToken = params.getString("refresh_token");
  903. EntityUtils.consume(he);
  904. } catch (IOException e) {
  905. e.printStackTrace();
  906. }
  907. hp.setEntity(entity);
  908. return renewRefreshAccessToken;
  909. }
  910. //----------------------------------------------------h5的方式上传视频------------------------------------------------
  911. /**
  912. * h5的方式上传视频
  913. * @return
  914. * @throws IOException
  915. */
  916. @Override
  917. public ResponseJson getclientToken(String title,String videoPath,Integer authId) throws IOException {
  918. //获取accessToken
  919. String client_key = "awwwvh9tsnvo54w1";
  920. String client_secret = "1dd7446d29e16738787447b771ced2df";
  921. String grant_type = "client_credential";
  922. String url = "https://open.douyin.com/oauth/client_token/?client_key=" + client_key
  923. + "&client_secret=" + client_secret
  924. + "&grant_type=" + grant_type;
  925. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  926. //创建httppost对象
  927. HttpPost hp = new HttpPost(url);
  928. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  929. builder.setCharset(Consts.UTF_8);
  930. builder.setContentType(ContentType.MULTIPART_FORM_DATA);
  931. //构建参数
  932. HttpEntity entity = builder.build();
  933. hp.setEntity(entity);
  934. CloseableHttpResponse response = null;
  935. String schema=null;
  936. try {
  937. response = closeableHttpClient.execute(hp);
  938. HttpEntity he = response.getEntity();
  939. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  940. //把返回结果转json获取access_token
  941. JSONObject jsonObject=JSONObject.parseObject(result);
  942. String data=jsonObject.getString("data");
  943. JSONObject params=JSONObject.parseObject(data);
  944. String accessToken=params.getString("access_token");
  945. //根据accesstoken获取tiket
  946. schema = getDouYingTicket(accessToken, title,videoPath,authId);
  947. EntityUtils.consume(he);
  948. } catch (IOException e) {
  949. e.printStackTrace();
  950. }
  951. return ResponseJson.success(schema);
  952. }
  953. /**
  954. * 根据token获取ticket
  955. **/
  956. @RequestMapping("/getDouYingTicket")
  957. public String getDouYingTicket(String clientToken,String title,String videoPath,Integer authId) throws IOException {
  958. //时间戳
  959. long l = System.currentTimeMillis();
  960. String timestamp = String.valueOf(l);
  961. //随机数
  962. String noncestr = randomGen(16);
  963. String uri = "https://open.douyin.com/open/getticket/";
  964. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  965. HttpGet httpGet = new HttpGet(uri);
  966. httpGet.setHeader("access-token", clientToken);
  967. httpGet.setHeader("Content-Type","application/json");
  968. CloseableHttpResponse response = null;
  969. String schema=null;
  970. try {
  971. response = closeableHttpClient.execute(httpGet);
  972. HttpEntity he = response.getEntity();
  973. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  974. //获取ticket
  975. JSONObject jsonObject=JSONObject.parseObject(result);
  976. String data = jsonObject.getString("data");
  977. JSONObject params=JSONObject.parseObject(data);
  978. String ticket = params.getString("ticket");
  979. //getDouYingshareId
  980. String shareId = getDouYingshareId(clientToken);
  981. //保存shareId用于回调时存储item_id
  982. authMapper.savaShareIdByAuthId(authId,shareId);
  983. //获取签名 并且用md5加密
  984. String signature = signatureAlgorithm(ticket, timestamp,noncestr);
  985. //获取schema(返回前端用于生成二维码发布视频)
  986. schema = appendSchema(signature, shareId, timestamp,noncestr, title, videoPath);
  987. EntityUtils.consume(he);
  988. } catch (IOException e) {
  989. e.printStackTrace();
  990. }
  991. return schema;
  992. }
  993. /**
  994. * 获取签名 并且用md5加密
  995. * ticket
  996. **/
  997. @RequestMapping("/signatureAlgorithm")
  998. public String signatureAlgorithm(String ticket, String timestamp,String noncestr) {
  999. TreeMap<String, String> treeMap = new TreeMap<>();
  1000. treeMap.put("nonce_str", noncestr);
  1001. treeMap.put("ticket", ticket);
  1002. treeMap.put("timestamp", timestamp);
  1003. StringBuffer stringBuffer = new StringBuffer();
  1004. Iterator<Map.Entry<String, String>> it = treeMap.entrySet().iterator();
  1005. while (it.hasNext()) {
  1006. Map.Entry<String, String> entry = it.next();
  1007. stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
  1008. }
  1009. String result = stringBuffer.substring(0, stringBuffer.length() - 1);
  1010. //进行md5签名
  1011. String signature = Md5Util.md5(result).toLowerCase();
  1012. return signature;
  1013. }
  1014. /**
  1015. * Schema 生成
  1016. **/
  1017. public String appendSchema(String signature, String shareId, String timestamp,String noncestr,String title,String videoPath) {
  1018. URIBuilder uri = null;
  1019. String schema = null;
  1020. try {
  1021. uri = new URIBuilder("snssdk1128://openplatform/share");
  1022. uri.addParameter("share_type", "h5");//固定h5
  1023. uri.addParameter("client_key", "awwwvh9tsnvo54w1");//应用唯一标识
  1024. uri.addParameter("nonce_str", noncestr);//随机数(必须和签名时的nonce_str一致)
  1025. uri.addParameter("timestamp", timestamp);//时间戳(必须和签名时的timestamp一致)
  1026. uri.addParameter("signature", signature);//签名
  1027. uri.addParameter("state", shareId);//通过方法获取(基于webhook,获取视频发布回调信息,不传则收不到回调信息)
  1028. //https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4
  1029. //视频地址(必须为网络地址,本地地址无法发布)单视频上传
  1030. uri.addParameter("video_path",videoPath);//"https://caimei-oss.oss-cn-shenzhen.aliyuncs.com/beta/authFile/5c7bfb6e-9919-48b1-a905-88a888f22a11.mp4");//https://caimei-oss.oss-cn-shenzhen.aliyuncs.com/beta/authFile/5c7bfb6e-9919-48b1-a905-88a888f22a11.mp4
  1031. uri.addParameter("share_to_publish", "1");//为1则直接发布视频至抖音
  1032. uri.addParameter("title",title);//"给大佐都整emo了");//视频标题
  1033. schema = uri.toString();
  1034. } catch (URISyntaxException e) {
  1035. e.printStackTrace();
  1036. }
  1037. return schema;
  1038. }
  1039. /**
  1040. * 获取shareId 用于生成schema
  1041. **/
  1042. @RequestMapping("/getDouYingshareId")
  1043. public String getDouYingshareId(String clientToken) throws IOException {
  1044. String uri = "https://open.douyin.com/share-id/?need_callback=true&default_hashtag=hashtag";
  1045. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  1046. HttpGet httpGet = new HttpGet(uri);
  1047. httpGet.setHeader("access-token", clientToken);
  1048. CloseableHttpResponse response = null;
  1049. String shareId = "";
  1050. try {
  1051. response = closeableHttpClient.execute(httpGet);
  1052. HttpEntity he = response.getEntity();
  1053. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  1054. JSONObject jsonObject=JSONObject.parseObject(result);
  1055. String data = jsonObject.getString("data");
  1056. JSONObject params=JSONObject.parseObject(data);
  1057. shareId = params.getString("share_id");
  1058. EntityUtils.consume(he);
  1059. } catch (IOException e) {
  1060. e.printStackTrace();
  1061. }
  1062. return shareId;
  1063. }
  1064. /**
  1065. * 获取已发布视频列表
  1066. * @param openId 用户唯一标志
  1067. * @param cursor 分页游标, 第一页请求cursor是0, response中会返回下一页请求用到的cursor, 同时response还会返回has_more来表明是否有更多的数据。
  1068. * @param count 每页数量 10
  1069. */
  1070. public String getVideoList(String openId,Long cursor,Integer count,String accessToken){
  1071. String requestUrl="https://open.douyin.com/video/list/?open_id="+openId+"&cursor="+cursor+"&count="+count;
  1072. //创建httppost对象
  1073. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  1074. HttpGet hg = new HttpGet(requestUrl);
  1075. hg.setHeader("Content-Type","application/json");
  1076. hg.addHeader("access-token",accessToken);
  1077. String resultList=null;
  1078. try {
  1079. CloseableHttpResponse execute = closeableHttpClient.execute(hg);
  1080. HttpEntity entity = execute.getEntity();
  1081. String result=EntityUtils.toString(entity,StandardCharsets.UTF_8);
  1082. JSONObject jsonObject = JSONObject.parseObject(result);
  1083. resultList = jsonObject.getString("data");
  1084. // resultList = JSONArray.parseArray(itemIdlist);
  1085. // String itemId = params.getJSONObject(0).get("item_id").toString();
  1086. //根据itemid获取视频的数据(点赞,播放,评论量)
  1087. EntityUtils.consume(entity);
  1088. } catch (IOException e) {
  1089. e.printStackTrace();
  1090. }
  1091. return resultList;
  1092. }
  1093. /**
  1094. * 生成随机数
  1095. *
  1096. * @param place
  1097. * @return
  1098. */
  1099. public String randomGen(int place) {
  1100. String base = "wqetryuioplkjhgfdsazxcvbmnABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1101. StringBuffer sb = new StringBuffer();
  1102. Random rd = new Random();
  1103. for (int i = 0; i < place; i++) {
  1104. sb.append(base.charAt(rd.nextInt(base.length())));
  1105. }
  1106. return sb.toString();
  1107. }
  1108. /**
  1109. * 保存视频信息
  1110. * @return
  1111. */
  1112. @Override
  1113. public ResponseJson saveVideoInfo(ChallengeRoundVo cr){
  1114. Date date=new Date();
  1115. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1116. String releaseTime = sf.format(date).replace("T", "");
  1117. authMapper.saveVideoInfo(cr.getUserName(),cr.getCover(),cr.getOssUrl(),cr.getOssName(),cr.getTitle(),releaseTime,cr.getAuthId(),cr.getAuthUserId());
  1118. return ResponseJson.success("保存成功",null);
  1119. }
  1120. /**
  1121. * 根据authid获取authUserId
  1122. * @param authId
  1123. * @return
  1124. */
  1125. @Override
  1126. public boolean getauthUserId(Integer authId){
  1127. String authUserId= authMapper.getauthUserId(authId);
  1128. return StringUtils.isEmpty(authUserId);
  1129. }
  1130. /**
  1131. * 判断是否存在userName
  1132. * @param userName
  1133. * @return
  1134. */
  1135. @Override
  1136. public boolean getuserName(String userName){
  1137. String name= authMapper.getuserName(userName);
  1138. return StringUtils.isEmpty(name);
  1139. }
  1140. /**
  1141. * 验证是否在活动时间内
  1142. * @param releaseTime 发布时间
  1143. * @return
  1144. */
  1145. @Override
  1146. public boolean checkActivityTime(String releaseTime){
  1147. Integer id= authMapper.checkActivityTime(releaseTime);
  1148. return id==null?true:false;
  1149. }
  1150. /**
  1151. * 获取已发布视频列表(前端)
  1152. * @param clubUserName 手机号或者机构名
  1153. * @param status 用户发布状态
  1154. * @param cursor 页码
  1155. * @param count 条数
  1156. * @return
  1157. */
  1158. @Override
  1159. public ResponseJson<PageInfo<ChallengeRoundVo>> getPublishedVideoList(String clubUserName,Integer status,Integer cursor,Integer count,Integer pageNum,Integer pageSize){
  1160. PageHelper.startPage(pageNum, pageSize);
  1161. List<ChallengeRoundVo> listChallengeRoundVo=authMapper.getPublishedVideoList(clubUserName,status);
  1162. PageInfo<ChallengeRoundVo> pageData = new PageInfo<>(listChallengeRoundVo);
  1163. //调用抖音api获取视频数据
  1164. String dyopenId=null;
  1165. String DYaccessToken=null;
  1166. if(redisService.getExpireTime("DyopenId")>0&&redisService.getExpireTime("DYaccessToken")>0){
  1167. dyopenId=redisService.get("DyopenId").toString();
  1168. DYaccessToken=redisService.get("DYaccessToken").toString();
  1169. }
  1170. Long flag=1l;
  1171. List<DyVideoInfoVo> list=new ArrayList<>();
  1172. while (flag!=0){
  1173. if (flag==1){flag=0l;}
  1174. String data = getVideoList(dyopenId, flag, count, DYaccessToken);
  1175. JSONObject paramslist = JSONObject.parseObject(data);
  1176. Integer error_code = Integer.valueOf(paramslist.getString("error_code"));
  1177. if(error_code>0){
  1178. break;
  1179. }
  1180. String resultList = paramslist.getString("list");
  1181. String cor = paramslist.getString("cursor");
  1182. flag=Long.parseLong(cor);
  1183. List<DyVideoInfoVo> listDyVideoInfoVo= JSONArray.parseArray(resultList, DyVideoInfoVo.class);
  1184. if(listDyVideoInfoVo!=null&&listDyVideoInfoVo.size()>0){
  1185. for (DyVideoInfoVo dv:listDyVideoInfoVo) {
  1186. list.add(dv);
  1187. }
  1188. }
  1189. }
  1190. if(listChallengeRoundVo!=null&&listChallengeRoundVo.size()>0){
  1191. for (ChallengeRoundVo ChallengeRoundVo:listChallengeRoundVo) {
  1192. if(StringUtils.isEmpty(ChallengeRoundVo.getDiggCount())){
  1193. ChallengeRoundVo.setDiggCount("0");
  1194. }
  1195. if(StringUtils.isEmpty(ChallengeRoundVo.getPlayCount())){
  1196. ChallengeRoundVo.setPlayCount("0");
  1197. }
  1198. if(list!=null&&list.size()>0){
  1199. for (DyVideoInfoVo dyVideoInfoVo:list) {
  1200. if(dyVideoInfoVo.getItem_id().equals(ChallengeRoundVo.getItemId())){
  1201. StatisticsVo StatisticsVo= JSONObject.parseObject(dyVideoInfoVo.getStatistics(), StatisticsVo.class);
  1202. ChallengeRoundVo.setDiggCount(StatisticsVo.getDigg_count());
  1203. ChallengeRoundVo.setPlayCount(StatisticsVo.getPlay_count());
  1204. break;
  1205. }
  1206. }
  1207. }
  1208. }
  1209. }
  1210. //根据点赞量降序排序
  1211. // PageHelper.startPage(pageNum, pageSize);
  1212. List<ChallengeRoundVo> collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序
  1213. PageInfo<ChallengeRoundVo> pageDa = new PageInfo<>(collect);
  1214. return ResponseJson.success(pageDa);
  1215. }
  1216. /**
  1217. * 获取已发布视频列表(后端)
  1218. * @param mobile
  1219. * @param authParty
  1220. * @param status
  1221. * @param cursor
  1222. * @param count
  1223. * @param authUserId
  1224. * @return
  1225. */
  1226. @Override
  1227. public ResponseJson<PageInfo<ChallengeRoundVo>> getPublishedVideo(String mobile,String authParty,Integer status,Integer cursor,Integer count,Integer authUserId,Integer pageNum,Integer pageSize){
  1228. PageHelper.startPage(pageNum, pageSize);
  1229. List<ChallengeRoundVo> listChallengeRoundVo=authMapper.getPublishedVideo(mobile,authParty,status,authUserId);
  1230. PageInfo<ChallengeRoundVo> pageData = new PageInfo<>(listChallengeRoundVo);
  1231. //调用抖音api获取视频数据
  1232. String dyopenId=null;
  1233. String DYaccessToken=null;
  1234. if(redisService.getExpireTime("DyopenId")>0&&redisService.getExpireTime("DYaccessToken")>0){
  1235. dyopenId=redisService.get("DyopenId").toString();
  1236. DYaccessToken=redisService.get("DYaccessToken").toString();
  1237. }
  1238. Long flag=1l;
  1239. List<DyVideoInfoVo> list=new ArrayList<>();
  1240. while (flag!=0){
  1241. if (flag==1){flag=0l;}
  1242. String data = getVideoList(dyopenId, flag, count, DYaccessToken);
  1243. JSONObject paramslist = JSONObject.parseObject(data);
  1244. Integer error_code = Integer.valueOf(paramslist.getString("error_code"));
  1245. if(error_code>0){
  1246. break;
  1247. }
  1248. String resultList = paramslist.getString("list");
  1249. String cor = paramslist.getString("cursor");
  1250. flag=Long.parseLong(cor);
  1251. List<DyVideoInfoVo> listDyVideoInfoVo= JSONArray.parseArray(resultList, DyVideoInfoVo.class);
  1252. if(listDyVideoInfoVo!=null&&listDyVideoInfoVo.size()>0){
  1253. for (DyVideoInfoVo dv:listDyVideoInfoVo) {
  1254. list.add(dv);
  1255. }
  1256. }
  1257. }
  1258. if(listChallengeRoundVo!=null&&listChallengeRoundVo.size()>0){
  1259. for (ChallengeRoundVo ChallengeRoundVo:listChallengeRoundVo) {
  1260. if(StringUtils.isEmpty(ChallengeRoundVo.getDiggCount())){
  1261. ChallengeRoundVo.setDiggCount("0");
  1262. }
  1263. if(StringUtils.isEmpty(ChallengeRoundVo.getPlayCount())){
  1264. ChallengeRoundVo.setPlayCount("0");
  1265. }
  1266. if(list!=null&&list.size()>0){
  1267. for (DyVideoInfoVo dyVideoInfoVo:list) {
  1268. if(dyVideoInfoVo.getItem_id().equals(ChallengeRoundVo.getItemId())){
  1269. StatisticsVo StatisticsVo= JSONObject.parseObject(dyVideoInfoVo.getStatistics(), StatisticsVo.class);
  1270. ChallengeRoundVo.setDiggCount(StatisticsVo.getDigg_count());
  1271. ChallengeRoundVo.setPlayCount(StatisticsVo.getPlay_count());
  1272. break;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. }
  1278. //根据点赞量降序排序
  1279. // PageHelper.startPage(pageNum, pageSize);
  1280. List<ChallengeRoundVo> collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序
  1281. PageInfo<ChallengeRoundVo> pageDa = new PageInfo<>(collect);
  1282. return ResponseJson.success(pageDa);
  1283. }
  1284. /**
  1285. * 获取机构已发布视频的机构下拉列表
  1286. * @param authUserId
  1287. * @return
  1288. */
  1289. @Override
  1290. public ResponseJson<List<ChallengeRoundVo>> getAuthPartylist(Integer authUserId){
  1291. return ResponseJson.success(authMapper.getAuthPartylist(authUserId));
  1292. }
  1293. /**
  1294. * 保存活动信息
  1295. * @param startTime
  1296. * @param endTime
  1297. * @param status
  1298. * @return
  1299. */
  1300. @Override
  1301. public ResponseJson saveActivityTime(String startTime,String endTime,Integer status,Integer authUserId){
  1302. //如果数据库有值则修改,没值则新增
  1303. List<ChallengeActivityVo> challengeList = authMapper.checkActivityId();
  1304. List<Integer> authUserIdList=new ArrayList<>();
  1305. for (ChallengeActivityVo ac:challengeList) {
  1306. authUserIdList.add(ac.getAuthUserId());
  1307. }
  1308. if(challengeList.size()<0||!authUserIdList.contains(authUserId)){
  1309. authMapper.saveActivityInfo(startTime,endTime,status,authUserId);
  1310. }else {
  1311. authMapper.upActivityInfo(startTime,endTime,status,authUserId);
  1312. }
  1313. return ResponseJson.success();
  1314. }
  1315. /**
  1316. * 获取活动信息
  1317. * @return
  1318. */
  1319. @Override
  1320. public ResponseJson<ChallengeActivityVo> getActivityTime(Integer authUserId){
  1321. return ResponseJson.success(authMapper.getActivityTime(authUserId));
  1322. }
  1323. /**
  1324. * 判断shareId是否存在
  1325. * @param shareId
  1326. * @return
  1327. */
  1328. @Override
  1329. public boolean getShareId(String shareId){
  1330. return StringUtils.isNotEmpty(authMapper.getShareId(shareId));
  1331. }
  1332. /**
  1333. * 根据ShareId保存itemId (webhook触发时调用)
  1334. * @param shareId
  1335. * @param itemId
  1336. */
  1337. @Override
  1338. public void savaItemIdByShareId(String shareId,String itemId){
  1339. authMapper.savaItemIdByShareId(shareId,itemId);
  1340. }
  1341. @Override
  1342. public ResponseJson<ChallengeActivityVo> getActivitty(Integer authUserId){
  1343. ChallengeActivityVo activityTime = authMapper.getActivityTime(authUserId);
  1344. Date date=new Date();
  1345. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1346. String releaseTime = sf.format(date).replace("T", "");
  1347. if(activityTime!=null){
  1348. if(activityTime.getStartTime().compareTo(releaseTime)>0){
  1349. activityTime.setActivityState(0);
  1350. }else if(activityTime.getStartTime().compareTo(releaseTime)<0&&activityTime.getEndTime().compareTo(releaseTime)>0){
  1351. activityTime.setActivityState(1);
  1352. }else {
  1353. activityTime.setActivityState(2);
  1354. }
  1355. }
  1356. return ResponseJson.success(activityTime);
  1357. }
  1358. /**
  1359. * 根据authId获取手机号
  1360. * @param authId
  1361. * @return
  1362. */
  1363. @Override
  1364. public String getMobileByAuthId(Integer authId){
  1365. return authMapper.getMobileByAuthId(authId);
  1366. }
  1367. /**
  1368. * 根据authId获取手机号
  1369. * @param authId
  1370. * @return
  1371. */
  1372. @Override
  1373. public String getAuthUserName(Integer authId){
  1374. return authMapper.getAuthUserName(authId);
  1375. }
  1376. /**
  1377. * 保存抖音口令
  1378. * @param authId
  1379. * @return
  1380. */
  1381. @Override
  1382. public void savaDyCommand(Integer authId,String content){
  1383. authMapper.savaDyCommand(authId,content);
  1384. }
  1385. /**
  1386. * 根据authId获取ossName
  1387. * @param videoID
  1388. * @return
  1389. */
  1390. @Override
  1391. public String getOssNameAuthId(Integer videoID){
  1392. return authMapper.getOssNameId(videoID);
  1393. }
  1394. /**
  1395. * 根据authId删除视频
  1396. * @param videoID
  1397. * @return
  1398. */
  1399. @Override
  1400. public void deleteVideoByAuthId(Integer videoID){
  1401. authMapper.deleteVideoById(videoID);
  1402. }
  1403. @Override
  1404. public ResponseJson downLoadChoseZip(String fileId,HttpServletResponse response){
  1405. if (fileId.contains(",")) {
  1406. String[] split = fileId.split(",");
  1407. ArrayList<ChallengeRoundVo> fileTreeVos = new ArrayList<>();
  1408. for (String s : split) {
  1409. ChallengeRoundVo file = authMapper.getChallengeRoundInfo(Integer.valueOf(s));
  1410. fileTreeVos.add(file);
  1411. }
  1412. //有package则在服务器固定路径new file.mkdir
  1413. UUID uuid = UUID.randomUUID();
  1414. String zipPath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/" + uuid;
  1415. String filePath = zipPath;
  1416. if ("dev".equals(active)) {
  1417. zipPath = "D:\\caimei-workSpace\\file\\" + uuid;
  1418. filePath = zipPath;
  1419. }
  1420. boolean mkdirs = new File(filePath).mkdirs();
  1421. Assert.isTrue(mkdirs, "文件夹创建失败");
  1422. for (ChallengeRoundVo challengeRoundVo : fileTreeVos) {
  1423. //普通文件直接下载到临时文件夹uuid下
  1424. String fileName = "";
  1425. String ossurl = challengeRoundVo.getOssUrl();
  1426. ossurl.indexOf(".");
  1427. String title=challengeRoundVo.getTitle();
  1428. Pattern pattern = Pattern.compile("[\\s\\\\/:\\*\\?\\\"<>\\|]");
  1429. Matcher matcher = pattern.matcher(title);
  1430. title= matcher.replaceAll("");
  1431. if(title.length()>50){
  1432. title= title.substring(0,50);
  1433. }
  1434. if ("dev".equals(active)) {
  1435. fileName = zipPath + "\\"+title + ossurl.substring(ossurl.lastIndexOf("."));
  1436. } else {
  1437. fileName = zipPath + "/"+title + ossurl.substring(ossurl.lastIndexOf("."));
  1438. }
  1439. OSSUtils.downFileByFilePath("authFile/", challengeRoundVo.getOssName(), fileName);
  1440. // else {
  1441. // //文件夹在uuid文件夹下创建自己包名的文件夹
  1442. // String param = fileTreeVo.getId() + "," + authUserId;
  1443. // String myPath = "";
  1444. // myPath = filePath + "/" + fileTreeVo.getFileName();
  1445. // if ("dev".equals(active)) {
  1446. // myPath = filePath + "\\" + fileTreeVo.getFileName();
  1447. // }
  1448. // boolean dirs = new File(myPath).mkdirs();
  1449. // Assert.isTrue(dirs, "文件夹创建失败");
  1450. // recursion(param, myPath);
  1451. // }
  1452. }
  1453. //压缩
  1454. FileZipUtils.compress(zipPath, "", true);
  1455. String s = zipPath + ".zip";
  1456. String fileName = uuid + ".zip";
  1457. File file = new File(s);
  1458. try {
  1459. if (file.exists()) {
  1460. FileInputStream fileInputStream = new FileInputStream(file);
  1461. ServletOutputStream outputStream = response.getOutputStream();
  1462. // 设置下载文件的mineType,告诉浏览器下载文件类型
  1463. // int i = fileName.lastIndexOf(".");
  1464. // String substring = fileName.substring(i + 1, filePath.length());
  1465. response.setContentType("application/zip");
  1466. // 设置一个响应头,无论是否被浏览器解析,都下载
  1467. response.setHeader("Content-disposition", "attachment; filename=" + fileName);
  1468. byte[] bytes = new byte[1024];
  1469. int len;
  1470. while ((len = fileInputStream.read(bytes)) != -1) {
  1471. outputStream.write(bytes, 0, len);
  1472. }
  1473. fileInputStream.close();
  1474. outputStream.close();
  1475. }
  1476. } catch (IOException e) {
  1477. e.printStackTrace();
  1478. }
  1479. file.delete();
  1480. FileZipUtils.deleteFile(new File(zipPath));
  1481. }else {
  1482. ArrayList<ChallengeRoundVo> fileTreeVos = new ArrayList<>();
  1483. ChallengeRoundVo f = authMapper.getChallengeRoundInfo(Integer.valueOf(fileId));
  1484. fileTreeVos.add(f);
  1485. //有package则在服务器固定路径new file.mkdir
  1486. UUID uuid = UUID.randomUUID();
  1487. String zipPath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/" + uuid;
  1488. String filePath = zipPath;
  1489. if ("dev".equals(active)) {
  1490. zipPath = "D:\\caimei-workSpace\\file\\" + uuid;
  1491. filePath = zipPath;
  1492. }
  1493. boolean mkdirs = new File(filePath).mkdirs();
  1494. Assert.isTrue(mkdirs, "文件夹创建失败");
  1495. for (ChallengeRoundVo challengeRoundVo : fileTreeVos) {
  1496. //普通文件直接下载到临时文件夹uuid下
  1497. String fileName = "";
  1498. String ossurl = challengeRoundVo.getOssUrl();
  1499. String title=challengeRoundVo.getTitle();
  1500. Pattern pattern = Pattern.compile("[\\s\\\\/:\\*\\?\\\"<>\\|]");
  1501. Matcher matcher = pattern.matcher(title);
  1502. title= matcher.replaceAll("");
  1503. if(title.length()>50){
  1504. title= title.substring(0,50);
  1505. }
  1506. if ("dev".equals(active)) {
  1507. fileName = zipPath + "\\"+title +ossurl.substring(ossurl.lastIndexOf("."));
  1508. } else {
  1509. fileName = zipPath + "/"+title + ossurl.substring(ossurl.lastIndexOf("."));
  1510. }
  1511. OSSUtils.downFileByFilePath("authFile/", challengeRoundVo.getOssName(), fileName);
  1512. // else {
  1513. // //文件夹在uuid文件夹下创建自己包名的文件夹
  1514. // String param = fileTreeVo.getId() + "," + authUserId;
  1515. // String myPath = "";
  1516. // myPath = filePath + "/" + fileTreeVo.getFileName();
  1517. // if ("dev".equals(active)) {
  1518. // myPath = filePath + "\\" + fileTreeVo.getFileName();
  1519. // }
  1520. // boolean dirs = new File(myPath).mkdirs();
  1521. // Assert.isTrue(dirs, "文件夹创建失败");
  1522. // recursion(param, myPath);
  1523. // }
  1524. }
  1525. //压缩
  1526. FileZipUtils.compress(zipPath, "", true);
  1527. String s = zipPath + ".zip";
  1528. String fileName = uuid + ".zip";
  1529. File file = new File(s);
  1530. try {
  1531. if (file.exists()) {
  1532. FileInputStream fileInputStream = new FileInputStream(file);
  1533. ServletOutputStream outputStream = response.getOutputStream();
  1534. // 设置下载文件的mineType,告诉浏览器下载文件类型
  1535. // int i = fileName.lastIndexOf(".");
  1536. // String substring = fileName.substring(i + 1, filePath.length());
  1537. response.setContentType("application/zip");
  1538. // 设置一个响应头,无论是否被浏览器解析,都下载
  1539. response.setHeader("Content-disposition", "attachment; filename=" + fileName);
  1540. byte[] bytes = new byte[1024];
  1541. int len;
  1542. while ((len = fileInputStream.read(bytes)) != -1) {
  1543. outputStream.write(bytes, 0, len);
  1544. }
  1545. fileInputStream.close();
  1546. outputStream.close();
  1547. }
  1548. } catch (IOException e) {
  1549. e.printStackTrace();
  1550. }
  1551. file.delete();
  1552. FileZipUtils.deleteFile(new File(zipPath));
  1553. }
  1554. return null;
  1555. }
  1556. }