/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.dianguang.cloud.ossservice.service;

import com.aliyun.oss.OSSClient;
import com.dianguang.cloud.ossservice.config.CloudStorageConfig;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class AliyunCloudStorageService extends AbstractCloudStorageService {

    public AliyunCloudStorageService(CloudStorageConfig config){
        this.config = config;
    }

    @Override
    public String upload(byte[] data, String path) throws Exception {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) throws Exception {
        OSSClient client = new OSSClient(config.getEndPoint(), config.getAccessKey(),
                config.getSecretKey());
        try {
            client.putObject(config.getBucketName(), path, inputStream);
            client.shutdown();
        } catch (Exception e){
            throw new Exception("上传异常");
        }

        return "https://"+config.getUrl() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) throws Exception {
        return upload(data, getPath(config.getPrefix(), suffix));
    }

    @Override
    public String uploadFileName(byte[] data, String suffix,String fileName) throws Exception {
        return upload(data, getPath(config.getPrefix(), suffix,fileName));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) throws Exception {
        return upload(inputStream, getPath(config.getPrefix(), suffix));
    }
}