Aliyundrive.php 33.9 KB
Newer Older
R
v3  
root 已提交
1 2 3 4 5 6 7 8 9 10 11
<?php

class Aliyundrive {
    protected $access_token;
    protected $disktag;

    function __construct($tag) {
        $this->disktag = $tag;
        $this->auth_url = 'https://websv.aliyundrive.com/token/refresh';
        $this->api_url = 'https://api.aliyundrive.com/v2';
        $this->default_drive_id = getConfig('default_drive_id', $tag);
12
        $res = $this->get_access_token(getConfig('refresh_token', $tag));
R
v3  
root 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
    }
    
    public function isfine()
    {
        if (!$this->access_token) return false;
        else return true;
    }
    public function show_base_class()
    {
        return get_class();
        //$tmp[0] = get_class();
        //$tmp[1] = get_class($this);
        //return $tmp;
    }

Q
qkqpttgf 已提交
28 29
    public function ext_show_innerenv()
    {
R
root 已提交
30
        return ['default_drive_id'];
Q
qkqpttgf 已提交
31 32
    }

R
v3  
root 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
    public function list_files($path = '/')
    {

        $files = $this->list_path($path);

        return $this->files_format($files);
    }

    protected function files_format($files)
    {
        //return $files;
        if ($files['type']=='file') {
            $tmp['type'] = 'file';
            $tmp['id'] = $files['file_id'];
            if (isset($files['name'])) $tmp['name'] = $files['name'];
            elseif (isset($files['file_name'])) $tmp['name'] = $files['file_name'];
            $tmp['time'] = $files['updated_at'];
            $tmp['size'] = $files['size'];
            $tmp['mime'] = $files['file']['mimeType'];
            $tmp['url'] = $files['download_url'];
            $tmp['content'] = $files['content'];
            if (isset($files['exist'])) $tmp['exist'] = $files['exist'];
            if (isset($files['rapid_upload'])) $tmp['rapid_upload'] = $files['rapid_upload'];
        } elseif ($files['type']=='folder'||isset($files['items'])) {
            $tmp['type'] = 'folder';
            $tmp['id'] = $files['file_id'];
            if (isset($files['name'])) $tmp['name'] = $files['name'];
            elseif (isset($files['file_name'])) $tmp['name'] = $files['file_name'];
            $tmp['time'] = $files['updated_at'];
            $tmp['size'] = $files['size'];
            //$tmp['page'] = $files['folder']['page'];
            foreach ($files['items'] as $file) {
65
                $filename = strtolower($file['name']);
R
v3  
root 已提交
66
                if ($file['type']=='file') {
67 68 69
                    $tmp['list'][$filename]['type'] = 'file';
                    $tmp['list'][$filename]['url'] = $file['download_url'];
                    $tmp['list'][$filename]['mime'] = $file['file']['content_type'];
R
v3  
root 已提交
70
                } elseif ($file['type']=='folder') {
71
                    $tmp['list'][$filename]['type'] = 'folder';
R
v3  
root 已提交
72 73
                }
                //$tmp['id'] = $file['parent_file_id'];
74 75 76 77
                $tmp['list'][$filename]['id'] = $file['file_id'];
                $tmp['list'][$filename]['name'] = $file['name'];
                $tmp['list'][$filename]['time'] = $file['updated_at'];
                $tmp['list'][$filename]['size'] = $file['size'];
R
v3  
root 已提交
78 79
                $tmp['childcount']++;
            }
Q
qkqpttgf 已提交
80
        } elseif (isset($files['code'])||isset($files['error'])) {
R
v3  
root 已提交
81 82
            return $files;
        }
83
        //error_log1(json_encode($tmp));
R
v3  
root 已提交
84 85 86 87 88 89 90
        return $tmp;
    }

