自定远程服务端(未完成)

pull/18/head
HFO4 8 years ago
parent 0e0f7d5258
commit c28f08c210

@ -81,4 +81,11 @@ class Callback extends Controller{
$handllerObj -> s3Handler($callbackKey);
}
public function Remote(){
ob_end_clean();
header('Content-Type: application/json');
$handllerObj = new CallbackHandler(file_get_contents("php://input"));
$handllerObj -> remoteHandler(Request::instance()->header('Authorization'));
}
}

@ -20,6 +20,28 @@ class CallbackHandler extends Model{
$this->CallbackData = $data;
}
public function remoteHandler($header){
$jsonData = json_decode(base64_decode($this->CallbackData),true);
$CallbackSqlData = Db::name('callback')->where('callback_key',$jsonData['callbackkey'])->find();
$this->policyData = Db::name('policy')->where('id',$CallbackSqlData['pid'])->find();
if(!$this->IsRemoteCallback($header)){
$this->setError("Undelegated Request");
}
if($this->policyData == null){
$this->setError("CallbackKey Not Exist.");
}
if(!FileManage::sotrageCheck($CallbackSqlData["uid"],$jsonData["fsize"])){
$this->setError("空间容量不足",true);
}
$picInfo = $jsonData["picinfo"];
$addAction = FileManage::addFile($jsonData,$this->policyData,$CallbackSqlData["uid"],$picInfo);
if(!$addAction[0]){
$this->setError($addAction[1],true);
}
FileManage::storageCheckOut($CallbackSqlData["uid"],$jsonData["fsize"]);
$this->setSuccess($jsonData['fname']);
}
public function qiniuHandler($header){
$jsonData = json_decode($this->CallbackData,true);
$CallbackSqlData = Db::name('callback')->where('callback_key',$jsonData['callbackkey'])->find();
@ -172,6 +194,11 @@ class CallbackHandler extends Model{
}
}
private function IsRemoteCallback($header){
$signKey = hash_hmac("sha256",$this->CallbackData,$this->policyData["sk"]);
return ($signKey == $header);
}
public function IsOssCallback($auth,$pubKey){
if (empty($auth) || empty($pubKey)){
header("http/1.1 403 Forbidden");

@ -338,6 +338,10 @@ class FileManage extends Model{
$Redirect = $this->s3Preview();
return $Redirect;
break;
case 'remote':
$Redirect = $this->remotePreview();
return $Redirect;
break;
default:
# code...
break;
@ -384,6 +388,9 @@ class FileManage extends Model{
case 's3':
return $DownloadHandler = $this->s3Download();
break;
case 'remote':
return $DownloadHandler = $this->remoteDownload();
break;
default:
# code...
break;
@ -473,6 +480,8 @@ class FileManage extends Model{
self::upyunDelete($value,$uniquePolicy["upyunPolicyData"][$key][0]);
}else if(in_array($key,$uniquePolicy["s3List"])){
self::s3Delete($value,$uniquePolicy["s3PolicyData"][$key][0]);
}else if(in_array($key,$uniquePolicy["remoteList"])){
self::remoteDelete($value,$uniquePolicy["remotePolicyData"][$key][0]);
}
}
return ["result"=>["success"=>true,"error"=>null]];
@ -580,6 +589,12 @@ class FileManage extends Model{
self::deleteFileRecord(array_column($fileList, 'id'),array_sum(array_column($fileList, 'size')),$fileList[0]["upload_user"]);
}
static function remoteDelete($fileList,$policyData){
$remoteObj = new Remote($policyData);
$remoteObj->remove(array_column($fileList, 'pre_name'));
self::deleteFileRecord(array_column($fileList, 'id'),array_sum(array_column($fileList, 'size')),$fileList[0]["upload_user"]);
}
static function deleteFileRecord($id,$size,$uid){
Db::name('files')->where([
'id' => ["in",$id],
@ -673,6 +688,11 @@ class FileManage extends Model{
return [1,\S3\S3::aws_s3_link($this->policyData["ak"], $this->policyData["sk"],$this->policyData["bucketname"],"/".$this->fileData["pre_name"],3600,$this->policyData["op_name"])];
}
public function remotePreview(){
$remote = new Remote($this->policyData);
return [1,$remote->preview($this->fileData["pre_name"])];
}
public function upyunPreview($base=null,$name=null){
if(!$this->policyData['bucket_private']){
$fileUrl = $this->policyData["url"].$this->fileData["pre_name"]."?auth=0";
@ -753,6 +773,11 @@ class FileManage extends Model{
return [1,\S3\S3::aws_s3_link($this->policyData["ak"], $this->policyData["sk"],$this->policyData["bucketname"],"/".$this->fileData["pre_name"],3600,$this->policyData["op_name"],array(),false)];
}
private function remoteDownload(){
$remote = new Remote($this->policyData);
return [1,$remote->download($this->fileData["pre_name"],$this->fileData["orign_name"])];
}
public function ossDownload(){
if(!$this->policyData['bucket_private']){
$fileUrl = $this->policyData["url"].$this->fileData["pre_name"]."?response-content-disposition=".urlencode('attachment; filename='.$this->fileData["orign_name"]);
@ -1145,6 +1170,8 @@ class FileManage extends Model{
$upyunPolicyData = [];
$s3List = [];
$s3PolicyData = [];
$remoteList = [];
$remotePolicyData = [];
foreach ($data as $key => $value) {
if(!in_array($value['policy_id'],$tempList)){
array_push($tempList,$value['policy_id']);
@ -1185,6 +1212,13 @@ class FileManage extends Model{
}
array_push($s3PolicyData[$value['policy_id']],$policyTempData);
break;
case 'remote':
array_push($remoteList,$value['policy_id']);
if(empty($remotePolicyData[$value['policy_id']])){
$remotePolicyData[$value['policy_id']] = [];
}
array_push($remotePolicyData[$value['policy_id']],$policyTempData);
break;
default:
# code...
break;
@ -1203,6 +1237,8 @@ class FileManage extends Model{
'upyunPolicyData' => $upyunPolicyData,
's3List' => $s3List,
's3PolicyData' => $s3PolicyData,
'remoteList' => $remoteList,
'remotePolicyData' => $remotePolicyData,
);
return $returenValue;
}

@ -0,0 +1,59 @@
<?php
namespace app\index\model;
use think\Model;
use think\Db;
use \app\index\model\Option;
class Remote extends Model{
public $sk;
private $policy;
private $serverOutput;
private $httpCode;
public function __construct($policy){
$this->policy = $policy;
}
public function remove($fileList){
$signKey = $this->sign($fileList,"DELETE");
$this->send("manager.php",$signKey,"DELETE",base64_encode(json_encode($fileList)));
}
public function preview($fname){
return $this->signUrl($this->policy["url"]."object.php?action=preview&name=".urlencode($fname)."&expires=".(time()+(int)Option::getValue("timeout")));
}
public function download($fname,$attnanme){
return $this->signUrl($this->policy["url"]."object.php?action=download&name=".urlencode($fname)."&attaname=".urlencode($attnanme)."&expires=".(time()+(int)Option::getValue("timeout")));
}
public function signUrl($url){
$signKey = hash_hmac("sha256",$url,"GET".$this->policy["sk"]);
return $url."&auth=".$signKey;
}
public function send($target,$auth,$action,$object){
$session = curl_init($this->policy["server"].$target);
$postData = array(
"action" => $action,
"auth" => $auth,
"object" => $object,
);
curl_setopt($session, CURLOPT_POST, 1);
curl_setopt($session, CURLOPT_POSTFIELDS, $postData);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($session, CURLOPT_SSL_VERIFYHOST, false);
$this->serverOutput = curl_exec($session);
$this->httpCode = curl_getinfo($session,CURLINFO_HTTP_CODE);
echo $this->serverOutput;
}
public function sign($content,$method = null){
return hash_hmac("sha256",base64_encode(json_encode($content)),$method.$this->policy["sk"]);
}
}
?>

@ -228,6 +228,9 @@ class UploadHandler extends Model{
case 's3':
return $this->getS3Token();
break;
case 'remote':
return $this->getRemoteToken();
break;
default:
# code...
break;
@ -295,6 +298,35 @@ class UploadHandler extends Model{
return $token;
}
private function getRemoteToken(){
$callbackKey = $this->getRandomKey();
$sqlData = [
'callback_key' => $callbackKey,
'pid' => $this->policyId,
'uid' => $this->userId
];
Db::name('callback')->insert($sqlData);
$policy = array(
'callbackUrl' =>Option::getValue("siteURL").'Callback/Remote',
'callbackKey' => $callbackKey,
'callbackBodyType' => 'application/json',
'fsizeLimit' => (int)$this->policyContent['max_size'],
'uid' => $this->userId,
);
$dirName = $this->getObjName($this->policyContent['dirrule']);
if($this->policyContent["autoname"]){
$policy = array_merge($policy,array("saveKey" => $dirName.(empty($dirName)?"":"/").$this->getObjName($this->policyContent['namerule'])));
}else{
$policy = array_merge($policy,array("saveKey" => $dirName.(empty($dirName)?"":"/")."$(fname)"));
}
if(!empty($this->policyContent['mimetype'])){
$policy = array_merge($policy,array("mimeLimit" => $this->policyContent['mimetype']));
}
$signingKey = hash_hmac("sha256",json_encode($policy),"UPLOAD".$this->policyContent['sk']);
$token = $signingKey. ":" .base64_encode(json_encode($policy));
return $token;
}
static function upyunSign($key, $secret, $method, $uri, $date, $policy=null, $md5=null){
$elems = array();
foreach (array($method, $uri, $date, $policy, $md5) as $v){

@ -1 +1,2 @@
database.php
*
!.gitignore

@ -183,7 +183,7 @@ function QiniuJsSDK() {
"https://up.qbox.me"
]
};
}else if(uploadConfig.saveType == "local" || uploadConfig.saveType == "oss" ||uploadConfig.saveType == "upyun"||uploadConfig.saveType == "s3"){
}else if(uploadConfig.saveType == "local" || uploadConfig.saveType == "oss" ||uploadConfig.saveType == "upyun"||uploadConfig.saveType == "s3"|| uploadConfig.saveType == "remote"){
qiniuUploadUrl = uploadConfig.upUrl;
var qiniuUploadUrls = [uploadConfig.upUrl,];
var qiniuUpHosts = {
@ -618,7 +618,7 @@ function QiniuJsSDK() {
};
var getPutPolicy = function (uptoken) {
if(uploadConfig.saveType =="oss" || uploadConfig.saveType =="upyun"||uploadConfig.saveType =="s3"){
if(uploadConfig.saveType =="oss" || uploadConfig.saveType =="upyun"||uploadConfig.saveType =="s3"||uploadConfig.saveType =="remote"){
return "oss";
}else{
var segments = uptoken.split(":");
@ -692,6 +692,9 @@ function QiniuJsSDK() {
};
var getUptoken = function(file) {
if(uploadConfig.saveType == "remote"){
return that.token;
}
if (!that.token || (op.uptoken_url && that.tokenInfo.isExpired())) {
return getNewUpToken(file);
} else {
@ -742,6 +745,9 @@ function QiniuJsSDK() {
var putPolicy = that.token;
that.token = res.token;
that.policy = res.policy;
}else if(uploadConfig.saveType == "remote"){
var putPolicy = that.token;
that.policy = res.uptoken;
}else{
var segments = that.token.split(":");
var putPolicy = that.parseJSON(that.URLSafeBase64Decode(segments[2]));
@ -992,6 +998,12 @@ function QiniuJsSDK() {
multipart_params_obj = {
'path': file.path
};
}else if(uploadConfig.saveType == "remote"){
multipart_params_obj = {
'path': file.path,
"token" :that.policy,
"MAX_FILE_SIZE":4194304,
};
}else if(uploadConfig.saveType == "oss"){
multipart_params_obj = {
'policy': that.token,
@ -1134,6 +1146,18 @@ function QiniuJsSDK() {
}
// TODO: to support bput
// http://developer.qiniu.com/docs/v6/api/reference/up/bput.html
if(uploadConfig.saveType == "remote"){
up.setOption({
'url': qiniuUploadUrl + 'chunk.php',
'multipart': false,
'chunk_size': chunk_size,
'required_features': "chunks",
'headers': {
'Authorization': getUptoken(file)
},
'multipart_params': multipart_params_obj
});
}else{
up.setOption({
'url': qiniuUploadUrl + '/mkblk/' + blockSize,
'multipart': false,
@ -1145,6 +1169,7 @@ function QiniuJsSDK() {
'multipart_params': multipart_params_obj
});
}
}
} else {
logger.debug("directUpload because uploader.runtime !== 'html5' || uploader.runtime !== 'flash' || !chunk_size");
// direct upload if runtime is not html5
@ -1186,13 +1211,26 @@ function QiniuJsSDK() {
up.setOption({
'url': qiniuUploadUrl + '/mkblk/' + leftSize
});
if(uploadConfig.saveType == "remote"){
up.setOption({
'url': qiniuUploadUrl + 'chunk.php'
});
}
logger.debug("up.setOption url: ", qiniuUploadUrl + '/mkblk/' + leftSize);
}
if(uploadConfig.saveType == "remote"){
up.setOption({
'headers': {
'Authorization': getUptoken(file)
}
});
}else{
up.setOption({
'headers': {
'Authorization': 'UpToken ' + getUptoken(file)
}
});
}
localStorage.setItem(file.name, that.stringifyJSON({
ctx: ctx,
percent: file.percent,
@ -1423,7 +1461,16 @@ function QiniuJsSDK() {
}
var fname = '/fname/' + that.URLSafeBase64Encode(file.name);
if(uploadConfig.saveType=="remote"){
if (!op.save_key) {
key = getFileKey(up, file, that.key_handler);
key = key ? that.URLSafeBase64Encode(key) : '';
}
fname = '' + that.URLSafeBase64Encode(file.name);
op.x_vars= {
'path': file.path,
};
}
logger.debug("op.x_vars: ", op.x_vars);
if(uploadConfig.saveType == "qiniu"){
op.x_vars= {
@ -1453,8 +1500,11 @@ function QiniuJsSDK() {
}
local_path = '/path/'+that.URLSafeBase64Encode(pathTmp);
}
if(uploadConfig.saveType == "remote"){
var url = qiniuUploadUrl + 'mkfile.php?size=' + file.size +"&key="+ key+"&fname="+ fname +"&path="+local_path;
}else{
var url = qiniuUploadUrl + '/mkfile/' + file.size + key + fname + x_vars_url+local_path;
}
var ie = that.detectIEVersion();
var ajax;
if (ie && ie <= 9) {
@ -1465,7 +1515,11 @@ function QiniuJsSDK() {
}
ajax.open('POST', url, true);
ajax.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
if(uploadConfig.saveType == "remote"){
ajax.setRequestHeader('Authorization',that.token);
}else{
ajax.setRequestHeader('Authorization', 'UpToken ' + that.token);
}
var onreadystatechange = function(){
logger.debug("ajax.readyState: ", ajax.readyState);
if (ajax.readyState === 4) {

Loading…
Cancel
Save