package com.caimei.service.auth.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.caimei.components.RedisService; import com.caimei.config.FastDfsClient; import com.caimei.mapper.cmMapper.AuthMapper; import com.caimei.mapper.cmMapper.AuthProductMapper; import com.caimei.mapper.ldmMapper.LdmMapper; import com.caimei.model.ResponseJson; import com.caimei.model.po.*; import com.caimei.model.vo.*; import com.caimei.service.auth.AuthProductService; import com.caimei.service.auth.AuthService; import com.caimei.service.auth.ShopService; import com.caimei.service.auth.UploadService; import com.caimei.utils.*; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.swing.*; import java.awt.*; import java.awt.Font; import java.io.*; import java.math.BigDecimal; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Description * * @author : Aslee * @date : 2021/5/11 */ @Slf4j @Service public class AuthServiceImpl implements AuthService { @Resource private AuthMapper authMapper; @Resource private LdmMapper ldmMapper; @Value("${caimei.zpapi}") private String zpServer; private AuthProductService authProductService; @Autowired public void setAuthProductService(AuthProductService authProductService) { this.authProductService = authProductService; } private ShopService shopService; @Autowired public void setShopService(ShopService shopService) { this.shopService = shopService; } private UploadService uploadService; @Autowired public void setUploadService(UploadService uploadService) { this.uploadService = uploadService; } @Value("${spring.profiles.active}") private String active; @Autowired private FastDfsClient client; @Value("${caimei.imageDomain}") private String imageDomain; @Resource private RedisService redisService; @Override public ResponseJson> getAuthList(Integer listType, Integer authUserId, String authParty, String mobile, Integer status, Integer starFlag, Integer auditStatus, Integer lowerAuditStatus, Integer shopAuditStatus, Integer sendStatus,String authCode, Integer pageNum, Integer pageSize) { listType = null == listType ? 1 : listType; PageHelper.startPage(pageNum, pageSize); List authList = authMapper.getAuthList(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus,authCode); PageInfo pageData = new PageInfo<>(authList); return ResponseJson.success(pageData); } @Override public ResponseJson> getAuthListAll(Integer listType, Integer authUserId, String authParty, String mobile, Integer status, Integer starFlag, Integer auditStatus, Integer lowerAuditStatus, Integer shopAuditStatus, Integer sendStatus, String name, String snCode, Integer pageNum, Integer pageSize) { listType = null == listType ? 1 : listType; PageHelper.startPage(pageNum, pageSize); List authList = authMapper.getAuthListAll(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus, name, snCode); PageInfo pageData = new PageInfo<>(authList); return ResponseJson.success(pageData); } @Override public ResponseJson updateAuthStatus(Integer authId, Integer status) { if (null == authId) { return ResponseJson.error("请输入授权id"); } if (null == status) { return ResponseJson.error("请输入要更新的状态值"); } authMapper.updateAuthStatusByAuthId(authId, status); if (0 == status) { return ResponseJson.success("下线品牌授权成功"); } else { return ResponseJson.success("上线品牌授权成功"); } } @Override public ResponseJson deleteAuth(Integer authId) { if (null == authId) { return ResponseJson.error("参数异常,请输入授权id"); } // 删除品牌授权 authMapper.deleteAuthByAuthId(authId); // 删除轮播图 authMapper.deleteBanner(authId); // 删除商品及商品参数 List productIdList = authProductService.getProductIdsByAuthId(authId); productIdList.forEach(productId -> { if (null != productId) { authProductService.deleteProduct(productId); } }); return ResponseJson.success("删除品牌授权成功"); } @Override public ResponseJson getAuthFormData(Integer authId) { if (null == authId) { return ResponseJson.error("参数异常,机构id不能为空", null); } AuthFormVo authFormVo = authMapper.getAuthFormById(authId); //该机构关联机构用集合形式返回便于前端赋值 if (null != authFormVo.getRelationId() && !"".equals(authFormVo.getRelationId())) { String[] relationIdList = authFormVo.getRelationId().split(","); List authIdList = authMapper.getAuthIdList(relationIdList); authFormVo.setReleationClubList(authIdList); } if (null != authFormVo.getLng()) { authFormVo.setLngAndLat(authFormVo.getLng() + "," + authFormVo.getLat()); } List bannerList = authMapper.getBannerList(authId); authFormVo.setBannerList(bannerList); return ResponseJson.success(authFormVo); } @Override public ResponseJson> getAuthSelectList(Integer authUserId) { List authList = authMapper.getAuthList(1, authUserId, null, null, null, null, null, null, null, null,null); return ResponseJson.success(authList); } @Override public ResponseJson importLdmImage(Integer authUserId) { List ldmClubData = ldmMapper.getLdmClubData(null, 0); ldmClubData.forEach(ldmClub -> { String pic2 = ldmClub.getPic2(); String pic3 = ldmClub.getPic3(); String pic4 = ldmClub.getPic4(); List authList = authMapper.getAuthByNameAndAddress(ldmClub.getAuthParty(), ldmClub.getAddress()); if (null != authList && authList.size() > 0) { if (authList.size() > 1) { log.info(">>>>>>>>>>>>>>>>>>>>>导入ldm门店图错误:对应门店过多,门店名称:" + ldmClub.getAuthParty()); } else { AuthVo auth = authList.get(0); Integer authId = auth.getAuthId(); if (StringUtils.isNotEmpty(pic2) || StringUtils.isNotEmpty(pic3) || StringUtils.isNotEmpty(pic4)) { authMapper.deleteBanner(authId); insertBanner(pic2, authId); insertBanner(pic3, authId); insertBanner(pic4, authId); } if (StringUtils.isNotEmpty(ldmClub.getRemarks())) { authMapper.updateRemarks(authId, ldmClub.getRemarks()); } } } else { log.info(">>>>>>>>>>>>>>>>>>>>>导入ldm门店图错误:找不到对应门店,门店名称:" + ldmClub.getAuthParty()); } }); return ResponseJson.success(); } @Override public ResponseJson checkAuth(Integer authId) { authMapper.checkAuth(authId); return ResponseJson.success(); } @Override public ResponseJson starAuth(Integer authId, Integer starFlag, String starNum) { authMapper.starAuth(authId, starFlag, starNum); return ResponseJson.success(); } private void insertBanner(String pic, Integer authId) { if (StringUtils.isNotEmpty(pic)) { String imagePath = "https://wangdian.skinovachina.com" + pic; String fileName = imagePath.substring(imagePath.lastIndexOf("/") + 1); try { String banner = uploadService.saveFileByUrl(imagePath, fileName); authMapper.insertBanner(authId, banner); } catch (Exception e) { e.printStackTrace(); } } } @Override public ResponseJson saveAuth(CmBrandAuthPo auth, List bannerList, boolean importFlag, Integer source) { Integer authId = auth.getId(); boolean insertFlag = null == authId; AuthVo dbAuth = null; if (!insertFlag) { dbAuth = authMapper.getAuthById(authId); } String authParty = auth.getAuthParty(); if (StringUtils.isBlank(authParty)) { return ResponseJson.error("参数异常,请输入授权机构名称"); } if (null == auth.getFirstClubType()) { return ResponseJson.error("请勾选机构类型"); } if ((1 == auth.getFirstClubType() || 2 == auth.getFirstClubType()) && null == auth.getSecondClubType()) { return ResponseJson.error("请勾选二级机构类型"); } if (1 == auth.getFirstClubType() && StringUtils.isEmpty(auth.getMedicalLicenseImage())) { return ResponseJson.error("请上传医疗许可证"); } if (null == auth.getEmpNum()) { return ResponseJson.error("请输入员工人数"); } if (1 == source) { if (null == auth.getCreateBy()) { return ResponseJson.error("参数异常,请输入创建人id"); } /*if (1 == auth.getAuthImageType() && StringUtils.isEmpty(auth.getAuthImageLogo())) { return ResponseJson.error("授权牌logo不能为空"); }*/ if (2 == auth.getAuthImageType() && StringUtils.isEmpty(auth.getAuthImage())) { return ResponseJson.error("授权牌不能为空"); } } else { // 机构添加默认模板库生成 auth.setAuthImageType(1); } if (!importFlag) { if (null == auth.getProvinceId() || null == auth.getCityId() || null == auth.getTownId() || StringUtils.isEmpty(auth.getAddress()) || null == auth.getLng() || null == auth.getLat()) { return ResponseJson.error("参数异常,地址信息异常"); } if (StringUtils.isEmpty(auth.getLogo())) { return ResponseJson.error("参数异常,请上传机构logo"); } if (null == bannerList || bannerList.size() <= 0) { return ResponseJson.error("参数异常,请上传轮播图"); } } // 供应商保存,直接上线;机构保存,需要供应商审核通过后才上线 if (null != dbAuth && 1 != dbAuth.getAuditStatus()) { // 被驳回的数据,编辑变为待审核状态 auth.setStatus(2); auth.setAuditStatus(2); } else { auth.setStatus(1 == source ? 1 : 2); auth.setAuditStatus(1 == source ? 1 : 2); } Integer adminUserId = authMapper.getAdminUserId(); auth.setAuditBy(adminUserId); auth.setAuditTime(new Date()); if (1 == source) { auth.setShopAuditBy(auth.getCreateBy()); auth.setShopAuditTime(new Date()); } auth.setDelFlag(0); auth.setCheckFlag(0); auth.setShopAuditStatus(1 == source ? 1 : 2); /* 保存授权 */ if (insertFlag) { authMapper.insertAuth(auth); } else { authMapper.updateAuthByAuthId(auth); // 删除原有的轮播图 authMapper.deleteBanner(auth.getId()); } // 保存之后生成授权牌和水印授权牌 String authImage = null; if (1 == auth.getAuthImageType()) { // 模板库生成 // 获取对应模板 TemplateVo authTemplate = authMapper.getAuthTemplate(auth.getId(), null, 1); authImage = generateAuthImage(authTemplate, auth); auth.setAuthImage(authImage); } // 添加水印 if (StringUtils.isNotEmpty(auth.getAuthImage())) { auth.setPcAuthImage(addWaterMark(auth.getAuthImage(), 1)); auth.setAppletsAuthImage(addWaterMark(auth.getAuthImage(), 2)); authMapper.updateAuthImage(auth); } // 保存轮播图 if (null != bannerList) { bannerList.forEach(banner -> authMapper.insertBanner(auth.getId(), banner)); } return ResponseJson.success("保存品牌授权成功", auth); } @Override public String addWaterMark(String image, Integer type) { try { //type:1pc,2applets ClassPathResource classPathResource = new ClassPathResource("/images/newPcWaterMark.png"); InputStream inputStreamImg = classPathResource.getInputStream(); Image pcWaterMarkImg = ImageIO.read(inputStreamImg); classPathResource = new ClassPathResource("/images/newAppletsWaterMark.png"); inputStreamImg = classPathResource.getInputStream(); Image appletsWaterMarkImg = ImageIO.read(inputStreamImg); String img = ImageUtils.markImageByIcon(type == 1 ? pcWaterMarkImg : appletsWaterMarkImg, image, null); String imagePath = null; if (StringUtils.isNotEmpty(img)) { MultipartFile imgFile = Base64Util.base64ToMultipart(img); if (null != imgFile) { imagePath = uploadService.saveFile(imgFile); } log.info(">>>>>>>>>>>>>>>>水印图片上传成功:" + imagePath); } else { log.info(">>>>>>>>>>>>>>>>水印图片上传失败"); } return imagePath; } catch (Exception e) { e.printStackTrace(); } return null; } @Override public String generateAuthImage(TemplateVo authTemplate, CmBrandAuthPo auth) { if (null != authTemplate) { // 根据模板id设置相关数据 Map templateInfo = getTemplateInfo(authTemplate, auth); Object templateImage = templateInfo.get("templateImage"); if (null != templateImage) { String authImage = ImageUtils.generateAuthImage(templateInfo); log.info("【图片上传】>>>>>>>>>>>>>>>>图片临时路径:" + authImage); // 临时图片 File tempFile = new File(authImage); String imageUrl = null; try { imageUrl = imageDomain + "/" + client.uploadFile(authImage); } catch (Exception e) { e.printStackTrace(); } // 删除临时图片 boolean delete = tempFile.delete(); log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时图片:" + delete); return imageUrl; } else { return null; } } return null; } private Map getTemplateInfo(TemplateVo template, CmBrandAuthPo auth) { HashMap map = new HashMap<>(); Integer templateId = template.getTemplateId(); if (1 == templateId) { map.put("templateImage", template.getTemplateImage()); double rate = 0.15; if (StringUtils.isNotEmpty(auth.getAuthImageLogo())) { // 获取授权牌logo位置 try { ImageIcon imageIcon = new ImageIcon(new URL(template.getTemplateImage())); Image srcImg = imageIcon.getImage(); int srcWidth = srcImg.getWidth(null); ImageIcon authImageLogo = new ImageIcon(new URL(auth.getAuthImageLogo())); Image authLogo = authImageLogo.getImage(); int authLogoWidth = authLogo.getWidth(null); int x = (srcWidth - (int) Math.round(238 * rate) - authLogoWidth) / 2 + (int) Math.round(238 * rate); int y = (int) Math.round(1230 * rate); map.put("addImage1_x", x); map.put("addImage1_y", y); map.put("addImage1_image", auth.getAuthImageLogo()); } catch (Exception e) { e.printStackTrace(); } } // 添加认证编号信息 if (StringUtils.isNotEmpty(auth.getAuthCode())) { map.put("addWord1_content", auth.getAuthCode()); map.put("addWord1_color", "218,185,107"); map.put("addWord1_type", "思源宋体"); map.put("addWord1_style", Font.BOLD); map.put("addWord1_size", (int) Math.round(90 * rate)); map.put("addWord1_x", (int) Math.round(2168 * rate)); map.put("addWord1_y", (int) Math.round(3157 * rate)); } // 添加认证日期信息 if (null != auth.getAuthDate()) { SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd"); map.put("addWord2_content", format.format(auth.getAuthDate())); map.put("addWord2_color", "218,185,107"); map.put("addWord2_type", "思源宋体"); map.put("addWord2_style", Font.PLAIN); map.put("addWord2_size", (int) Math.round(90 * rate)); map.put("addWord2_x", (int) Math.round(2085 * rate)); map.put("addWord2_y", (int) Math.round(3289 * rate)); } // 添加二维码信息 if (StringUtils.isNotEmpty(template.getQrPosition())) { String qrCodeLink = zpServer + "/" + auth.getAuthUserId() + "/" + authMapper.getPrefix(auth.getAuthUserId()) + "/approve/club/detail?id=" + auth.getId(); map.put("addQr1_link", qrCodeLink); map.put("addQr1_size", template.getQrSize()); String[] split = template.getQrPosition().split(","); if (split.length == 2) { map.put("addQr1_x", Integer.parseInt(split[0])); map.put("addQr1_y", Integer.parseInt(split[1])); } } } return map; } @Override public ResponseJson auditAuth(Integer authId, Integer auditStatus, String invalidReason, Integer auditBy, Integer source) { if (authId == null) { return ResponseJson.error("请输入授权id"); } if (auditStatus == null) { return ResponseJson.error("请输入审核结果"); } if (auditStatus == 0 && StringUtils.isEmpty(invalidReason)) { return ResponseJson.error("请输入审核不通过的原因"); } source = null == source ? 1 : source; Date auditTime = new Date(); // 授权状态更新 Integer status = null; if (auditStatus == 0) { // 审核不通过,下线授权 status = 0; } else { // 审核通过,上线授权 status = 1; } if (1 == source) { authMapper.updateAuthAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime); } if (2 == source) { authMapper.updateAuthShopAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime); } return ResponseJson.success("审核机构认证成功"); } @Override @Transactional(rollbackFor = Exception.class) public ResponseJson importDataByExcel(MultipartFile file, Integer authUserId, Integer createBy) { String originalFilename = file.getOriginalFilename(); String randomStr = UUID.randomUUID().toString(); assert originalFilename != null; int index = originalFilename.lastIndexOf("."); String extName = originalFilename.substring(index); String filePath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/"; if ("dev".equals(active)) { filePath = "D:\\WorkSpace\\file\\tempImport\\"; } filePath += randomStr + extName; try { File tempFile = new File(filePath); if (!tempFile.exists()) { tempFile.mkdirs(); } file.transferTo(tempFile); return saveExcelData(filePath, authUserId, createBy); } catch (IOException e) { e.printStackTrace(); } log.info(">>>>>>>>>>>>>>>>文件临时路径:" + filePath); return null; } private ResponseJson saveExcelData(String filePath, Integer authUserId, Integer createBy) { //判断是否为excel类型文件 if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) { System.out.println("文件不是excel类型"); } // 获取供应商品牌 List shopBrands = shopService.getShopBrands(authUserId); // 授权列表 List authImportList = new ArrayList<>(); try { FileInputStream fis = new FileInputStream(filePath); // 得到表格数据 XSSFWorkbook workbook = new XSSFWorkbook(fis); //得到第一个工作表(机构表) XSSFSheet authPartySheet = workbook.getSheetAt(0); //获得表头 Row rowHead = authPartySheet.getRow(0); //判断表头是否正确 if (9 != rowHead.getLastCellNum() || !"机构名称".equals(rowHead.getCell(0).getStringCellValue())) { return ResponseJson.error("授权机构表格式错误"); } // 获得数据的总行数 int authPartyRowNum = authPartySheet.getLastRowNum(); //获得所有数据 for (int i = 1; i <= authPartyRowNum; i++) { //获得第i行对象 Row authPartyRow = authPartySheet.getRow(i); if (null == authPartyRow) { break; } Cell cell = null; // 校验机构名称 cell = authPartyRow.getCell(0); cell.setCellType(CellType.STRING); String authParty = cell.getStringCellValue(); if (StringUtils.isBlank(authParty)) { return ResponseJson.error("第" + i + 1 + "行机构名称不能为空"); } // 校验省市区 cell = authPartyRow.getCell(1); cell.setCellType(CellType.STRING); String area = cell.getStringCellValue(); if (StringUtils.isBlank(area)) { return ResponseJson.error("第" + i + 1 + "行所在地区不能为空"); } String[] areaSplit = area.split("/"); if (areaSplit.length < 2 || areaSplit.length > 3) { return ResponseJson.error("第" + i + 1 + "行所在地区格式错误"); } // 省份 String provinceName = areaSplit[0]; if (StringUtils.isBlank(provinceName)) { return ResponseJson.error("第" + i + 1 + "行省份不能为空"); } if (provinceName.length() > 2) { provinceName = provinceName.substring(0, provinceName.length() - 1).trim(); } Integer provinceId = authMapper.getProvinceId(provinceName); // 市名 String cityName = areaSplit[1]; if (StringUtils.isBlank(cityName)) { return ResponseJson.error("第" + i + 1 + "行市名不能为空"); } if (cityName.length() > 2) { cityName = cityName.substring(0, cityName.length() - 1).trim(); } Integer cityId = authMapper.getCityId(cityName); Integer townId = null; if (areaSplit.length > 2) { // 区名 String townName = areaSplit[2]; if (StringUtils.isNotEmpty(townName) && townName.length() > 2) { townName = townName.substring(0, townName.length() - 1).trim(); } List townList = authMapper.getTownList(townName); for (int j = 0; j < townList.size(); j++) { TownPo town = townList.get(j); if (null == townId) { if (null != cityId) { if (town.getCityId().equals(cityId)) { townId = town.getTownId(); } } else { Integer checkCityId = authMapper.getCityIdByTownId(town.getTownId()); if (null != provinceId && null != checkCityId) { Integer checkProvinceId = authMapper.getProvinceIdByCityId(cityId); if (provinceId.equals(checkProvinceId)) { cityId = checkCityId; townId = town.getTownId(); } } } } } } // 校验详细地址 cell = authPartyRow.getCell(2); cell.setCellType(CellType.STRING); String address = cell.getStringCellValue(); if (StringUtils.isBlank(address)) { return ResponseJson.error("第" + i + 1 + "行详细地址不能为空"); } // 校验经纬度 cell = authPartyRow.getCell(3); cell.setCellType(CellType.STRING); String lngAndLat = cell.getStringCellValue(); if (StringUtils.isBlank(lngAndLat)) { return ResponseJson.error("第" + i + 1 + "行经纬度不能为空"); } String[] split = lngAndLat.split(","); if (2 != split.length) { return ResponseJson.error("第" + i + 1 + "行经纬度格式错误"); } BigDecimal lng = new BigDecimal(split[0]); BigDecimal lat = new BigDecimal(split[1]); // 校验联系电话 cell = authPartyRow.getCell(4); cell.setCellType(CellType.STRING); String mobile = cell.getStringCellValue(); if (StringUtils.isBlank(mobile)) { return ResponseJson.error("第" + i + 1 + "行联系电话不能为空"); } // 认证编号 cell = authPartyRow.getCell(5); cell.setCellType(CellType.STRING); String authCode = cell.getStringCellValue(); // 认证日期 Date authDate = null; cell = authPartyRow.getCell(6); cell.setCellType(CellType.STRING); String authDateStr = cell.getStringCellValue(); if (StringUtils.isNotBlank(authDateStr)) { SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd"); authDate = format.parse(authDateStr); } // 校验员工人数 Integer empNum = null; cell = authPartyRow.getCell(7); cell.setCellType(CellType.STRING); String empNumStr = cell.getStringCellValue(); if (StringUtils.isBlank(empNumStr)) { return ResponseJson.error("第" + i + 1 + "行员工人数不能为空"); } try { empNum = Integer.parseInt(empNumStr); } catch (Exception e) { return ResponseJson.error("第" + i + 1 + "行员工人数格式错误"); } // 校验店铺备注 cell = authPartyRow.getCell(8); cell.setCellType(CellType.STRING); String remarks = cell.getStringCellValue(); Integer customFlag = 0; if (StringUtils.isNotEmpty(remarks)) { customFlag = 1; } CmBrandAuthPo authPo = new CmBrandAuthPo(); authPo.setAuthParty(authParty); authPo.setProvinceId(provinceId); authPo.setCityId(cityId); authPo.setTownId(townId); authPo.setAddress(address); authPo.setLng(lng); authPo.setLat(lat); authPo.setMobile(mobile); authPo.setAuthCode(authCode); authPo.setAuthDate(authDate); authPo.setAuthImageType(1); authPo.setEmpNum(empNum); authPo.setCustomFlag(customFlag); authPo.setRemarks(remarks); authImportList.add(authPo); } } catch (Exception e) { e.printStackTrace(); return ResponseJson.error("导入失败,请检查表格数据"); } finally { // 删除临时数据 File tempFile = new File(filePath); boolean delete = tempFile.delete(); log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时表格:" + delete); } // 保存授权数据 for (int i = 0; i < authImportList.size(); i++) { CmBrandAuthPo authPo = authImportList.get(i); // 保存授权机构 authPo.setAuthUserId(authUserId); authPo.setCreateBy(createBy); authPo.setCreateSource(1); authPo.setFirstClubType(5); // 导入数据 ResponseJson result = saveAuth(authPo, null, true, 1); if (result.getCode() != 0) { // 设置手动回滚事务 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return ResponseJson.error("导入失败"); } } return ResponseJson.success("导入成功"); } /** * 获取机构关联的机构信息 * 1.7.4版本: */ @Override public ResponseJson> getRelationgInfo(String snCode, Integer authUserId) { //根据sn码获取关联这个产品的机构列表 List relationgList = authMapper.getRelationgList(snCode); String relationgInfo = null; List authIdList = null; if (relationgList.size() > 0) { for (int i = 0; i < relationgList.size(); i++) { if (null != relationgInfo) { relationgInfo += ","; } relationgInfo += relationgList.get(i).getRelationId(); } if (null != relationgInfo) { String[] relationIdList = relationgInfo.split(","); authIdList = authMapper.getAuthIdList(relationIdList); } } return ResponseJson.success(authIdList); } /** * 1.7.4版本 * 获取可绑定机构机构信息 **/ @Override public ResponseJson> getClubBindAuth(Integer authUserId) { List clubBindAuth = authMapper.getClubBindAuth(authUserId); return ResponseJson.success(clubBindAuth); } //------------------------------------------v1.7.5上传视频至抖音--------------------------------------------------------------------------------------- ///用户授权(用于获取数据) /** * 用户扫码授权,获取code值 * @param response * @return true :token没过期 false:token过期需重新授权 * @throws IOException */ @Override public ResponseJson getDouYingCode(HttpServletResponse response) throws IOException { //验证是否是第一次登录(根据redis缓存中的token验证) // long dYaccessTok = redisService.getExpireTime("DYaccessToken"); // boolean s=redisService.exists("DYaccessToken"); // String s1= redisService.get("DyopenId").toString(); //// if(!redisService.exists("DYaccessToken")){ // //验证token是否过期 // long dYaccessToken = redisService.getExpireTime("DYaccessToken"); // if(dYaccessToken<=0){ //tonken过期 // //判断refreshToken是否过期 // long DyrefreshToken = redisService.getExpireTime("DyrefreshToken"); // if(DyrefreshToken>=0){ //refreshToken // //根据refreshToken刷新token,重新缓存token // String refreshToken=redisService.get("DyrefreshToken").toString(); // String accessToken = refreshAccessToken(refreshToken); // redisService.set("DYaccessToken",accessToken , 60L * 60 * 24 * 15); // boolean flag= redisService.exists("DYaccessToken"); // return ResponseJson.success(true); // }else{ //根据refreshToken刷新refreshToken(总共可以刷新3次,次数完后需重新扫码授权) // String refreshToken=redisService.get("DyrefreshToken").toString(); // String newRefreshToken = resetRefreshAccessToken(refreshToken); // if(StringUtils.isNotEmpty(newRefreshToken)){ // String accessToken = refreshAccessToken(newRefreshToken); // redisService.set("DYaccessToken",accessToken,60L * 60 * 24 * 15); // return ResponseJson.success(true); // } // } // }else { // return ResponseJson.success(true); // } // } //验证token是否过期 // long dYaccessToken = redisService.getExpireTime("DYaccessToken"); return redisService.getExpireTime("DYaccessToken")<0 ? ResponseJson.success(false): ResponseJson.success(true); // String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识 // String responestype = "code";//写死为'code'即可 // String scope = "video.data,video.list,trial.whitelist,data.external.item";//应用授权作用域,多个授权作用域以英文逗号(,)分隔 // String redirectUrl = "https://www.caimei365.com";//回调地址,应用中配置 // String state = "false";//用于保持请求和回调的状态 // String code = "https://open.douyin.com/platform/oauth/connect/?client_key=" + clintKey // + "&response_type=" + responestype + "&scope=" + scope + "&redirect_uri=" + redirectUrl + "&state=" + state; // response.sendRedirect(code); } /** * 根据用户的code值获取AcessToken * ccode 用户授权登录code **/ @Override public ResponseJson getDouYingAcessToken(String code) throws IOException { String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识 String clintSecret = "1dd7446d29e16738787447b771ced2df";//应用唯一标识对应的密钥 String grantType = "authorization_code";//固定值 String requestUrl = "https://open.douyin.com/oauth/access_token/";//请求地址 CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); //创建httppost对象 HttpPost hp = new HttpPost(requestUrl); hp.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); // hp.setHeader("Content-Type","application/x-www-form-urlencoded"); //拼接请求参数 List list = new ArrayList(); list.add(new BasicNameValuePair("client_key", clintKey)); list.add(new BasicNameValuePair("client_secret", clintSecret)); list.add(new BasicNameValuePair("code", code)); list.add(new BasicNameValuePair("grant_type", grantType)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8); hp.setEntity(entity); //发送请求 CloseableHttpResponse execute = closeableHttpClient.execute(hp); HttpEntity he = execute.getEntity(); String result = EntityUtils.toString(he, StandardCharsets.UTF_8); //获取access_token,open_id(用于获取视频数据),refresh_token(刷新token) JSONObject jsonObject =JSONObject.parseObject(result); String data = jsonObject.getString("data"); JSONObject params =JSONObject.parseObject(data); String accessToken = params.getString("access_token"); String openId = params.getString("open_id"); String refreshToken = params.getString("refresh_token"); String errorCode = params.getString("error_code"); if(Integer.valueOf(errorCode)>0){return ResponseJson.success("tonken缓存失败",null);} //用redis缓存access_token,refresh_token redisService.set("DYaccessToken",accessToken , 60L * 60 * 24 * 15);// * 60 * 24 * 15 redisService.set("DyrefreshToken",refreshToken,60L * 60 * 24 * 30); redisService.set("DyopenId",openId,60L * 60 * 24 * 30); EntityUtils.consume(he); String DYaccessToken=redisService.get("DYaccessToken").toString(); String DyrefreshToken=redisService.get("DyrefreshToken").toString(); String DyopenId=redisService.get("DyopenId").toString(); if (StringUtils.isNotEmpty(DYaccessToken)&&StringUtils.isNotEmpty(DyrefreshToken)&&StringUtils.isNotEmpty(DyopenId)){ return ResponseJson.success(); }else { return ResponseJson.success("tonken缓存失败",null); } } /** * 刷新tonken * @param refreshToken */ public String refreshAccessToken(String refreshToken){ String requestUrl="https://open.douyin.com/oauth/refresh_token/"; String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识 String grantType = "refresh_token";//固定值 String accessToken=null; //创建httppost对象 CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpPost hp = new HttpPost(requestUrl); hp.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); // hp.setHeader("Content-Type","application/x-www-form-urlencoded"); //拼接请求参数 List list = new ArrayList(); list.add(new BasicNameValuePair("client_key", clintKey)); list.add(new BasicNameValuePair("grant_type", grantType)); list.add(new BasicNameValuePair("refresh_token", refreshToken)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8); hp.setEntity(entity); try { CloseableHttpResponse execute = closeableHttpClient.execute(hp); HttpEntity he = execute.getEntity(); String result = EntityUtils.toString(he, StandardCharsets.UTF_8); JSONObject params=JSONObject.parseObject(result); String data=params.getString("data"); JSONObject datalist=JSONObject.parseObject(data); accessToken=datalist.getString("access_token"); EntityUtils.consume(he); } catch (IOException e) { e.printStackTrace(); } hp.setEntity(entity); return accessToken; } /** * 刷新refreshAccessToken * @param refreshToken */ public String resetRefreshAccessToken(String refreshToken){ String requestUrl="https://open.douyin.com/oauth/renew_refresh_token/"; String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识 String renewRefreshAccessToken=null; //创建httppost对象 CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpPost hp = new HttpPost(requestUrl); List list = new ArrayList(); list.add(new BasicNameValuePair("client_key", clintKey)); list.add(new BasicNameValuePair("refresh_token", refreshToken)); list.add(new BasicNameValuePair("Content-Type", "multipart/form-data")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8); hp.setEntity(entity); try { CloseableHttpResponse execute = closeableHttpClient.execute(hp); HttpEntity he = execute.getEntity(); String result = EntityUtils.toString(he, StandardCharsets.UTF_8); JSONObject jsonObject=JSONObject.parseObject(result); String data = jsonObject.getString("data"); JSONObject params=JSONObject.parseObject(data); renewRefreshAccessToken = params.getString("refresh_token"); EntityUtils.consume(he); } catch (IOException e) { e.printStackTrace(); } hp.setEntity(entity); return renewRefreshAccessToken; } //----------------------------------------------------h5的方式上传视频------------------------------------------------ /** * h5的方式上传视频 * @return * @throws IOException */ @Override public ResponseJson getclientToken(String title,String videoPath,Integer authId) throws IOException { //获取accessToken String client_key = "awwwvh9tsnvo54w1"; String client_secret = "1dd7446d29e16738787447b771ced2df"; String grant_type = "client_credential"; String url = "https://open.douyin.com/oauth/client_token/?client_key=" + client_key + "&client_secret=" + client_secret + "&grant_type=" + grant_type; CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); //创建httppost对象 HttpPost hp = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(Consts.UTF_8); builder.setContentType(ContentType.MULTIPART_FORM_DATA); //构建参数 HttpEntity entity = builder.build(); hp.setEntity(entity); CloseableHttpResponse response = null; String schema=null; try { response = closeableHttpClient.execute(hp); HttpEntity he = response.getEntity(); String result = EntityUtils.toString(he, StandardCharsets.UTF_8); //把返回结果转json获取access_token JSONObject jsonObject=JSONObject.parseObject(result); String data=jsonObject.getString("data"); JSONObject params=JSONObject.parseObject(data); String accessToken=params.getString("access_token"); //根据accesstoken获取tiket schema = getDouYingTicket(accessToken, title,videoPath,authId); EntityUtils.consume(he); } catch (IOException e) { e.printStackTrace(); } return ResponseJson.success(schema); } /** * 根据token获取ticket **/ @RequestMapping("/getDouYingTicket") public String getDouYingTicket(String clientToken,String title,String videoPath,Integer authId) throws IOException { //时间戳 long l = System.currentTimeMillis(); String timestamp = String.valueOf(l); //随机数 String noncestr = randomGen(16); String uri = "https://open.douyin.com/open/getticket/"; CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("access-token", clientToken); httpGet.setHeader("Content-Type","application/json"); CloseableHttpResponse response = null; String schema=null; try { response = closeableHttpClient.execute(httpGet); HttpEntity he = response.getEntity(); String result = EntityUtils.toString(he, StandardCharsets.UTF_8); //获取ticket JSONObject jsonObject=JSONObject.parseObject(result); String data = jsonObject.getString("data"); JSONObject params=JSONObject.parseObject(data); String ticket = params.getString("ticket"); //getDouYingshareId String shareId = getDouYingshareId(clientToken); //保存shareId用于回调时存储item_id authMapper.savaShareIdByAuthId(authId,shareId); //获取签名 并且用md5加密 String signature = signatureAlgorithm(ticket, timestamp,noncestr); //获取schema(返回前端用于生成二维码发布视频) schema = appendSchema(signature, shareId, timestamp,noncestr, title, videoPath); EntityUtils.consume(he); } catch (IOException e) { e.printStackTrace(); } return schema; } /** * 获取签名 并且用md5加密 * ticket **/ @RequestMapping("/signatureAlgorithm") public String signatureAlgorithm(String ticket, String timestamp,String noncestr) { TreeMap treeMap = new TreeMap<>(); treeMap.put("nonce_str", noncestr); treeMap.put("ticket", ticket); treeMap.put("timestamp", timestamp); StringBuffer stringBuffer = new StringBuffer(); Iterator> it = treeMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = it.next(); stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } String result = stringBuffer.substring(0, stringBuffer.length() - 1); //进行md5签名 String signature = Md5Util.md5(result).toLowerCase(); return signature; } /** * Schema 生成 **/ public String appendSchema(String signature, String shareId, String timestamp,String noncestr,String title,String videoPath) { URIBuilder uri = null; String schema = null; try { uri = new URIBuilder("snssdk1128://openplatform/share"); uri.addParameter("share_type", "h5");//固定h5 uri.addParameter("client_key", "awwwvh9tsnvo54w1");//应用唯一标识 uri.addParameter("nonce_str", noncestr);//随机数(必须和签名时的nonce_str一致) uri.addParameter("timestamp", timestamp);//时间戳(必须和签名时的timestamp一致) uri.addParameter("signature", signature);//签名 uri.addParameter("state", shareId);//通过方法获取(基于webhook,获取视频发布回调信息,不传则收不到回调信息) //https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4 //视频地址(必须为网络地址,本地地址无法发布)单视频上传 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 uri.addParameter("share_to_publish", "1");//为1则直接发布视频至抖音 uri.addParameter("title",title);//"给大佐都整emo了");//视频标题 schema = uri.toString(); } catch (URISyntaxException e) { e.printStackTrace(); } return schema; } /** * 获取shareId 用于生成schema **/ @RequestMapping("/getDouYingshareId") public String getDouYingshareId(String clientToken) throws IOException { String uri = "https://open.douyin.com/share-id/?need_callback=true&default_hashtag=hashtag"; CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("access-token", clientToken); CloseableHttpResponse response = null; String shareId = ""; try { response = closeableHttpClient.execute(httpGet); HttpEntity he = response.getEntity(); String result = EntityUtils.toString(he, StandardCharsets.UTF_8); JSONObject jsonObject=JSONObject.parseObject(result); String data = jsonObject.getString("data"); JSONObject params=JSONObject.parseObject(data); shareId = params.getString("share_id"); EntityUtils.consume(he); } catch (IOException e) { e.printStackTrace(); } return shareId; } /** * 获取已发布视频列表 * @param openId 用户唯一标志 * @param cursor 分页游标, 第一页请求cursor是0, response中会返回下一页请求用到的cursor, 同时response还会返回has_more来表明是否有更多的数据。 * @param count 每页数量 10 */ public String getVideoList(String openId,Long cursor,Integer count,String accessToken){ String requestUrl="https://open.douyin.com/video/list/?open_id="+openId+"&cursor="+cursor+"&count="+count; //创建httppost对象 CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpGet hg = new HttpGet(requestUrl); hg.setHeader("Content-Type","application/json"); hg.addHeader("access-token",accessToken); String resultList=null; try { CloseableHttpResponse execute = closeableHttpClient.execute(hg); HttpEntity entity = execute.getEntity(); String result=EntityUtils.toString(entity,StandardCharsets.UTF_8); JSONObject jsonObject = JSONObject.parseObject(result); resultList = jsonObject.getString("data"); // resultList = JSONArray.parseArray(itemIdlist); // String itemId = params.getJSONObject(0).get("item_id").toString(); //根据itemid获取视频的数据(点赞,播放,评论量) EntityUtils.consume(entity); } catch (IOException e) { e.printStackTrace(); } return resultList; } /** * 生成随机数 * * @param place * @return */ public String randomGen(int place) { String base = "wqetryuioplkjhgfdsazxcvbmnABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; StringBuffer sb = new StringBuffer(); Random rd = new Random(); for (int i = 0; i < place; i++) { sb.append(base.charAt(rd.nextInt(base.length()))); } return sb.toString(); } /** * 保存视频信息 * @return */ @Override public ResponseJson saveVideoInfo(ChallengeRoundVo cr){ Date date=new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String releaseTime = sf.format(date).replace("T", ""); authMapper.saveVideoInfo(cr.getUserName(),cr.getCover(),cr.getOssUrl(),cr.getOssName(),cr.getTitle(),releaseTime,cr.getAuthId(),cr.getAuthUserId()); return ResponseJson.success("保存成功",null); } /** * 根据authid获取authUserId * @param authId * @return */ @Override public boolean getauthUserId(Integer authId){ String authUserId= authMapper.getauthUserId(authId); return StringUtils.isEmpty(authUserId); } /** * 判断是否存在userName * @param userName * @return */ @Override public boolean getuserName(String userName){ String name= authMapper.getuserName(userName); return StringUtils.isEmpty(name); } /** * 验证是否在活动时间内 * @param releaseTime 发布时间 * @return */ @Override public boolean checkActivityTime(String releaseTime){ Integer id= authMapper.checkActivityTime(releaseTime); return id==null?true:false; } /** * 获取已发布视频列表(前端) * @param clubUserName 手机号或者机构名 * @param status 用户发布状态 * @param cursor 页码 * @param count 条数 * @return */ @Override public ResponseJson> getPublishedVideoList(String clubUserName,Integer status,Integer cursor,Integer count,Integer pageNum,Integer pageSize){ PageHelper.startPage(pageNum, pageSize); List listChallengeRoundVo=authMapper.getPublishedVideoList(clubUserName,status); PageInfo pageData = new PageInfo<>(listChallengeRoundVo); //调用抖音api获取视频数据 String dyopenId=null; String DYaccessToken=null; if(redisService.getExpireTime("DyopenId")>0&&redisService.getExpireTime("DYaccessToken")>0){ dyopenId=redisService.get("DyopenId").toString(); DYaccessToken=redisService.get("DYaccessToken").toString(); } Long flag=1l; List list=new ArrayList<>(); while (flag!=0){ if (flag==1){flag=0l;} String data = getVideoList(dyopenId, flag, count, DYaccessToken); JSONObject paramslist = JSONObject.parseObject(data); Integer error_code = Integer.valueOf(paramslist.getString("error_code")); if(error_code>0){ break; } String resultList = paramslist.getString("list"); String cor = paramslist.getString("cursor"); flag=Long.parseLong(cor); List listDyVideoInfoVo= JSONArray.parseArray(resultList, DyVideoInfoVo.class); if(listDyVideoInfoVo!=null&&listDyVideoInfoVo.size()>0){ for (DyVideoInfoVo dv:listDyVideoInfoVo) { list.add(dv); } } } if(listChallengeRoundVo!=null&&listChallengeRoundVo.size()>0){ for (ChallengeRoundVo ChallengeRoundVo:listChallengeRoundVo) { if(StringUtils.isEmpty(ChallengeRoundVo.getDiggCount())){ ChallengeRoundVo.setDiggCount("0"); } if(StringUtils.isEmpty(ChallengeRoundVo.getPlayCount())){ ChallengeRoundVo.setPlayCount("0"); } if(list!=null&&list.size()>0){ for (DyVideoInfoVo dyVideoInfoVo:list) { if(dyVideoInfoVo.getItem_id().equals(ChallengeRoundVo.getItemId())){ StatisticsVo StatisticsVo= JSONObject.parseObject(dyVideoInfoVo.getStatistics(), StatisticsVo.class); ChallengeRoundVo.setDiggCount(StatisticsVo.getDigg_count()); ChallengeRoundVo.setPlayCount(StatisticsVo.getPlay_count()); break; } } } } } //根据点赞量降序排序 // PageHelper.startPage(pageNum, pageSize); List collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序 PageInfo pageDa = new PageInfo<>(collect); return ResponseJson.success(pageDa); } /** * 获取已发布视频列表(后端) * @param mobile * @param authParty * @param status * @param cursor * @param count * @param authUserId * @return */ @Override public ResponseJson> getPublishedVideo(String mobile,String authParty,Integer status,Integer cursor,Integer count,Integer authUserId,Integer pageNum,Integer pageSize){ PageHelper.startPage(pageNum, pageSize); List listChallengeRoundVo=authMapper.getPublishedVideo(mobile,authParty,status,authUserId); PageInfo pageData = new PageInfo<>(listChallengeRoundVo); //调用抖音api获取视频数据 String dyopenId=null; String DYaccessToken=null; if(redisService.getExpireTime("DyopenId")>0&&redisService.getExpireTime("DYaccessToken")>0){ dyopenId=redisService.get("DyopenId").toString(); DYaccessToken=redisService.get("DYaccessToken").toString(); } Long flag=1l; List list=new ArrayList<>(); while (flag!=0){ if (flag==1){flag=0l;} String data = getVideoList(dyopenId, flag, count, DYaccessToken); JSONObject paramslist = JSONObject.parseObject(data); Integer error_code = Integer.valueOf(paramslist.getString("error_code")); if(error_code>0){ break; } String resultList = paramslist.getString("list"); String cor = paramslist.getString("cursor"); flag=Long.parseLong(cor); List listDyVideoInfoVo= JSONArray.parseArray(resultList, DyVideoInfoVo.class); if(listDyVideoInfoVo!=null&&listDyVideoInfoVo.size()>0){ for (DyVideoInfoVo dv:listDyVideoInfoVo) { list.add(dv); } } } if(listChallengeRoundVo!=null&&listChallengeRoundVo.size()>0){ for (ChallengeRoundVo ChallengeRoundVo:listChallengeRoundVo) { if(StringUtils.isEmpty(ChallengeRoundVo.getDiggCount())){ ChallengeRoundVo.setDiggCount("0"); } if(StringUtils.isEmpty(ChallengeRoundVo.getPlayCount())){ ChallengeRoundVo.setPlayCount("0"); } if(list!=null&&list.size()>0){ for (DyVideoInfoVo dyVideoInfoVo:list) { if(dyVideoInfoVo.getItem_id().equals(ChallengeRoundVo.getItemId())){ StatisticsVo StatisticsVo= JSONObject.parseObject(dyVideoInfoVo.getStatistics(), StatisticsVo.class); ChallengeRoundVo.setDiggCount(StatisticsVo.getDigg_count()); ChallengeRoundVo.setPlayCount(StatisticsVo.getPlay_count()); break; } } } } } //根据点赞量降序排序 // PageHelper.startPage(pageNum, pageSize); List collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序 PageInfo pageDa = new PageInfo<>(collect); return ResponseJson.success(pageDa); } /** * 获取机构已发布视频的机构下拉列表 * @param authUserId * @return */ @Override public ResponseJson> getAuthPartylist(Integer authUserId){ return ResponseJson.success(authMapper.getAuthPartylist(authUserId)); } /** * 保存活动信息 * @param startTime * @param endTime * @param status * @return */ @Override public ResponseJson saveActivityTime(String startTime,String endTime,Integer status,Integer authUserId){ //如果数据库有值则修改,没值则新增 List challengeList = authMapper.checkActivityId(); List authUserIdList=new ArrayList<>(); for (ChallengeActivityVo ac:challengeList) { authUserIdList.add(ac.getAuthUserId()); } if(challengeList.size()<0||!authUserIdList.contains(authUserId)){ authMapper.saveActivityInfo(startTime,endTime,status,authUserId); }else { authMapper.upActivityInfo(startTime,endTime,status,authUserId); } return ResponseJson.success(); } /** * 获取活动信息 * @return */ @Override public ResponseJson getActivityTime(Integer authUserId){ return ResponseJson.success(authMapper.getActivityTime(authUserId)); } /** * 判断shareId是否存在 * @param shareId * @return */ @Override public boolean getShareId(String shareId){ return StringUtils.isNotEmpty(authMapper.getShareId(shareId)); } /** * 根据ShareId保存itemId (webhook触发时调用) * @param shareId * @param itemId */ @Override public void savaItemIdByShareId(String shareId,String itemId){ authMapper.savaItemIdByShareId(shareId,itemId); } @Override public ResponseJson getActivitty(Integer authUserId){ ChallengeActivityVo activityTime = authMapper.getActivityTime(authUserId); Date date=new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String releaseTime = sf.format(date).replace("T", ""); if(activityTime!=null){ if(activityTime.getStartTime().compareTo(releaseTime)>0){ activityTime.setActivityState(0); }else if(activityTime.getStartTime().compareTo(releaseTime)<0&&activityTime.getEndTime().compareTo(releaseTime)>0){ activityTime.setActivityState(1); }else { activityTime.setActivityState(2); } } return ResponseJson.success(activityTime); } /** * 根据authId获取手机号 * @param authId * @return */ @Override public String getMobileByAuthId(Integer authId){ return authMapper.getMobileByAuthId(authId); } /** * 根据authId获取手机号 * @param authId * @return */ @Override public String getAuthUserName(Integer authId){ return authMapper.getAuthUserName(authId); } /** * 保存抖音口令 * @param authId * @return */ @Override public void savaDyCommand(Integer authId,String content){ authMapper.savaDyCommand(authId,content); } /** * 根据authId获取ossName * @param videoID * @return */ @Override public String getOssNameAuthId(Integer videoID){ return authMapper.getOssNameId(videoID); } /** * 根据authId删除视频 * @param videoID * @return */ @Override public void deleteVideoByAuthId(Integer videoID){ authMapper.deleteVideoById(videoID); } @Override public ResponseJson downLoadChoseZip(String fileId,HttpServletResponse response){ if (fileId.contains(",")) { String[] split = fileId.split(","); ArrayList fileTreeVos = new ArrayList<>(); for (String s : split) { ChallengeRoundVo file = authMapper.getChallengeRoundInfo(Integer.valueOf(s)); fileTreeVos.add(file); } //有package则在服务器固定路径new file.mkdir UUID uuid = UUID.randomUUID(); String zipPath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/" + uuid; String filePath = zipPath; if ("dev".equals(active)) { zipPath = "D:\\caimei-workSpace\\file\\" + uuid; filePath = zipPath; } boolean mkdirs = new File(filePath).mkdirs(); Assert.isTrue(mkdirs, "文件夹创建失败"); for (ChallengeRoundVo challengeRoundVo : fileTreeVos) { //普通文件直接下载到临时文件夹uuid下 String fileName = ""; String ossurl = challengeRoundVo.getOssUrl(); ossurl.indexOf("."); String title=challengeRoundVo.getTitle(); Pattern pattern = Pattern.compile("[\\s\\\\/:\\*\\?\\\"<>\\|]"); Matcher matcher = pattern.matcher(title); title= matcher.replaceAll(""); if(title.length()>50){ title= title.substring(0,50); } if ("dev".equals(active)) { fileName = zipPath + "\\"+title + ossurl.substring(ossurl.lastIndexOf(".")); } else { fileName = zipPath + "/"+title + ossurl.substring(ossurl.lastIndexOf(".")); } OSSUtils.downFileByFilePath("authFile/", challengeRoundVo.getOssName(), fileName); // else { // //文件夹在uuid文件夹下创建自己包名的文件夹 // String param = fileTreeVo.getId() + "," + authUserId; // String myPath = ""; // myPath = filePath + "/" + fileTreeVo.getFileName(); // if ("dev".equals(active)) { // myPath = filePath + "\\" + fileTreeVo.getFileName(); // } // boolean dirs = new File(myPath).mkdirs(); // Assert.isTrue(dirs, "文件夹创建失败"); // recursion(param, myPath); // } } //压缩 FileZipUtils.compress(zipPath, "", true); String s = zipPath + ".zip"; String fileName = uuid + ".zip"; File file = new File(s); try { if (file.exists()) { FileInputStream fileInputStream = new FileInputStream(file); ServletOutputStream outputStream = response.getOutputStream(); // 设置下载文件的mineType,告诉浏览器下载文件类型 // int i = fileName.lastIndexOf("."); // String substring = fileName.substring(i + 1, filePath.length()); response.setContentType("application/zip"); // 设置一个响应头,无论是否被浏览器解析,都下载 response.setHeader("Content-disposition", "attachment; filename=" + fileName); byte[] bytes = new byte[1024]; int len; while ((len = fileInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } fileInputStream.close(); outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } file.delete(); FileZipUtils.deleteFile(new File(zipPath)); }else { ArrayList fileTreeVos = new ArrayList<>(); ChallengeRoundVo f = authMapper.getChallengeRoundInfo(Integer.valueOf(fileId)); fileTreeVos.add(f); //有package则在服务器固定路径new file.mkdir UUID uuid = UUID.randomUUID(); String zipPath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/" + uuid; String filePath = zipPath; if ("dev".equals(active)) { zipPath = "D:\\caimei-workSpace\\file\\" + uuid; filePath = zipPath; } boolean mkdirs = new File(filePath).mkdirs(); Assert.isTrue(mkdirs, "文件夹创建失败"); for (ChallengeRoundVo challengeRoundVo : fileTreeVos) { //普通文件直接下载到临时文件夹uuid下 String fileName = ""; String ossurl = challengeRoundVo.getOssUrl(); String title=challengeRoundVo.getTitle(); Pattern pattern = Pattern.compile("[\\s\\\\/:\\*\\?\\\"<>\\|]"); Matcher matcher = pattern.matcher(title); title= matcher.replaceAll(""); if(title.length()>50){ title= title.substring(0,50); } if ("dev".equals(active)) { fileName = zipPath + "\\"+title +ossurl.substring(ossurl.lastIndexOf(".")); } else { fileName = zipPath + "/"+title + ossurl.substring(ossurl.lastIndexOf(".")); } OSSUtils.downFileByFilePath("authFile/", challengeRoundVo.getOssName(), fileName); // else { // //文件夹在uuid文件夹下创建自己包名的文件夹 // String param = fileTreeVo.getId() + "," + authUserId; // String myPath = ""; // myPath = filePath + "/" + fileTreeVo.getFileName(); // if ("dev".equals(active)) { // myPath = filePath + "\\" + fileTreeVo.getFileName(); // } // boolean dirs = new File(myPath).mkdirs(); // Assert.isTrue(dirs, "文件夹创建失败"); // recursion(param, myPath); // } } //压缩 FileZipUtils.compress(zipPath, "", true); String s = zipPath + ".zip"; String fileName = uuid + ".zip"; File file = new File(s); try { if (file.exists()) { FileInputStream fileInputStream = new FileInputStream(file); ServletOutputStream outputStream = response.getOutputStream(); // 设置下载文件的mineType,告诉浏览器下载文件类型 // int i = fileName.lastIndexOf("."); // String substring = fileName.substring(i + 1, filePath.length()); response.setContentType("application/zip"); // 设置一个响应头,无论是否被浏览器解析,都下载 response.setHeader("Content-disposition", "attachment; filename=" + fileName); byte[] bytes = new byte[1024]; int len; while ((len = fileInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } fileInputStream.close(); outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } file.delete(); FileZipUtils.deleteFile(new File(zipPath)); } return null; } }