    protected function list_path($path = '/')
    {
        global $exts;
        while (substr($path, -1)=='/') $path = substr($path, 0, -1);
Q
qkqpttgf 已提交
91
        if ($path == '') $path = '/';
R
v3  
root 已提交
92 93
        //$files = getcache('path_' . $path, $this->disktag);
        //if (!$files) {
Q
qkqpttgf 已提交
94
        if (!($files = getcache('path_' . $path, $this->disktag))) {
R
v3  
root 已提交
95 96
            if ($path == '/' || $path == '') {
                $files = $this->fileList('root');
97
                //error_log1('root_id' . $files['id']);
R
v3  
root 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
                $files['file_id'] = 'root';
                $files['type'] = 'folder';
            } else {
                $tmp = splitlast($path, '/');
                $parent_path = $tmp[0];
                $filename = urldecode($tmp[1]);
                $parent_folder = $this->list_path($parent_path);
                foreach ($parent_folder['items'] as $item) {
                    if ($item['name']==$filename) {
                        if ($item['type']=='folder') {
                            $files = $this->fileList($item['file_id']);
                            $files['type'] = 'folder';
                            $files['file_id'] = $item['file_id'];
                            $files['name'] = $item['name'];
                            $files['time'] = $item['updated_at'];
                            $files['size'] = $item['size'];
                        } else $files = $item;
                        
                    }
                    
                }
                //echo $files['name'];
            }
            if ($files['type']=='file') {
                if (in_array(splitlast($files['name'],'.')[1], $exts['txt'])) {
                    if (!(isset($files['content'])&&$files['content']['stat']==200)) {
                        $content1 = curl('GET', $files['download_url']);
                        $files['content'] = $content1;
                        savecache('path_' . $path, $files, $this->disktag);
                    }
R
root 已提交
128
                    error_log1($files['name'] . ' : ' . json_encode($files['content']) . PHP_EOL);
R
v3  
root 已提交
129 130 131 132 133 134 135
                }
            }
            if (!$files) {
                $files['error']['code'] = 'Not Found';
                $files['error']['message'] = 'Not Found';
                $files['error']['stat'] = 404;
            } elseif (isset($files['stat'])) {
Q
qkqpttgf 已提交
136
                $files['error']['stat'] = $files['stat'];
R
v3  
root 已提交
137 138 139 140 141
                $files['error']['code'] = 'Error';
                $files['error']['message'] = $files['body'];
            } else {
                savecache('path_' . $path, $files, $this->disktag, 600);
            }
Q
qkqpttgf 已提交
142 143
        }
        //error_log1('path:' . $path . ', files:' . substr(json_encode($files), 0, 150));
R
v3  
root 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        return $files;
    }

    protected function fileGet($file_id)
    {
        $url = $this->api_url . '/file/get';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;

        $data['drive_id'] = $this->default_drive_id;
        $data['file_id'] = $file_id;

        $res = curl('POST', $url, json_encode($data), $header);
        if ($res['stat']==200) return json_decode($res['body'], true);
        else return $res;
    }
    protected function fileList($parent_file_id)
    {
        $url = $this->api_url . '/file/list';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;

        $data['limit'] = 50;
        $data['marker'] = NULL;
        $data['drive_id'] = $this->default_drive_id;
        $data['parent_file_id'] = $parent_file_id;
        $data['image_thumbnail_process'] = 'image/resize,w_160/format,jpeg';
        $data['image_url_process'] = 'image/resize,w_1920/format,jpeg';
        $data['video_thumbnail_process'] = 'video/snapshot,t_0,f_jpg,w_300';
        $data['fields'] = '*';
        $data['order_by'] = 'updated_at';
        $data['order_direction'] = 'DESC';

        $res = curl('POST', $url, json_encode($data), $header);
        if ($res['stat']==200) return json_decode($res['body'], true);
        else return $res;
    }

