package com.chinacreator.process.job; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.chinacreator.process.dao.DictionaryDao; import com.chinacreator.process.dao.NewYearVideoDao; import com.chinacreator.process.exception.BusinessException; import com.chinacreator.process.util.Bash; import com.chinacreator.process.util.JsonUtil; import com.chinacreator.process.util.TripleDES; import com.chinacreator.process.util.URLUtil; import com.chinacreator.process.util.fakeid.MD5; import com.frameworkset.util.StringUtil; import oracle.sql.CLOB; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import sun.misc.BASE64Decoder; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.*; /** * @author zhengrong.yan * @date 2021/2/1 9:45 */ public class NewYearMakeVideoJob { private Logger log = Logger.getLogger("newyearmakevideo"); @Autowired private DictionaryDao dictionaryDao; @Autowired private NewYearVideoDao newYearVideoDao; public void doProcess() throws Exception { log.info(Thread.currentThread().getName() + "定时任务开始"); long beginTime = System.currentTimeMillis(); List list = newYearVideoDao.getData(); if (list != null && list.size() > 0) { CountDownLatch threadSignal = new CountDownLatch(list.size()); ExecutorService executorService = new ThreadPoolExecutor(12, 16, 10L, TimeUnit.MINUTES, new LinkedBlockingQueue(), new ThreadPoolExecutor.CallerRunsPolicy()); //去除重复数据 //List dataList = paraseData(list); log.info("数据库有效需要处理的数:" + list.size()); for (HashMap vipmap : list) { NewYearVideoMakeService continueService = new NewYearVideoMakeService(list.size(), threadSignal, vipmap, dictionaryDao, newYearVideoDao); executorService.execute(continueService); } executorService.shutdown(); try { executorService.awaitTermination(5L, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } } log.info(Thread.currentThread().getName() + "定时任务完成,耗时:" + (System.currentTimeMillis() - beginTime) / 1000 + " 秒"); } /** * 去除重复数据,防止赠送会员接口被并发限制 * * @param dataList * @return */ private List paraseData(List dataList) { //去重复后的数据集 List reDataList = new ArrayList(); HashMap tmpMap = new HashMap(); for (HashMap dataMap : dataList) { if (tmpMap.containsKey(dataMap.get("USERID").toString())) { log.info("重复数据," + dataMap.get("USERID")); } else { reDataList.add(dataMap); List tmpList = new ArrayList(); tmpList.add(dataMap.get("ID")); tmpMap.put(dataMap.get("USERID").toString(), tmpList); } } return reDataList; } static class NewYearVideoMakeService implements Runnable { private static Logger log = Logger.getLogger("newyearmakevideo"); private int totalSize; private CountDownLatch threadSignal; private HashMap busimap; private DictionaryDao dictionaryDao; private NewYearVideoDao newYearVideoDao; public NewYearVideoMakeService(int totalSize, CountDownLatch threadSignal, HashMap busimap, DictionaryDao dictionaryDao, NewYearVideoDao newYearVideoDao) { this.totalSize = totalSize; this.threadSignal = threadSignal; this.busimap = busimap; this.dictionaryDao = dictionaryDao; this.newYearVideoDao = newYearVideoDao; } /** * 业务处理 * * @param */ public void run() { long startime = System.currentTimeMillis(); Map logMap = new HashMap(); //logMap.put("data", busimap); String resultCode = "-1"; String resultInfo = ""; String result = ""; String id = String.valueOf(busimap.get("ID")); try { String video_url = String.valueOf(busimap.get("RETURNVIDEOURL")); if (StringUtil.isEmpty(video_url)) { resultCode = "5000"; resultInfo = "未回传视频地址"; } else { //下载视频到服务器 getPutFile(video_url, id); newYearVideoDao.updateHasDowload(String.valueOf(busimap.get("ID"))); //调cdn脚本 String command = "/kc/newyearvideo/publish.sh ../data/cdn/" + id + ".mp4"; String res = Bash.exec(command); System.out.println("调用脚本结果===>" + res); log.info("调用脚本结果===>" + res); if (!"".equals(res)) { //调拓维接口 result = invoke(busimap); JSONObject jsonObject = JSON.parseObject(result); resultCode = jsonObject.getString("code"); resultInfo = jsonObject.getString("msg"); resultCode = "0"; } else { throw new BusinessException("8001", "cdn缓存失败"); } } } catch (Exception e) { try { newYearVideoDao.updateRowback(String.valueOf(busimap.get("ID"))); } catch (Exception e1) { e1.printStackTrace(); } e.printStackTrace(); if (e instanceof BusinessException) { resultInfo = ((BusinessException) e).getMessage(); resultCode = ((BusinessException) e).getCode(); } else { resultCode = "8000"; resultInfo = "系统错误," + e.getMessage(); } } finally { threadSignal.countDown(); try { if (resultInfo != null && resultInfo.length() > 250) { resultInfo = resultInfo.substring(0, 250); } if ("0".equals(resultCode)) { String videourl = "http://res.tv.wo.cn/springfestival/" + id + ".mp4"; newYearVideoDao.updateHasFinish(id, resultCode, resultInfo, videourl); } } catch (Exception e) { e.printStackTrace(); log.error("更新数据出现异常," + id + ", resultCode:" + resultCode + ", resultInfo:" + resultInfo); } logMap.put("reusltCode", resultCode); logMap.put("resultInfo", resultInfo); logMap.put("result", result); log.info(JsonUtil.objectToJson(logMap)); } } /** * 调合作方接口 * * @param * @return * @throws Exception */ private String invoke(Map params) throws Exception { String result = ""; try { String url = dictionaryDao.getValue("twWXNotify");//调拓维通知接口 String openid = String.valueOf(params.get("USERID")); System.out.println("openid===>"+openid); String templateId = "fa5QGaGoY9YDB_vPz4q890JO68tLAv97_BjTkY3hTY4"; String tourl = "https://live.v.wo.cn/platform/ytpxz/univideo/personal.html?id="+openid; url +="?openId="+openid+"&templateId="+templateId+"&url="+tourl; //新年视频换脸 //url = "https://fifa.wo186.tv/wx/sendTemplateMessage.do?openId=ojCvV0t_sRfF1a5AolUTextKHfvM&templateId=fa5QGaGoY9YDB_vPz4q890JO68tLAv97_BjTkY3hTY4&url="; //新年视频换脸 String modulesname = String.valueOf(params.get("MODULESNAME")); String modulestime = String.valueOf(params.get("MODULESTIME")); String jsonParams = ""; JSONObject jsondata = new JSONObject(); String[] s = {"remark", "first", "keyword1", "keyword2", "keyword3", "keyword4"}; String[] s2 = {"点击此通知直接进入制作好的视频页面,并可进行分享哦", "您的超清版视频已经制作完成!", "AI变脸送新春祝福", modulesname, modulestime, "超清无水印"}; for (int i = 0; i < 6; i++) { JSONObject jsonObject = new JSONObject(); jsonObject.put("color", "#000000"); jsonObject.put("value", s2[i]); jsondata.put(s[i], jsonObject); } jsonParams = jsondata.toJSONString(); log.info(url); log.info(jsondata.toJSONString()); try { //加密 String keyStr = "d663bd873d93a76ab2ce11e9"; String txt = TripleDES.encrypt(jsonParams, keyStr); ; System.out.println(txt); //MD5 String sid = "h5game"; String timestamp = System.currentTimeMillis() / 1000 + ""; String sign = sid + "&" + timestamp + "&" + txt + "&" + keyStr; sign = MD5.MD5Encode(sign); URL url2 = new URL(url); SSLContext sc = SSLContext.getInstance("TLSv1.2"); //$NON-NLS-1$ sc.init(null, null, new java.security.SecureRandom()); HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection(); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setRequestMethod("POST"); conn.addRequestProperty("content-type", "application/json;charset=UTF-8"); conn.addRequestProperty("sid", sid); conn.addRequestProperty("timestamp", timestamp); conn.addRequestProperty("sign", sign); conn.setDoOutput(true); conn.setUseCaches(false); OutputStreamWriter out = null; out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); out.write(txt); out.flush(); result = URLUtil.readInputStream(conn.getInputStream()); } catch (Exception e) { e.printStackTrace(); } log.info("url: " + url); log.info("调合作方接口结果=> wxuserid: " + String.valueOf(busimap.get("USERID")) + ", id: " + String.valueOf(busimap.get("ID")) + " , result: " + result); } catch (Exception e) { e.printStackTrace(); log.error("id=>" + String.valueOf(params.get("ID")) + "调拓维接口失败," + e); } return result; } /** * 解析数据 * * @param body orderId TD_POINTS_ORDER_REC表ID字段,我方生成的订单流水号 * orderNo 积分商城订单号 * requestId 返回给客户的请求ID * @return */ public Map transBean(Map body) { String jsonStr = JsonUtil.objectToJson(body); return (Map) JsonUtil.jsonToBean(jsonStr, Map.class); } /** * 获取请求属性性 * * @return */ private static Map getProperty() { Map reqProperty = new HashMap(); reqProperty.put("Content-type", "application/json;charset=UTF-8"); return reqProperty; } public static void getPutFile(String urlPath, String id) throws Exception { File file = new File("/kc/data/cdn/" + id + ".mp4"); file.getParentFile().mkdirs(); BufferedInputStream bufferedInputStream = new BufferedInputStream(new URL(urlPath).openStream()); FileOutputStream fileOutputStream = new FileOutputStream("/kc/data/cdn/" + id + ".mp4"); int count = 0; byte[] b = new byte[1000]; while ((count = bufferedInputStream.read(b)) != -1) { fileOutputStream.write(b, 0, count); } } } }