Index.php 8.7 KB
<?php

namespace addons\upyun\controller;

use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Attachment;
use think\addons\Controller;
use think\Config;
use Upyun\Api\Rest;
use Upyun\Signature;
use Upyun\Upyun;
use Upyun\Util;

/**
 * 又拍云云储存
 *
 */
class Index extends Controller
{

    /**
     * @var \Upyun\Config
     */
    protected $config = null;

    public function _initialize()
    {
        //跨域检测
        check_cors_request();

        parent::_initialize();
        Config::set('default_return_type', 'json');

        $config = get_addon_config('upyun');
        $this->config = new \Upyun\Config($config['bucket'], $config['operator'], $config['password']);
    }

    public function index()
    {
        Config::set('default_return_type', 'html');
        $this->error("当前插件暂无前台页面");
    }

    /**
     * 获取签名
     */
    public function params()
    {
        $this->check();
        $name = $this->request->post('name');
        $md5 = $this->request->post('md5');
        $chunk = $this->request->post('chunk');
        $config = get_addon_config('upyun');

        $upload = new Upload();
        $url = $upload->getSavekey($config['savekey'], $name, $md5);

        $signature = Signature::getHeaderSign($this->config, 'PUT', '/' . $config['bucket'] . $url);
        $data = [];
        $data['headers'] = $signature;
        $data['url'] = $url;
        if ($chunk) {
            $type = $this->request->post('type');
            $fileSize = $this->request->post('size');
            $chunkSize = $this->request->post('chunkSize');
            //如果分片大小不是整数,则进行变更
            if (!is_int($chunkSize / 1024 / 1024)) {
                $chunkSize = 1024 * 1024 * 2;
            }
            $req = new Rest($this->config);
            $res = $req->request('PUT', $url)
                ->withHeaders(array(
                    'X-Upyun-Multi-Disorder'  => 'true',
                    'X-Upyun-Multi-Stage'     => 'initiate',
                    'X-Upyun-Multi-Length'    => (string)$fileSize,
                    'X-Upyun-Multi-Type'      => $type,
                    'X-Upyun-Multi-Part-Size' => $chunkSize,
                ))
                ->send();
            if ($res->getStatusCode() !== 204) {
                $this->error('初始化失败');
            }

            $init = Util::getHeaderParams($res->getHeaders());

            $data['headers']['X-Upyun-Multi-Stage'] = 'upload';
            $data['headers']['X-Upyun-Multi-Uuid'] = $init['x-upyun-multi-uuid'];
            $data['uuid'] = $init['x-upyun-multi-uuid'];
            $data['chunkSize'] = $chunkSize;

            $this->success("", "", $data);
        } else {
            $this->success('', null, $data);
        }

        return;
    }

    /**
     * 服务器中转上传文件
     * 上传分片
     * 合并分片
     */
    public function upload()
    {
        $this->check();
        $config = get_addon_config('upyun');

        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filesize = $this->request->post("filesize");
            $filename = $this->request->post("filename");
            $url = $this->request->post("url");
            $uuid = $this->request->post("uuid");

            if ($action == 'merge') {
                //合并分片
                if ($config['uploadmode'] == 'server') {
                    $attachment = null;
                    //合并分片文件
                    try {
                        $upload = new Upload();
                        $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                }

                try {
                    $req = new Rest($this->config);
                    $res = $req->request('PUT', $url)
                        ->withHeaders(array(
                            'X-Upyun-Multi-Uuid'  => $uuid,
                            'X-Upyun-Multi-Stage' => 'complete'
                        ))
                        ->send();
                    if ($res->getStatusCode() != 204 && $res->getStatusCode() != 201) {
                        throw new \Exception('end request failed when poinit upload!');
                    }
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
                $this->success("上传成功", '', ['url' => $url, 'fullurl' => cdnurl($url, true)]);
            } else {
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                try {
                    //上传分片到OSS
                    $req = new Rest($this->config);
                    $req->request('PUT', $url)
                        ->withHeaders(array(
                            'X-Upyun-Multi-Stage' => 'upload',
                            'X-Upyun-Multi-Uuid'  => $uuid,
                            'X-Upyun-Part-Id'     => $chunkindex
                        ))
                        ->withFile($file)
                        ->send();
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }

                $this->success("上传成功", "", [], 3, ['url' => $url]);
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            //文件绝对路径
            $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

            try {
                $upyun = new Upyun($this->config);
                $ret = $upyun->write($attachment->url, $upload->getFile());
                //成功不做任何操作
            } catch (\Exception $e) {
                $attachment->delete();
                @unlink($filePath);
                $this->error("上传失败");
            }

            $this->success("上传成功", '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }
        return;
    }

    /**
     * 回调
     */
    public function notify()
    {
        $this->check();
        $size = $this->request->post('size');
        $name = $this->request->post('name');
        $md5 = $this->request->post('md5');
        $type = $this->request->post('type');
        $url = $this->request->post('url');
        $suffix = substr($name, stripos($name, '.') + 1);
        $attachment = Attachment::where('url', $url)->where('storage', 'upyun')->find();
        if (!$attachment) {
            $params = array(
                'admin_id'    => (int)session('admin.id'),
                'user_id'     => (int)cookie('uid'),
                'filesize'    => $size,
                'filename'    => $name,
                'imagewidth'  => 0,
                'imageheight' => 0,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $type,
                'url'         => $url,
                'uploadtime'  => time(),
                'storage'     => 'upyun',
                'sha1'        => $md5,
            );
            Attachment::create($params);
        }
        $this->success();
        return;
    }

    /**
     * 检查签名是否正确或过期
     */
    protected function check()
    {
        $upyuntoken = $this->request->post('upyuntoken', '', 'trim');
        if (!$upyuntoken) {
            $this->error("参数不正确");
        }
        $config = get_addon_config('upyun');
        list($sign, $data) = explode(':', $upyuntoken);
        if (!$sign || !$data) {
            $this->error("参数不正确");
        }
        $policy = $data;
        if (base64_decode($sign) !== Signature::getBodySignature($this->config, 'POST', '/' . $config['bucket'], null, $policy)) {
            $this->error("签名不正确");
        }
        $json = json_decode(base64_decode($data), true);
        if ($json['expiration'] < time()) {
            $this->error("请求已经超时");
        }
    }

}