<?php
/**
 * JYmusic音乐管理系统
 *
 * @version     2.0
 * @author      战神~~巴蒂 <jyuucn@163.com>
 * @license     http://jyuu.cn [未经授权严禁私自出售，否者承担法律责任]
 * @copyright   2014 - 2017 JYmusic
 */

namespace addons\Upload\controller;

use Qiniu\Auth;
use Qiniu\Zone;

class QiniuController extends BaseController
{
    
    protected  $uploadConf;
    
    public function _initialize()
    {
        $this->uploadConf = get_addon_config('Upload');
    }

    //用户上传需要验证token
    public function sign()
    {
        $accessKey = $this->uploadConf['qiniu_ak'];
        $secretKey = $this->uploadConf['qiniu_sk'];
        $bucket   = $this->uploadConf['qiniu_bucket'];
    
        if (empty($accessKey) || empty($secretKey) || empty($bucket)) {
            return json([
                'code' => 40030,
                'error' => '七牛云存储配置不正确，缺失参数'
            ]);
        }
        
    
        $host  = $this->uploadConf['qiniu_domain'];
        
        //$maxSize  = $maxSize? $maxSize * 1024*1024 : 1048576000;
        $filename = $this->request->param('filename');
        $uploadType = $this->request->param('upload_type');
        
        if ($uploadType == 'listen') {
            $uploadDir = $this->uploadConf['qiniu_listen_dir'];
            $uploadDir = !empty($uploadDir)? $uploadDir : 'listen';
        } elseif ($uploadType == 'down') {
            $uploadDir = $this->uploadConf['qiniu_down_dir'];
            $uploadDir = !empty($uploadDir)? $uploadDir : 'down';
        } else {
            $uploadDir = $this->uploadConf['qiniu_image_dir'];
            $uploadDir = !empty($uploadDir)? $uploadDir : 'images';
        }
        $uploadDir = rtrim($uploadDir, '/') . '/';
    
        $auth   = new Auth($accessKey, $secretKey);
        $key    = $uploadDir .  $filename;
        $expire = $this->uploadConf['qiniu_timeout'] * 100;
        
        $upToken = $auth->uploadToken($bucket, $key, $expire);
        
        $zone = new Zone();
        $hosts = $zone->getUpHosts($accessKey, $bucket);
        
        $response = [
            'code' => 0,
            'result' => [
                'key' => $key,
                'host' => $hosts[0][0],
                'token' => $upToken,
                'filepath' => rtrim($host, '/') . '/' . $key
            ]
        ];
        
        return json($response);
    }
    
}
