1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633 |
- 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<PageInfo<AuthVo>> 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<AuthVo> authList = authMapper.getAuthList(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus,authCode);
- PageInfo<AuthVo> pageData = new PageInfo<>(authList);
- return ResponseJson.success(pageData);
- }
- @Override
- public ResponseJson<PageInfo<AuthVo>> 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<AuthVo> authList = authMapper.getAuthListAll(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus, name, snCode);
- PageInfo<AuthVo> 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<Integer> productIdList = authProductService.getProductIdsByAuthId(authId);
- productIdList.forEach(productId -> {
- if (null != productId) {
- authProductService.deleteProduct(productId);
- }
- });
- return ResponseJson.success("删除品牌授权成功");
- }
- @Override
- public ResponseJson<AuthFormVo> 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<AuthFormVo> authIdList = authMapper.getAuthIdList(relationIdList);
- authFormVo.setReleationClubList(authIdList);
- }
- if (null != authFormVo.getLng()) {
- authFormVo.setLngAndLat(authFormVo.getLng() + "," + authFormVo.getLat());
- }
- List<String> bannerList = authMapper.getBannerList(authId);
- authFormVo.setBannerList(bannerList);
- return ResponseJson.success(authFormVo);
- }
- @Override
- public ResponseJson<List<AuthVo>> getAuthSelectList(Integer authUserId) {
- List<AuthVo> 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<LdmDataPo> ldmClubData = ldmMapper.getLdmClubData(null, 0);
- ldmClubData.forEach(ldmClub -> {
- String pic2 = ldmClub.getPic2();
- String pic3 = ldmClub.getPic3();
- String pic4 = ldmClub.getPic4();
- List<AuthVo> 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<String> 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<String, Object> 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<String, Object> getTemplateInfo(TemplateVo template, CmBrandAuthPo auth) {
- HashMap<String, Object> 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<String> shopBrands = shopService.getShopBrands(authUserId);
- // 授权列表
- List<CmBrandAuthPo> 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<TownPo> 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<List<AuthFormVo>> getRelationgInfo(String snCode, Integer authUserId) {
- //根据sn码获取关联这个产品的机构列表
- List<ProductFormVo> relationgList = authMapper.getRelationgList(snCode);
- String relationgInfo = null;
- List<AuthFormVo> 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<List<AuthFormVo>> getClubBindAuth(Integer authUserId) {
- List<AuthFormVo> 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<NameValuePair> 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<NameValuePair> 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<NameValuePair> 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<String, String> treeMap = new TreeMap<>();
- treeMap.put("nonce_str", noncestr);
- treeMap.put("ticket", ticket);
- treeMap.put("timestamp", timestamp);
- StringBuffer stringBuffer = new StringBuffer();
- Iterator<Map.Entry<String, String>> it = treeMap.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry<String, String> 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<PageInfo<ChallengeRoundVo>> getPublishedVideoList(String clubUserName,Integer status,Integer cursor,Integer count,Integer pageNum,Integer pageSize){
- PageHelper.startPage(pageNum, pageSize);
- List<ChallengeRoundVo> listChallengeRoundVo=authMapper.getPublishedVideoList(clubUserName,status);
- PageInfo<ChallengeRoundVo> 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<DyVideoInfoVo> 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<DyVideoInfoVo> 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<ChallengeRoundVo> collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序
- PageInfo<ChallengeRoundVo> pageDa = new PageInfo<>(collect);
- return ResponseJson.success(pageDa);
- }
- /**
- * 获取已发布视频列表(后端)
- * @param mobile
- * @param authParty
- * @param status
- * @param cursor
- * @param count
- * @param authUserId
- * @return
- */
- @Override
- public ResponseJson<PageInfo<ChallengeRoundVo>> getPublishedVideo(String mobile,String authParty,Integer status,Integer cursor,Integer count,Integer authUserId,Integer pageNum,Integer pageSize){
- PageHelper.startPage(pageNum, pageSize);
- List<ChallengeRoundVo> listChallengeRoundVo=authMapper.getPublishedVideo(mobile,authParty,status,authUserId);
- PageInfo<ChallengeRoundVo> 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<DyVideoInfoVo> 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<DyVideoInfoVo> 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<ChallengeRoundVo> collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序
- PageInfo<ChallengeRoundVo> pageDa = new PageInfo<>(collect);
- return ResponseJson.success(pageDa);
- }
- /**
- * 获取机构已发布视频的机构下拉列表
- * @param authUserId
- * @return
- */
- @Override
- public ResponseJson<List<ChallengeRoundVo>> 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<ChallengeActivityVo> challengeList = authMapper.checkActivityId();
- List<Integer> 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<ChallengeActivityVo> 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<ChallengeActivityVo> 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<ChallengeRoundVo> 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<ChallengeRoundVo> 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;
- }
- }
|