package com.cool.store.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.stream.Collectors;

/**
 * 对腾讯云音视频回调单独验签
 */
@Component
@Order(4)
@Slf4j
public class TRTCCallbackFilter implements Filter {

    @Value("${trtc.video.callback.secretKey:null}")
    private String secretkey;

    @Override
    public void init(FilterConfig filterConfig) {
        //do nothing
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        //不是腾讯云音视频回调请求
        if (!uri.startsWith("/partner/pc/video")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (!"POST".equals(request.getMethod())) {
            return;
        }
        String requestBody = request.getReader().lines().collect(Collectors.joining());
        //回调的签名
        String sign = request.getHeader("Sign");
        //服务器端生成的签名
        String newSign = "";
        try {
            newSign = getResultSign(secretkey, requestBody);
        } catch (Exception e) {
            log.error("腾讯云音视频回调签名生成错误，e：\t{}", e.getMessage());
            return;
        }
        if (StringUtils.isEmpty(sign) || !newSign.equals(sign)) {
            log.error("腾讯云音视频回调签名错误, sign：\t{}, newSign：\t{}", sign, newSign);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        //do nothing
    }

    private String getResultSign(String key, String body) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        hmacSha256.init(secretKey);
        return Base64.getEncoder().encodeToString(hmacSha256.doFinal(body.getBytes()));
    }

}
