package com.yutou.tools.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yutou.tools.interfaces.DownloadInterface;

import java.io.*;

public class OSSTools {
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    private static String accessKeyId = "LTAI4G7J5pWbZeYdhFvGb4Dj";
    private static String accessKeySecret = "GyXRDaOkER2qArGu4A2Tiym6ajuQPd";
    private static String bucketName = "yutou-oss-test";
    public static void uploadFile(File file, DownloadInterface downloadInterface) {
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        String objectName = "bot/download/"+System.currentTimeMillis()+"/"+file.getName();
// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        try {
            InputStream inputStream=new FileInputStream(file);
            ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
            byte[] bytes=new byte[4096];
            int len;
            while ((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(outputStream.toByteArray()));
            outputStream.close();
            inputStream.close();

            downloadInterface.onDownload("https://yutou-oss-test.oss-cn-hangzhou.aliyuncs.com/"+objectName);
        } catch (Exception e) {
            e.printStackTrace();
            downloadInterface.onError(e);
        }
// 关闭OSSClient。
        ossClient.shutdown();
    }
    public static void delete(String path){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, path);
        ossClient.shutdown();
    }
}
