DingTalkServiceImpl.java 5.13 KB
Newer Older
shenggui.li committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
package com.reyun.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.reyun.model.Account;
import com.reyun.model.AccountRestrict4Web;
import com.reyun.model.BussinessMan;
import com.reyun.model.DingSales;
import com.reyun.repository.AccountRepository;
import com.reyun.repository.AccountRestrict4WebRepository;
import com.reyun.repository.BussinessManRepository;
import com.reyun.repository.DingSalesRepository;
import com.reyun.service.AccountFlowRestrictService;
import com.reyun.service.DingTalkService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DingTalkServiceImpl implements DingTalkService {

	Logger logger = LoggerFactory.getLogger(DingTalkServiceImpl.class);

	@Autowired
	private DingSalesRepository dingSalesRepository;
	@Autowired
	private AccountRepository accountRepository;
	@Autowired
	private BussinessManRepository bussinessManRepository;
	@Autowired
	private AccountRestrict4WebRepository accountRestrict4WebRepository;
	@Autowired
	private AccountFlowRestrictService accountFlowRestrictService;

	@Override
	public String getAccountAndFlowInfo(String body, Map head) {
		JSONObject data = JSON.parseObject(body);
		String nickName = data.getString("senderNick");
		String content = data.getJSONObject("text").getString("content");

		if (StringUtils.isEmpty(content)) {
			//不回复消息
			return "{ \"msgtype\": \"empty\" }";
		}
		String formater = "{ \"msgtype\": \"text\", \"text\": { \"content\": \"%s\" },\"at\": { \"isAtAll\": false } }";

		DingSales sales = dingSalesRepository.findByNameOrNickName(nickName);

		if (sales == null || !checkSign(sales, head)) {
			return String.format(formater, "未开通此功能");
		}

		Account account = accountRepository.findRootAccountByEmail(content.trim());
		if (account == null) {
			return String.format(formater, "账号不存在");
		}
		if ("trackingio@reyun.com".equals(account.getEmail())) {
			//均可查询测试账号  测试机器人
			sales.setBussinessId(-1L);
		}

		boolean getid = true;
		Long curId = account.getBussinessman();
		List<Long> allIds = new ArrayList<>();
		allIds.add(curId);

		if (!sales.getBussinessId().equals(-1L)) {
			while (getid) {
				BussinessMan man = bussinessManRepository.findOne(curId);
				if (man == null) {
					break;
				}
				if (man.getId().equals(Long.parseLong(man.getLeader()))) {
					getid = false;
				} else {
					curId = Long.parseLong(man.getLeader());
					allIds.add(curId);
				}
			}
		}

		if (!sales.getBussinessId().equals(-1L) && !allIds.contains(sales.getBussinessId())) {
			return String.format(formater, "没有权限查看");
		}

		//
		return getFlowText(account, formater, null);

	}


	public String getFlowText(Account account, String formater, String email) {

		if (formater == null) {
			formater = "{ \"msgtype\": \"text\", \"text\": { \"content\": \"%s\" },\"at\": { \"isAtAll\": false } }";
		}

		if (account == null && email != null) {
			account = accountRepository.findRootAccountByEmail(email);
		}

		AccountRestrict4Web byAccountId = accountRestrict4WebRepository.findByAccountId(account.getId());
		if (byAccountId == null) {

			byAccountId = accountFlowRestrictService.RestrictFlowByAccountTask(account, "zh");
		}

		AccountRestrict4Web restrict4Web = accountFlowRestrictService.getAccountUsedFlows(byAccountId, account);

		StringBuffer contentMain = new StringBuffer();

		contentMain.append("主账号:").append(account.getEmail())
				.append("\n公司名:").append(account.getCompany())
				.append("\n已使用流量:").append(restrict4Web.getTrackTotalFlow().longValue())
				.append("\n流量上限:").append(restrict4Web.getTrackLimit().longValue())
				.append("\n开通时间:").append(new DateTime(account.getPubDate()).toString("yyyy-MM-dd"))
				.append("\n过期时间:").append(new DateTime(account.getPastDate()).toString("yyyy-MM-dd"));

		return String.format(formater, contentMain.toString());

	}

	public boolean checkSign(DingSales sales, Map<String, String> head) {
		String timestamp = head.get("timestamp");
		return getSign(timestamp, sales.getAppSecret()).equals(head.get("sign"));
	}


	private String getSign(String timestamp, String appSecret) {
		try {
			String stringToSign = timestamp + "\n" + appSecret;
			Mac mac = Mac.getInstance("HmacSHA256");
			mac.init(new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256"));
			byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
			return new String(Base64.encodeBase64(signData));
		} catch (Exception e) {
			logger.error("ding talk get sign erro", e);
		}
		return timestamp;
	}

	public static void main(String[] args) {
		String formatData = "{ \"msgtype\": \"text\", \"text\": { \"content\": \"%s\" },\"at\": { \"isAtAll\": false } }";
		System.out.println(String.format(formatData, "aaaaaaaaa"));
	}
}