package com.cnd3b.utility.obs;

import com.obs.services.ObsClient;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.ObjectMetadata;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import com.obs.services.model.fs.DropFolderRequest;

public class BucketFileTest {
    protected String bucketname;
    ObsClient obsClient;

    public BucketFileTest(String siteid) {
        // 创建ObsClient实例
        obsClient = new ObsClient("EKJMDXUVJLBGDRCVVVLP", "9EUAXeFmxKjJ5x12lYVTzCCUuIQIjrO6VAyzGr9u", "obs.cn-east-2.myhuaweicloud.com");
        this.bucketname = siteid.toLowerCase();
    }

    public static void main(String[] args) {
//        BucketFileTest bucketFile1 = new BucketFileTest("BCDQ");
//        //ObjectMetadata data= bucketFile1.getObjectMetadata("202108031627962912130B1e0afa29.mp4");
//        //System.err.println(data.getContentLength());
//        bucketFile1.getCes();
//        bucketFile1.close();
//        //BucketFileTest bucketFile1 = new BucketFileTest("BCDQ");
    }

    public boolean doesObjectExist(String objectname) {
        return obsClient.doesObjectExist(bucketname, objectname);
    }

    /**
     * 文件删除,如果存在缩略文件，则缩略文件会一起删除
     *
     * @param objectname
     */
    public void deleteFile(String objectname) {
        obsClient.deleteObject(bucketname, objectname);
        if (obsClient.doesObjectExist(bucketname, "s_" + objectname)) {
            obsClient.deleteObject(bucketname, "s_" + objectname);
        }
        if (obsClient.doesObjectExist(bucketname, "c_" + objectname)) {
            obsClient.deleteObject(bucketname, "c_" + objectname);
        }
    }

    public void deleteFolder(String foldername) {
        DropFolderRequest dropFolderRequest = new DropFolderRequest(bucketname, foldername);
        obsClient.dropFolder(dropFolderRequest);
    }

    public ObjectMetadata getObjectMetadata(String objectname) {
        ObjectMetadata metadata = obsClient.getObjectMetadata(bucketname, objectname);
        return metadata;
    }

    /**
     * 获取文件下载地址
     */
    public String getFileUrl(String filename) {
        //临时访问地址有效时间
        //long expireSeconds = 3600L;
        // 创建ObsClient实例
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, 3600);
        request.setBucketName(bucketname);
        request.setObjectKey(filename);
        // 生成临时授权URL
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);

        //截取永久访问url，需要桶设置公共访问策略
        String url = response.getSignedUrl();
        return url.substring(0, url.indexOf("?"));
    }

    /**
     * 关闭
     */
    public void close() {
        if (obsClient != null) {
            try {
                obsClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