    public function Rename($file, $newname) {
        $url = $this->api_url . '/file/update';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;

        $data['check_name_mode'] = 'refuse';
        $data['drive_id'] = $this->default_drive_id;
        $data['file_id'] = $file['id'];
        $data['name'] = $newname;
        //$data['parent_file_id'] = 'root';

        $result = curl('POST', $url, json_encode($data), $header);
        //savecache('path_' . $file['path'], json_decode('{}',true), $this->disktag, 1);
198
        //error_log1('decode:' . json_encode($result));
R
v3  
root 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
        //return output($result['body'], $result['stat']);
    }
    public function Delete($file) {
        $url = $this->api_url . '/batch';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;

        $data['resource'] = 'file';
        $data['requests'][0]['url'] = '/file/delete';
        $data['requests'][0]['method'] = 'DELETE';
        $data['requests'][0]['id'] = $file['id'];
        $data['requests'][0]['headers']['Content-Type'] = 'application/json';
        $data['requests'][0]['body']['drive_id'] = $this->default_drive_id;
        $data['requests'][0]['body']['file_id'] = $file['id'];

        $result = curl('POST', $url, json_encode($data), $header);
        //savecache('path_' . $file['path'], json_decode('{}',true), $this->disktag, 1);
218
        //error_log1('result:' . json_encode($result));
R
v3  
root 已提交
219 220 221 222 223 224 225 226 227 228
        //return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
        $res = json_decode($result['body'], true)['responses'][0];
        if (isset($res['status'])) return output($res['id'], $res['status']);
        else return output($result['body'], $result['stat']);
    }
    public function Encrypt($folder, $passfilename, $pass) {
        $existfile = $this->list_path($folder['path'] . '/' . $passfilename);
        if (isset($existfile['type'])) { // 删掉原文件
            $this->Delete(['id'=>$existfile['file_id']]);
        }
Q
qkqpttgf 已提交
229 230 231 232
        if ($pass==='') {
            // 如果为空,上面已经删除了
            return output('Success', 200);
        }
R
v3  
root 已提交
233 234
        if (!$folder['id']) {
            $res = $this->list_path($folder['path']);
235
            //error_log1('res:' . json_encode($res));
R
v3  
root 已提交
236 237 238 239 240 241 242 243
            $folder['id'] = $res['file_id'];
        }
        $tmp = '/tmp/' . $passfilename;
        file_put_contents($tmp, $pass);

        $result = $this->tmpfileCreate($folder['id'], $tmp, $passfilename);

        if ($result['stat']==201) {
244
            //error_log1('1,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
245 246 247 248 249 250 251 252 253
            $res = json_decode($result['body'], true);
            $url = $res['part_info_list'][0]['upload_url'];
            if (!$url) { // 无url,应该算秒传
                return output('no up url', 200);
            }
            $file_id = $res['file_id'];
            $upload_id = $res['upload_id'];
            $result = curl('PUT', $url, $pass, [], 1);
            if ($result['stat']==200) { // 块1传好
R
root 已提交
254
                $result = $this->fileComplete($file_id, $upload_id, [ $result['returnhead']['ETag'] ]);
R
v3  
root 已提交
255 256 257
                return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
            }
        }
258
        //error_log1('2,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
259 260 261 262 263
        return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
    }
    public function Move($file, $folder) {
        if (!$folder['id']) {
            $res = $this->list_path($folder['path']);
264
            //error_log1('res:' . json_encode($res));
R
v3  
root 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
            $folder['id'] = $res['file_id'];
        }

        $url = $this->api_url . '/batch';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;

        $data['resource'] = 'file';
        $data['requests'][0]['url'] = '/file/move';
        $data['requests'][0]['method'] = 'POST';
        $data['requests'][0]['id'] = $file['id'];
        $data['requests'][0]['headers']['Content-Type'] = 'application/json';
        $data['requests'][0]['body']['drive_id'] = $this->default_drive_id;
        $data['requests'][0]['body']['file_id'] = $file['id'];
        $data['requests'][0]['body']['auto_rename'] = true;
        $data['requests'][0]['body']['to_parent_file_id'] = $folder['id'];

        $result = curl('POST', $url, json_encode($data), $header);
        //savecache('path_' . $file['path'], json_decode('{}',true), $this->disktag, 1);
285
        //error_log1('result:' . json_encode($result));
R
v3  
root 已提交
286 287 288 289 290
        return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
    }
    public function Copy($file) {
        if (!$file['id']) {
            $oldfile = $this->list_path($file['path'] . '/' . $file['name']);
291
            //error_log1('res:' . json_encode($res));
R
v3  
root 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
            //$file['id'] = $res['file_id'];
        } else {
            $oldfile = $this->fileGet($file['id']);
        }

        $url = $this->api_url . '/file/create';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;

        $data['check_name_mode'] = 'auto_rename'; // ignore, auto_rename, refuse.
        $data['content_hash'] = $oldfile['content_hash'];
        $data['content_hash_name'] = 'sha1';
        $data['content_type'] = $oldfile['content_type'];
        $data['drive_id'] = $this->default_drive_id;
        $data['ignoreError'] = false;
        $data['name'] = $oldfile['name'];
        $data['parent_file_id'] = $oldfile['parent_file_id'];
        $data['part_info_list'][0]['part_number'] = 1;
        $data['size'] = $oldfile['size'];
        $data['type'] = 'file';

        $result = curl('POST', $url, json_encode($data), $header);

        if ($result['stat']==201) {
317
            //error_log1('1,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
318 319 320 321 322 323 324 325 326 327 328 329
            $res = json_decode($result['body'], true);
            $url = $res['part_info_list'][0]['upload_url'];
            if (!$url) { // 无url,应该算秒传
                return output('no up url', 200);
            } else {
                return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
            }
            /*$file_id = $res['file_id'];
            $upload_id = $res['upload_id'];
            $result = curl('PUT', $url, $content, [], 1);
            if ($result['stat']==200) { // 块1传好
                $etag = $result['returnhead']['ETag'];
R
root 已提交
330
                $result = $this->fileComplete($file_id, $upload_id, [ $etag ]);
R
v3  
root 已提交
331 332 333 334
                if ($result['stat']!=200) return output($result['body'], $result['stat']);
                else return output('success', 0);
            }*/
        }
335
        //error_log1('2,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
        return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
    }
    public function Edit($file, $content) {
        $tmp = splitlast($file['path'], '/');
        $folderpath = $tmp[0];
        $filename = $tmp[1];
        $existfile = $this->list_path($file['path']);
        if (isset($existfile['type'])) { // 删掉原文件
            $this->Delete(['id'=>$existfile['file_id']]);
        }
        $tmp1 = '/tmp/' . $filename;
        file_put_contents($tmp1, $content);

        $result = $this->tmpfileCreate($this->list_path($folderpath)['file_id'], $tmp1, $filename);

        if ($result['stat']==201) {
352
            //error_log1('1,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
353 354 355 356 357 358 359 360 361
            $res = json_decode($result['body'], true);
            $url = $res['part_info_list'][0]['upload_url'];
            if (!$url) { // 无url,应该算秒传
                return output('no up url', 0);
            }
            $file_id = $res['file_id'];
            $upload_id = $res['upload_id'];
            $result = curl('PUT', $url, $content, [], 1);
            if ($result['stat']==200) { // 块1传好
R
root 已提交
362
                $result = $this->fileComplete($file_id, $upload_id, [ $result['returnhead']['ETag'] ]);
R
v3  
root 已提交
363 364 365 366
                if ($result['stat']!=200) return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
                else return output('success', 0);
            }
        }
367
        //error_log1('2,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
368 369 370 371 372
        return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
    }
    public function Create($folder, $type, $name, $content = '') {
        if (!$folder['id']) {
            $res = $this->list_path($folder['path']);
373
            //error_log1('res:' . json_encode($res));
R
v3  
root 已提交
374 375 376 377
            $folder['id'] = $res['file_id'];
        }
        if ($type=='folder') {
            $result = $this->folderCreate($folder['id'], $name);
378
            //error_log1('res:' . json_encode($result));
R
v3  
root 已提交
379 380 381 382 383 384 385 386 387
            return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
        }
        if ($type=='file') {
            $tmp = '/tmp/' . $name;
            file_put_contents($tmp, $content);

            $result = $this->tmpfileCreate($folder['id'], $tmp, $name);

            if ($result['stat']==201) {
388
                //error_log1('1,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
389 390 391
                $res = json_decode($result['body'], true);
                if (isset($res['exist'])&&$res['exist']!=false) {
                    // 已经有
392
                    //error_log1('exist:' . json_encode($res));
R
v3  
root 已提交
393 394 395 396
                    return output('{"type":"file","name":"' . $name . '", "exist":true}', 200);
                }
                if (isset($res['rapid_upload'])&&$res['rapid_upload']!=false) {
                    // 秒传
397
                    //error_log1('rapid up:' . json_encode($res));
R
v3  
root 已提交
398 399 400 401 402 403
                    return output('{"type":"file","name":"' . $name . '", "rapid_upload":true}', 200);
                }
                $url = $res['part_info_list'][0]['upload_url'];
                $file_id = $res['file_id'];
                $upload_id = $res['upload_id'];
                $result = curl('PUT', $url, $content, [], 1);
404
                //error_log1('2,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
405
                if ($result['stat']==200) { // 块1传好
R
root 已提交
406
                    $result = $this->fileComplete($file_id, $upload_id, [ $result['returnhead']['ETag'] ]);
407
                    //error_log1('3,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
408 409 410
                    return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
                }
            }
411
            //error_log1('4,url:' . $url .' res:' . json_encode($result));
R
v3  
root 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
            return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
        }
        return output('Type not folder or file.', 500);
    }

