package com.cxyxiaomo.epp.TencentCloud;

import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Response;

import java.util.TreeMap;

public class QCloudCosStsClient {

    private QCloudCosStsClient() {
    }

    public static TmpCredential getCredential(String cosObjectKey) {
        // 用户的 SecretId
        String secretId = "AKIDSkmeXTHsTqzwe8ZDiGcomW4OYXcZIerp";
        // 用户的 SecretKey
        String secretKey = "22sVt494mGZeV7sQkqwxnNjneHesqXxA";
        // bucket
        String bucket = "epp-1302260381";
        // bucket 所在地区
        String region = "ap-shanghai";
        // 临时密钥有效时长，单位是秒
        Integer durationSeconds = 1800;

        try {
            TreeMap<String, Object> config = new TreeMap<String, Object>();
            config.put("secretId", secretId);
            config.put("secretKey", secretKey);
            config.put("durationSeconds", durationSeconds);
            config.put("bucket", bucket);
            config.put("region", region);

            // 可以通过 allowPrefixes 指定前缀数组, 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            config.put("allowPrefixes", new String[]{
                    cosObjectKey
                    // "good",
                    // "avatar"
            });

            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[]{
                    // 简单上传
                    "name/cos:PutObject",
                    "name/cos:PostObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);

            Response response = CosStsClient.getCredential(config);

            long startTimestamp = System.currentTimeMillis();
            long expiredTimestamp = startTimestamp + (durationSeconds * 1000);

            return new TmpCredential(response, cosObjectKey, startTimestamp, expiredTimestamp, bucket, region);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("no valid secret !");
        }
    }
}