    protected function folderCreate($parentId, $folderName) {
        if (strrpos($folderName, '/')) {
            $tmp = splitlast($folderName, '/');
            $parentId = json_decode($this->folderCreate($parentId, $tmp[0])['body'], true)['file_id'];
            $folderName = $tmp[1];
        }
        $url = $this->api_url . '/file/create';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;

        $data['check_name_mode'] = 'refuse'; // ignore, auto_rename, refuse.
        $data['drive_id'] = $this->default_drive_id;
        $data['name'] = $folderName;
        $data['parent_file_id'] = $parentId;
        $data['type'] = 'folder';

        return curl('POST', $url, json_encode($data), $header);
    }
436
    protected function fileCreate($parentId, $fileName, $sha1, $size, $part_number) {
R
v3  
root 已提交
437 438 439 440 441 442 443 444 445 446 447 448 449
        $url = $this->api_url . '/file/create';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;
    
        $data['check_name_mode'] = 'refuse'; // ignore, auto_rename, refuse.
        $data['content_hash'] = $sha1;
        $data['content_hash_name'] = 'sha1';
        $data['content_type'] = '';
        $data['drive_id'] = $this->default_drive_id;
        $data['ignoreError'] = false;
        $data['name'] = $fileName;
        $data['parent_file_id'] = $parentId;
450 451 452
        for ($i=0;$i<$part_number;$i++) {
            $data['part_info_list'][$i]['part_number'] = $i+1;
        }
R
v3  
root 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
        $data['size'] = (int)$size;
        $data['type'] = 'file';

        return curl('POST', $url, json_encode($data), $header);
    }
    protected function tmpfileCreate($parentId, $tmpFilePath, $tofileName = '') {
        $sha1 = sha1_file($tmpFilePath);
        if ($tofileName == '') $tofileName = splitlast($tmpFilePath, '/')[1];
        $url = $this->api_url . '/file/create';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;

        $data['check_name_mode'] = 'refuse'; // ignore, auto_rename, refuse.
        $data['content_hash'] = $sha1;
        $data['content_hash_name'] = 'sha1';
        $data['content_type'] = 'text/plain'; // now only txt
        $data['drive_id'] = $this->default_drive_id;
        $data['ignoreError'] = false;
        $data['name'] = $tofileName;
        $data['parent_file_id'] = $parentId;
        $data['part_info_list'][0]['part_number'] = 1; // now only txt
        $data['size'] = filesize($tmpFilePath);
        $data['type'] = 'file';

        return curl('POST', $url, json_encode($data), $header);
    }
    protected function fileComplete($file_id, $upload_id, $etags) {
        $url = $this->api_url . '/file/complete';

        $header["content-type"] = "application/json; charset=utf-8";
        $header['authorization'] = 'Bearer ' . $this->access_token;

        $data['drive_id'] = $this->default_drive_id;
        $data['file_id'] = $file_id;
        $data['ignoreError'] = false;
489
        $i = 0;
R
v3  
root 已提交
490
        foreach ($etags as $etag) {
491 492 493
            $data['part_info_list'][$i]['part_number'] = $i + 1;
            $data['part_info_list'][$i]['etag'] = $etag;
            $i++;
R
v3  
root 已提交
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
        }
        $data['upload_id'] = $upload_id;

        return curl('POST', $url, json_encode($data), $header);
    }

    public function get_thumbnails_url($path = '/')
    {
        $res = $this->list_path($path);
        $thumb_url = $res['thumbnail'];
        return $thumb_url;
    }
    public function bigfileupload($path)
    {
        if (isset($_POST['uploadid'])) {
            // Complete
510
            $result = $this->fileComplete($_POST['fileid'], $_POST['uploadid'], json_decode($_POST['etag'], true));
R
v3  
root 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
            return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
        } else {
            if ($_POST['upbigfilename']=='') return output('error: no file name', 400);
            if (!is_numeric($_POST['filesize'])) return output('error: no file size', 400);
            if (!isset($_POST['filesha1'])) return output('error: no file sha1', 400);

            $tmp = splitlast($_POST['upbigfilename'], '/');
            if ($tmp[1]!='') {
                $fileinfo['name'] = $tmp[1];
                if ($_SERVER['admin']) $fileinfo['path'] = $tmp[0];
            } else {
                $fileinfo['name'] = $_POST['upbigfilename'];
            }
            $fileinfo['size'] = $_POST['filesize'];
            $fileinfo['filelastModified'] = $_POST['filelastModified'];
            if ($_SERVER['admin']) {
                $filename = $fileinfo['name'];
            } else {
                $tmp1 = splitlast($fileinfo['name'], '.');
                if ($tmp1[0]==''||$tmp1[1]=='') $filename = $_POST['filesha1'];
                else $filename = $_POST['filesha1'] . '.' . $tmp1[1];
            }
            /*if ($fileinfo['size']>10*1024*1024) {
                $cachefilename = spurlencode( $fileinfo['path'] . '/.' . $fileinfo['filelastModified'] . '_' . $fileinfo['size'] . '_' . $fileinfo['name'] . '.tmp', '/');
                $getoldupinfo=$this->list_path(path_format($path . '/' . $cachefilename));
                //echo json_encode($getoldupinfo, JSON_PRETTY_PRINT);
                if ($getoldupinfo['type']=='file'&&$getoldupinfo['size']<5120) {
                    $getoldupinfo_j = curl('GET', $getoldupinfo['url']);
                    $getoldupinfo = json_decode($getoldupinfo_j['body'], true);
                    //if ( json_decode( curl('GET', $getoldupinfo['uploadUrl'])['body'], true)['@odata.context']!='' ) return output($getoldupinfo_j['body'], $getoldupinfo_j['stat']);
                }
            }*/
            $parent = $this->list_path($path . '/' . $fileinfo['path']);
            if (isset($parent['file_id'])) {
                $parent_file_id = $parent['file_id'];
            } else {
                $res = $this->folderCreate($this->list_path($path)['file_id'], $fileinfo['path']);
548
                //error_log1($res['body']);
R
v3  
root 已提交
549 550
                $parent_file_id = json_decode($res['body'], true)['file_id'];
            }
551
            $response = $this->fileCreate($parent_file_id, $filename, $_POST['filesha1'], $fileinfo['size'], ceil($fileinfo['size']/$_POST['chunksize']));
R
v3  
root 已提交
552 553 554
            $res = json_decode($response['body'], true);
            if (isset($res['exist'])) {
                // 已经有
555
                //error_log1('exist:' . json_encode($res));
R
v3  
root 已提交
556 557 558 559 560
                return output(json_encode($this->files_format(json_decode($response['body'], true))), $response['stat']);
                //return output('{"type":"file","name":"' . $_POST['upbigfilename'] . '", "exist":true}', 200);
            }
            if (isset($res['rapid_upload'])&&$res['rapid_upload']!=false) {
                // 秒传
561
                //error_log1('rapid up:' . json_encode($res));
R
v3  
root 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
                return output(json_encode($this->files_format(json_decode($response['body'], true))), $response['stat']);
                //return output('{"type":"file","name":"' . $_POST['upbigfilename'] . '", "rapid upload":true}', 200);
            }
            //if ($response['stat']<500) {
            //    $responsearry = json_decode($response['body'], true);
            //    if (isset($responsearry['error'])) return output($response['body'], $response['stat']);
            //    $fileinfo['uploadUrl'] = $responsearry['uploadUrl'];
            //    if ($fileinfo['size']>10*1024*1024) $this->MSAPI('PUT', path_format($path . '/' . $cachefilename), json_encode($fileinfo, JSON_PRETTY_PRINT), $this->access_token);
            //}
            return output($response['body'], $response['stat']);
        }
    }

    public function AddDisk() {
        global $constStr;
        global $EnvConfigs;

        $envs = '';
        foreach ($EnvConfigs as $env => $v) if (isCommonEnv($env)) $envs .= '\'' . $env . '\', ';
        $url = path_format($_SERVER['PHP_SELF'] . '/');

        if (isset($_GET['install0']) && $_POST['disktag_add']!='') {
            $_POST['disktag_add'] = preg_replace('/[^0-9a-zA-Z|_]/i', '', $_POST['disktag_add']);
            $f = substr($_POST['disktag_add'], 0, 1);
            if (strlen($_POST['disktag_add'])==1) $_POST['disktag_add'] .= '_';
            if (isCommonEnv($_POST['disktag_add'])) {
                return message('Do not input ' . $envs . '<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>
                <script>
                var expd = new Date();
                expd.setTime(expd.getTime()+1);
                var expires = "expires="+expd.toGMTString();
                document.cookie=\'disktag=; path=/; \'+expires;
                </script>', 'Error', 201);
            } elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) {
                return message('Please start with letters<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>
                <script>
                var expd = new Date();
                expd.setTime(expd.getTime()+1);
                var expires = "expires="+expd.toGMTString();
                document.cookie=\'disktag=; path=/; \'+expires;
                </script>', 'Error', 201);
            }
604
            $res = curl('POST', $this->auth_url, json_encode([ 'refresh_token' => $_POST['refresh_token'] ]), ["content-type"=>"application/json; charset=utf-8"]);
R
v3  
root 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617
            //return output($res['body']);
            if ($res['stat']!=200) {
                return message($res['body'], $res['stat'], $res['stat']);
            }
            //var_dump($res['body']);
            $result = json_decode($res['body'], true);

            $tmp = null;
            foreach ($EnvConfigs as $env => $v) if (isInnerEnv($env)) $tmp[$env] = '';

            $tmp['refresh_token'] = $result['refresh_token'];
            $tmp['default_drive_id'] = $result['default_drive_id'];
            $tmp['default_sbox_drive_id'] = $result['default_sbox_drive_id'];
618
            $tmp['token_expires'] = time()+3*24*60*60;
R
v3  
root 已提交
619 620 621
            $tmp['Driver'] = 'Aliyundrive';
            $tmp['disktag_add'] = $_POST['disktag_add'];
            $tmp['diskname'] = $_POST['diskname'];
622
            //error_log(json_encode($tmp));
R
v3  
root 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683

            $response = setConfigResponse( setConfig($tmp, $this->disktag) );
            if (api_error($response)) {
                $html = api_error_msg($response);
                $title = 'Error';
                return message($html, $title, 201);
            } else {
                savecache('access_token', $result['access_token'], $this->disktag, $result['expires_in'] - 60);
                $str .= '<meta http-equiv="refresh" content="5;URL=' . $url . '">
                <script>
                var expd = new Date();
                expd.setTime(expd.getTime()+1);
                var expires = "expires="+expd.toGMTString();
                document.cookie=\'disktag=; path=/; \'+expires;
                </script>';
                return message($str, getconstStr('WaitJumpIndex'), 201);
            }

            /*$api = $this->api_url . '/user/get';
            $header['authorization'] = 'Bearer ' . $this->access_token;
            return json_encode(curl('GET', $api, '', $header));*/
        }

        $html = '
<div>
    <form id="form1" action="" method="post" onsubmit="return notnull(this);">
        ' . getconstStr('DiskTag') . ': (' . getConfig('disktag') . ')
        <input type="text" name="disktag_add" placeholder="' . getconstStr('EnvironmentsDescription')['disktag'] . '" style="width:100%"><br>
        ' . getconstStr('DiskName') . ':
        <input type="text" name="diskname" placeholder="' . getconstStr('EnvironmentsDescription')['diskname'] . '" style="width:100%"><br>
        <br>
        <div>填入refresh_token:
            <input type="text" name="refresh_token" placeholder="' . getconstStr(' ') . '" style="width:100%"><br>
        </div>
        <br>

        <input type="submit" value="' . getconstStr('Submit') . '">
    </form>
</div>
    <script>
        function notnull(t)
        {
            if (t.disktag_add.value==\'\') {
                alert(\'' . getconstStr('DiskTag') . '\');
                return false;
            }
            envs = [' . $envs . '];
            if (envs.indexOf(t.disktag_add.value)>-1) {
                alert("Do not input ' . $envs . '");
                return false;
            }
            var reg = /^[a-zA-Z]([_a-zA-Z0-9]{1,20})$/;
            if (!reg.test(t.disktag_add.value)) {
                alert(\'' . getconstStr('TagFormatAlert') . '\');
                return false;
            }
            if (t.refresh_token.value==\'\') {
                    alert(\'Input refresh_token\');
                    return false;
            }
            
684 685 686 687 688
            document.getElementById("form1").action="?install0&disktag=" + t.disktag_add.value + "&AddDisk=Aliyundrive";
            //var expd = new Date();
            //expd.setTime(expd.getTime()+(2*60*60*1000));
            //var expires = "expires="+expd.toGMTString();
            //document.cookie=\'disktag=\'+t.disktag_add.value+\'; path=/; \'+expires;
R
v3  
root 已提交
689 690 691 692 693 694 695
            return true;
        }
    </script>';
        $title = 'Select Account Type';
        return message($html, $title, 201);
    }
    protected function get_access_token($refresh_token) {
R
root 已提交
696 697 698 699 700 701
        if (!$refresh_token) {
            $tmp['stat'] = 0;
            $tmp['body'] = 'No refresh_token';
            $this->error = $tmp;
            return false;
        }
R
v3  
root 已提交
702 703 704 705 706 707 708
        if (!($this->access_token = getcache('access_token', $this->disktag))) {
            $p=0;
            $tmp1['refresh_token'] = $refresh_token;
            while ($response['stat']==0&&$p<3) {
                $response = curl('POST', $this->auth_url, json_encode($tmp1), ["content-type"=>"application/json; charset=utf-8"]);
                $p++;
            }
R
root 已提交
709
            //error_log1(json_encode($response));
R
v3  
root 已提交
710 711
            if ($response['stat']==200) $ret = json_decode($response['body'], true);
            if (!isset($ret['access_token'])) {
Q
qkqpttgf 已提交
712
                error_log1('failed to get [' . $this->disktag . '] access_token. response: ' . $response['stat'] . $response['body']);
713 714 715 716
                //$response['body'] = json_encode(json_decode($response['body']), JSON_PRETTY_PRINT);
                $response['body'] .= 'failed to get [' . $this->disktag . '] access_token.';
                $this->error = $response;
                return false;
R
v3  
root 已提交
717 718
            }
            $tmp = $ret;
R
root 已提交
719 720
            $tmp['access_token'] = substr($tmp['access_token'], 0, 10) . '******';
            $tmp['refresh_token'] = substr($tmp['refresh_token'], 0, 10) . '******';
721
            error_log1('[' . $this->disktag . '] Get access token:' . json_encode($tmp, JSON_PRETTY_PRINT));
R
v3  
root 已提交
722 723
            $this->access_token = $ret['access_token'];
            savecache('access_token', $this->access_token, $this->disktag, $ret['expires_in'] - 300);
724
            if (time()>getConfig('token_expires', $this->disktag)) setConfig([ 'refresh_token' => $ret['refresh_token'], 'token_expires' => time()+3*24*60*60 ], $this->disktag);
R
root 已提交
725
            return true;
R
v3  
root 已提交
726
        }
Q
qkqpttgf 已提交
727
        return true;
R
v3  
root 已提交
728
    }
Q
qkqpttgf 已提交
729
}