add WaitFunction in operate

pull/397/merge
root 2021-08-17 11:51:17 +00:00
parent 729e1e1176
commit f2ee21b683
13 changed files with 340 additions and 138 deletions

View File

@ -198,6 +198,13 @@ function main($path)
$url = path_format($_SERVER['PHP_SELF'] . '/'); $url = path_format($_SERVER['PHP_SELF'] . '/');
return output('<script>alert(\''.getconstStr('SetSecretsFirst').'\');</script>', 302, [ 'Location' => $url ]); return output('<script>alert(\''.getconstStr('SetSecretsFirst').'\');</script>', 302, [ 'Location' => $url ]);
} }
if (isset($_GET['WaitFunction'])) {
$response = WaitFunction($_GET['WaitFunction']);
//var_dump($response);
if ($response===true) return output("ok", 200);
elseif ($response===false) return output("", 206);
else return $response;
}
$_SERVER['sitename'] = getConfig('sitename'); $_SERVER['sitename'] = getConfig('sitename');
if (empty($_SERVER['sitename'])) $_SERVER['sitename'] = getconstStr('defaultSitename'); if (empty($_SERVER['sitename'])) $_SERVER['sitename'] = getconstStr('defaultSitename');
@ -295,6 +302,7 @@ function main($path)
return $drive->bigfileupload($path1); return $drive->bigfileupload($path1);
} }
} }
if ($_SERVER['admin']) { if ($_SERVER['admin']) {
$tmp = adminoperate($path); $tmp = adminoperate($path);
if ($tmp['statusCode'] > 0) { if ($tmp['statusCode'] > 0) {
@ -800,9 +808,9 @@ function get_timezone($timezone = '8')
return $timezones[$timezone]; return $timezones[$timezone];
} }
function message($message, $title = 'Message', $statusCode = 200) function message($message, $title = 'Message', $statusCode = 200, $wainstat = 0)
{ {
return output(' $html = '
<html lang="' . $_SERVER['language'] . '"> <html lang="' . $_SERVER['language'] . '">
<html> <html>
<meta charset=utf-8> <meta charset=utf-8>
@ -810,14 +818,61 @@ function message($message, $title = 'Message', $statusCode = 200)
<body> <body>
<h1>' . $title . '</h1> <h1>' . $title . '</h1>
<a href="' . $_SERVER['base_path'] . '">' . getconstStr('Back') . getconstStr('Home') . '</a> <a href="' . $_SERVER['base_path'] . '">' . getconstStr('Back') . getconstStr('Home') . '</a>
<p> <div id="dis" style="display: none;">
' . $message . ' ' . $message . '
</p> </div>';
if ($wainstat) {
$html .= '
<div id="err"></div>
<script>
var dis = document.getElementById("dis");
var errordiv = document.getElementById("err");
//var deployTime = new Date().getTime();
dis.style.display = "none";
var x = "";
var min = 0;
function getStatus() {
x += ".";
min++;
var xhr = new XMLHttpRequest();
var url = "?WaitFunction" + (status!=""?"=" + status:"");
xhr.open("GET", url);
//xhr.setRequestHeader("Authorization", "Bearer ");
xhr.onload = function(e) {
if (xhr.status==200) {
//var deployStat = JSON.parse(xhr.responseText).readyState;
if (xhr.responseText=="ok") {
errordiv.innerHTML = "";
dis.style.display = "";
} else {
errordiv.innerHTML = "ERROR<br>" + xhr.responseText;
//setTimeout(function() { getStatus() }, 1000);
}
} else if (xhr.status==206) {
errordiv.innerHTML = min + "<br>' . getconstStr('Wait') . '" + x;
setTimeout(function() { getStatus() }, 1000);
} else {
errordiv.innerHTML = "ERROR<br>" + xhr.status + "<br>" + xhr.responseText;
console.log(xhr.status);
console.log(xhr.responseText);
}
}
xhr.send(null);
}
getStatus();
//setTimeout(function() { getStatus() }, 3000);
</script>';
} else {
$html .= '
<script>document.getElementById("dis").style.display = "";</script>';
}
$html .= '
</body> </body>
</html> </html>
', $statusCode); ';
return output($html, $statusCode);
} }
function needUpdate() function needUpdate()
@ -1109,12 +1164,13 @@ function EnvOpt($needUpdate = 0)
if (api_error($response)) { if (api_error($response)) {
$html = api_error_msg($response); $html = api_error_msg($response);
$title = 'Error'; $title = 'Error';
return message($html, $title, 400);
} else { } else {
//WaitSCFStat(); //WaitSCFStat();
$html .= getconstStr('UpdateSuccess') . '<br><a href="">' . getconstStr('Back') . '</a>'; $html .= getconstStr('UpdateSuccess') . '<br><a href="">' . getconstStr('Back') . '</a><script>var status = "' . $response['status'] . '";</script>';
$title = getconstStr('Setup'); $title = getconstStr('Setup');
return message($html, $title, 202, 1);
} }
return message($html, $title);
} }
if (isset($_POST['submit1'])) { if (isset($_POST['submit1'])) {
$_SERVER['disk_oprating'] = ''; $_SERVER['disk_oprating'] = '';
@ -1127,11 +1183,11 @@ function EnvOpt($needUpdate = 0)
$f = substr($v, 0, 1); $f = substr($v, 0, 1);
if (strlen($v)==1) $v .= '_'; if (strlen($v)==1) $v .= '_';
if (isCommonEnv($v)) { if (isCommonEnv($v)) {
return message('Do not input ' . $envs . '<br><a href="">' . getconstStr('Back') . '</a>', 'Error', 201); return message('Do not input ' . $envs . '<br><a href="">' . getconstStr('Back') . '</a>', 'Error', 400);
} elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) { } elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) {
return message('<a href="">' . getconstStr('Back') . '</a>', 'Please start with letters', 201); return message('<a href="">' . getconstStr('Back') . '</a>', 'Please start with letters', 400);
} elseif (getConfig($v)) { } elseif (getConfig($v)) {
return message('<a href="">' . getconstStr('Back') . '</a>', 'Same tag', 201); return message('<a href="">' . getconstStr('Back') . '</a>', 'Same tag', 400);
} else { } else {
$tmp[$k] = $v; $tmp[$k] = $v;
} }
@ -1139,7 +1195,7 @@ function EnvOpt($needUpdate = 0)
if ($k=='disktag_sort') { if ($k=='disktag_sort') {
$td = implode('|', json_decode($v)); $td = implode('|', json_decode($v));
if (strlen($td)==strlen(getConfig('disktag'))) $tmp['disktag'] = $td; if (strlen($td)==strlen(getConfig('disktag'))) $tmp['disktag'] = $td;
else return message('Something wrong.'); else return message('Something wrong.', 'ERROR', 400);
} }
if ($k == 'disk') $_SERVER['disk_oprating'] = $v; if ($k == 'disk') $_SERVER['disk_oprating'] = $v;
} }
@ -1156,12 +1212,16 @@ function EnvOpt($needUpdate = 0)
if (api_error($response)) { if (api_error($response)) {
$html = api_error_msg($response); $html = api_error_msg($response);
$title = 'Error'; $title = 'Error';
return message($html, $title, 409);
} else { } else {
$html .= getconstStr('Success') . '!<br> $html .= getconstStr('Success') . '!<br>
<a href="">' . getconstStr('Back') . '</a>'; <a href="">' . getconstStr('Back') . '</a>
<script>
var status = "' . $response['status'] . '";
</script>';
$title = getconstStr('Setup'); $title = getconstStr('Setup');
return message($html, $title, 200, 1);
} }
return message($html, $title);
} }
if (isset($_POST['config_b'])) { if (isset($_POST['config_b'])) {
if (!$_POST['pass']) return output("{\"Error\": \"No admin pass\"}", 403); if (!$_POST['pass']) return output("{\"Error\": \"No admin pass\"}", 403);
@ -1233,7 +1293,7 @@ function EnvOpt($needUpdate = 0)
if (api_error($response)) { if (api_error($response)) {
return message(api_error_msg($response) . "<a href=\"\">" . getconstStr('Back') . "</a>", "Error", 403); return message(api_error_msg($response) . "<a href=\"\">" . getconstStr('Back') . "</a>", "Error", 403);
} else { } else {
return message("Success<a href=\"\">" . getconstStr('Back') . "</a>", "Success", 200); return message("Success<a href=\"\">" . getconstStr('Back') . "</a><script>var status = \"" . $response['status'] . "\";</script>", "Success", 200, 1);
} }
} else { } else {
return message("Old pass error<a href=\"\">" . getconstStr('Back') . "</a>", "Error", 403); return message("Old pass error<a href=\"\">" . getconstStr('Back') . "</a>", "Error", 403);

View File

@ -1072,11 +1072,11 @@ $constStr = [
'ar-sa' => 'أكد بي إتش بي قابل للكتابة', 'ar-sa' => 'أكد بي إتش بي قابل للكتابة',
], ],
'MakesuerRewriteOn' => [ 'MakesuerRewriteOn' => [
'en-us' => 'Plase make sure the RewriteEngine is On.', 'en-us' => 'Plase make sure the RewriteEngine is On',
'zh-cn' => '确认重写(伪静态)功能启用', 'zh-cn' => '确认重写(伪静态)功能启用',
'zh-tw' => '確認重寫(偽靜態)功能啟用', 'zh-tw' => '確認重寫(偽靜態)功能啟用',
'ja' => '書き換え(擬似静的)機能が有効になっていることを確認します', 'ja' => '書き換え(擬似静的)機能が有効になっていることを確認します',
'ko-kr' => '다시 쓰기 (의사 정적) 기능이 활성화되어 있는지 확인하십시오.', 'ko-kr' => '다시 쓰기 (의사 정적) 기능이 활성화되어 있는지 확인하십시오',
'fa' => 'لطفاً مطمئن شوید که RewriteEngine روشن است.', 'fa' => 'لطفاً مطمئن شوید که RewriteEngine روشن است.',
'ar-sa' => 'يؤكد أن الكتابة يمكن أن تكون وظيفة شبه استاتي', 'ar-sa' => 'يؤكد أن الكتابة يمكن أن تكون وظيفة شبه استاتي',
], ],

View File

@ -629,8 +629,19 @@ class Aliyundrive {
$title = 'Error'; $title = 'Error';
return message($html, $title, 201); return message($html, $title, 201);
} else { } else {
$str .= '<meta http-equiv="refresh" content="5;URL=' . $url . '">'; $str .= '
return message($str, getconstStr('WaitJumpIndex'), 201); <script>
var status = "' . $response['status'] . '";
var uploadList = setInterval(function(){
if (document.getElementById("dis").style.display=="none") {
console.log(min++);
} else {
clearInterval(uploadList);
location.href = "' . $url . '";
}
}, 1000);
</script>';
return message($str, getconstStr('WaitJumpIndex'), 201, 1);
} }
} }
if (isset($_GET['SelectDrive'])) { if (isset($_GET['SelectDrive'])) {
@ -691,17 +702,18 @@ class Aliyundrive {
</form> </form>
</div> </div>
<script> <script>
function notnull(t) var status = "' . $response['status'] . '";
{ function notnull(t)
if (t.driveId.value==\'\') { {
alert(\'Select a Disk\'); if (t.driveId.value==\'\') {
return false; alert(\'Select a Disk\');
} return false;
return true;
} }
</script> return true;
}
</script>
'; ';
return message($html, $title, 201); return message($html, $title, 201, 1);
} }
if (isset($_GET['install0']) && $_POST['disktag_add']!='') { if (isset($_GET['install0']) && $_POST['disktag_add']!='') {
$_POST['disktag_add'] = preg_replace('/[^0-9a-zA-Z|_]/i', '', $_POST['disktag_add']); $_POST['disktag_add'] = preg_replace('/[^0-9a-zA-Z|_]/i', '', $_POST['disktag_add']);
@ -737,7 +749,7 @@ class Aliyundrive {
if (api_error($response)) { if (api_error($response)) {
$html = api_error_msg($response); $html = api_error_msg($response);
$title = 'Error'; $title = 'Error';
return message($html, $title, 201); return message($html, $title, 400);
} else { } else {
$title = 'Refresh token'; $title = 'Refresh token';
$html = ' $html = '
@ -756,9 +768,10 @@ class Aliyundrive {
} }
return true; return true;
} }
var status = "' . $response['status'] . '";
</script> </script>
'; ';
return message($html, $title, 201); return message($html, $title, 201, 1);
} }
} }

View File

@ -504,14 +504,23 @@ class Onedrive {
$title = 'Error'; $title = 'Error';
return message($html, $title, 201); return message($html, $title, 201);
} else { } else {
$str .= '<meta http-equiv="refresh" content="5;URL=' . $url . '"> $html .= '<script>
<script>
var expd = new Date(); var expd = new Date();
expd.setTime(expd.getTime()+1); expd.setTime(expd.getTime()+1);
var expires = "expires="+expd.toGMTString(); var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=; path=/; \'+expires; document.cookie=\'disktag=; path=/; \'+expires;
var i = 0;
var status = "' . $response['status'] . '";
var uploadList = setInterval(function(){
if (document.getElementById("dis").style.display=="none") {
console.log(i++);
} else {
clearInterval(uploadList);
location.href = "' . $url . '";
}
}, 1000);
</script>'; </script>';
return message($str, getconstStr('WaitJumpIndex'), 201); return message($html, getconstStr('WaitJumpIndex'), 201, 1);
} }
} }
@ -607,9 +616,19 @@ class Onedrive {
return message($html, $title, 201); return message($html, $title, 201);
} else { } else {
savecache('access_token', $ret['access_token'], $this->disktag, $ret['expires_in'] - 60); savecache('access_token', $ret['access_token'], $this->disktag, $ret['expires_in'] - 60);
$str .= ' $html .= '<script>
<meta http-equiv="refresh" content="3;URL=' . $url . '?AddDisk=' . get_class($this) . '&disktag=' . $_GET['disktag'] . '&SelectDrive">'; var i = 0;
return message($str, getconstStr('Wait') . ' 3s', 201); var status = "' . $response['status'] . '";
var uploadList = setInterval(function(){
if (document.getElementById("dis").style.display=="none") {
console.log(i++);
} else {
clearInterval(uploadList);
location.href = "' . $url . '?AddDisk=' . get_class($this) . '&disktag=' . $_GET['disktag'] . '&SelectDrive";
}
}, 1000);
</script>';
return message($html, getconstStr('Wait') . ' 3s', 201, 1);
} }
} }
return message('<pre>' . json_encode(json_decode($tmp['body']), JSON_PRETTY_PRINT) . '</pre>', $tmp['stat']); return message('<pre>' . json_encode(json_decode($tmp['body']), JSON_PRETTY_PRINT) . '</pre>', $tmp['stat']);
@ -639,7 +658,7 @@ class Onedrive {
$f = substr($_POST['disktag_add'], 0, 1); $f = substr($_POST['disktag_add'], 0, 1);
if (strlen($_POST['disktag_add'])==1) $_POST['disktag_add'] .= '_'; if (strlen($_POST['disktag_add'])==1) $_POST['disktag_add'] .= '_';
if (isCommonEnv($_POST['disktag_add'])) { if (isCommonEnv($_POST['disktag_add'])) {
return message('Do not input ' . $envs . '<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>', 'Error', 201); return message('Do not input ' . $envs . '<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>', 'Error', 400);
} elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) { } 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> return message('Please start with letters<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>
<script> <script>
@ -647,7 +666,7 @@ class Onedrive {
expd.setTime(expd.getTime()+1); expd.setTime(expd.getTime()+1);
var expires = "expires="+expd.toGMTString(); var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=; path=/; \'+expires; document.cookie=\'disktag=; path=/; \'+expires;
</script>', 'Error', 201); </script>', 'Error', 400);
} }
$tmp = null; $tmp = null;
@ -673,12 +692,26 @@ class Onedrive {
if (api_error($response)) { if (api_error($response)) {
$html = api_error_msg($response); $html = api_error_msg($response);
$title = 'Error'; $title = 'Error';
return message($html, $title, 400);
} else { } else {
$title = getconstStr('MayinEnv'); $title = getconstStr('MayinEnv');
$html = getconstStr('Wait') . ' 3s<meta http-equiv="refresh" content="3;URL=' . $url . '?install1&disktag=' . $_GET['disktag'] . '&AddDisk=' . $_POST['Drive_ver'] . '">'; $html = getconstStr('Wait');
if ($_POST['Drive_ver']=='Sharelink') $html = getconstStr('Wait') . ' 3s<meta http-equiv="refresh" content="3;URL=' . $url . '">'; if ($_POST['Drive_ver']!='Sharelink') $url .= '?install1&disktag=' . $_GET['disktag'] . '&AddDisk=' . $_POST['Drive_ver'];
$html .= '<script>
var i = 0;
var status = "' . $response['status'] . '";
var uploadList = setInterval(function(){
if (document.getElementById("dis").style.display=="none") {
console.log(i++);
} else {
clearInterval(uploadList);
location.href = "' . $url . '";
}
}, 1000);
</script>';
return message($html, $title, 201, 1);
} }
return message($html, $title, 201);
} }
} }

View File

@ -497,3 +497,7 @@ function myErrorHandler($errno, $errstr, $errfile, $errline) {
} }
return true; return true;
} }
function WaitFunction() {
return true;
}

View File

@ -431,3 +431,7 @@ function addFileToZip($zip, $rootpath, $path = '')
} }
@closedir($path); @closedir($path);
} }
function WaitFunction() {
return true;
}

View File

@ -1,4 +1,5 @@
<?php <?php
// https://devcenter.heroku.com/articles/platform-api-reference#build-create
function getpath() function getpath()
{ {
@ -339,3 +340,7 @@ function setConfigResponse($response)
{ {
return json_decode( $response['body'], true ); return json_decode( $response['body'], true );
} }
function WaitFunction() {
return true;
}

View File

@ -487,3 +487,7 @@ function addFileToZip($zip, $rootpath, $path = '')
} }
@closedir($path); @closedir($path);
} }
function WaitFunction() {
return true;
}

View File

@ -868,3 +868,7 @@ class Signer
return $curl; return $curl;
} }
} }
function WaitFunction() {
return true;
}

View File

@ -246,7 +246,7 @@ function install()
document.getElementById("submitbtn").disabled = false; document.getElementById("submitbtn").disabled = false;
document.getElementById("formdiv").style.display = ""; document.getElementById("formdiv").style.display = "";
} else { } else {
alert("Url: " + url + "\nExpect http code 201, but received " + xhr4.status); alert("' . getconstStr('MakesuerRewriteOn') . '?\nfalse\n\nUrl: " + url + "\nExpect http code 201, but received " + xhr4.status);
} }
} }
} }
@ -385,3 +385,7 @@ function moveFolder($from, $to, $slash)
rmdir($from); rmdir($from);
return json_encode( [ 'response' => 'success' ] ); return json_encode( [ 'response' => 'success' ] );
} }
function WaitFunction() {
return true;
}

View File

@ -454,6 +454,14 @@ function setConfigResponse($response)
return json_decode( $response, true )['Response']; return json_decode( $response, true )['Response'];
} }
function WaitFunction() {
//$trynum = 0;
//while( json_decode(getfunctioninfo($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')),true)['Response']['Status']!='Active' ) echo '
//'.++$trynum;
if ( json_decode(getfunctioninfo($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')),true)['Response']['Status']=='Active' ) return true;
else return false;
}
function updateProgram($function_name, $Region, $Namespace, $SecretId, $SecretKey, $source) function updateProgram($function_name, $Region, $Namespace, $SecretId, $SecretKey, $source)
{ {
$secretId = $SecretId; $secretId = $SecretId;

View File

@ -645,3 +645,8 @@ function addFileToZip($zip, $rootpath, $path = '')
} }
@closedir($path); @closedir($path);
} }
function WaitFunction() {
if ( json_decode(getfunctioninfo($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')),true)['Response']['Status']=='Active' ) return true;
else return false;
}

View File

@ -75,7 +75,7 @@ function getConfig($str, $disktag = '')
if (isset($env[$str])) { if (isset($env[$str])) {
if (isBase64Env($str)) return base64y_decode($env[$str]); if (isBase64Env($str)) return base64y_decode($env[$str]);
else return $env[$str]; else return $env[$str];
} }
} else { } else {
if (isBase64Env($str)) return base64y_decode(getenv($str)); if (isBase64Env($str)) return base64y_decode(getenv($str));
else return getenv($str); else return getenv($str);
@ -112,7 +112,9 @@ function setConfig($arr, $disktag = '')
$operatedisk = 1; $operatedisk = 1;
} elseif ($k=='disktag_copy') { } elseif ($k=='disktag_copy') {
$newtag = $v . '_' . date("Ymd_His"); $newtag = $v . '_' . date("Ymd_His");
$tmp[$newtag] = getConfig($v); $tagvalue = getConfig($v);
if (is_array($tagvalue)) $tmp[$newtag] = json_encode($tagvalue);
else $tmp[$newtag] = $tagvalue;
array_push($disktags, $newtag); array_push($disktags, $newtag);
$operatedisk = 1; $operatedisk = 1;
} elseif ($k=='disktag_rename' || $k=='disktag_newname') { } elseif ($k=='disktag_rename' || $k=='disktag_newname') {
@ -134,7 +136,9 @@ function setConfig($arr, $disktag = '')
else array_push($tags, $tag); else array_push($tags, $tag);
} }
$tmp['disktag'] = implode('|', $tags); $tmp['disktag'] = implode('|', $tags);
$tmp[$arr['disktag_newname']] = getConfig($arr['disktag_rename']); $tagvalue = getConfig($arr['disktag_rename']);
if (is_array($tagvalue)) $tmp[$arr['disktag_newname']] = json_encode($tagvalue);
else $tmp[$arr['disktag_newname']] = $tagvalue;
$tmp[$arr['disktag_rename']] = null; $tmp[$arr['disktag_rename']] = null;
} else { } else {
$disktags = array_unique($disktags); $disktags = array_unique($disktags);
@ -157,49 +161,39 @@ function install()
$tmp['admin'] = $_POST['admin']; $tmp['admin'] = $_POST['admin'];
//$tmp['language'] = $_POST['language']; //$tmp['language'] = $_POST['language'];
$tmp['timezone'] = $_COOKIE['timezone']; $tmp['timezone'] = $_COOKIE['timezone'];
$APIKey = getConfig('APIKey'); $APIKey = $_POST['APIKey'];
if ($APIKey=='') { //if ($APIKey=='') {
$APIKey = $_POST['APIKey']; // $APIKey = getConfig('APIKey');
$tmp['APIKey'] = $APIKey; //}
} $tmp['APIKey'] = $APIKey;
$projectPath = splitlast(__DIR__, "/")[0];
//$html .= file_get_contents($projectPath . "/.data/config.php") . "<br>";GET /v5/now/deployments /v8/projects/:id/env
$token = $tmp['APIKey'];
$header["Authorization"] = "Bearer " . $token;
$header["Content-Type"] = "application/json";
$aliases = json_decode(curl("GET", "https://api.vercel.com/v3/now/aliases", "", $header)['body'], true);
$host = splitfirst($_SERVER["host"], "//")[1];
foreach ($aliases["aliases"] as $key => $aliase) {
if ($host==$aliase["alias"]) $projectId = $aliase["projectId"];
}
//$envs = json_decode(curl("GET", "https://api.vercel.com/v8/projects/" . $projectId . "/env", "", $header)['body'], true);
$token = $APIKey;
$header["Authorization"] = "Bearer " . $token;
$header["Content-Type"] = "application/json";
$aliases = json_decode(curl("GET", "https://api.vercel.com/v3/now/aliases", "", $header)['body'], true);
$host = splitfirst($_SERVER["host"], "//")[1];
foreach ($aliases["aliases"] as $key => $aliase) {
if ($host==$aliase["alias"]) $projectId = $aliase["projectId"];
}
$tmp['HerokuappId'] = $projectId; $tmp['HerokuappId'] = $projectId;
$response = json_decode(setVercelConfig($tmp, $projectId, $APIKey)['body'], true);
$response = json_decode(setVercelConfig($tmp, $projectId, $APIKey), true);
if (api_error($response)) { if (api_error($response)) {
$html = api_error_msg($response); $html = api_error_msg($response);
$title = 'Error'; $title = 'Error';
return message($html, $title, 400);
} else { } else {
return output('<span id="displayBox"></span> /*$html = '<script>
<script> var status = "' . $response['status'] . '";
var expd = new Date(); var expd = new Date();
expd.setTime(expd.getTime()+1000); expd.setTime(expd.getTime()+1000);
var expires = "expires="+expd.toGMTString(); var expires = "expires="+expd.toGMTString();
document.cookie=\'language=; path=/; \'+expires; document.cookie=\'language=; path=/; \'+expires;
x = 30; </script>';
function countSecond() return message($html, $title, 201, 1);*/
{  $data["dplId"] = $response['status'];
x--; return output(json_encode($data), 201);
document.getElementById("displayBox").innerHTML = x;
if (x>0) setTimeout("countSecond()", 1000);
}
// 执行函数
countSecond();
</script>
<meta http-equiv="refresh" content="30;URL=' . path_format($_SERVER['base_path'] . '/') . '">', 302);
} }
return message($html, $title, 201);
} }
} }
if ($_GET['install0']) { if ($_GET['install0']) {
@ -210,14 +204,16 @@ language:<br>';
$html .= ' $html .= '
<label><input type="radio" name="language" value="'.$key1.'" '.($key1==$constStr['language']?'checked':'').' onclick="changelanguage(\''.$key1.'\')">'.$value1.'</label><br>'; <label><input type="radio" name="language" value="'.$key1.'" '.($key1==$constStr['language']?'checked':'').' onclick="changelanguage(\''.$key1.'\')">'.$value1.'</label><br>';
} }
if (getConfig('APIKey')=='') $html .= ' //if (getConfig('APIKey')=='')
$html .= '<br>
<a href="https://vercel.com/account/tokens" target="_blank">' . getconstStr('Create') . ' token</a><br> <a href="https://vercel.com/account/tokens" target="_blank">' . getconstStr('Create') . ' token</a><br>
<label>Token:<input name="APIKey" type="text" placeholder="" size=""></label><br>'; <label>Token:<input name="APIKey" type="password" placeholder="" value="' . getConfig('APIKey') . '"></label><br>';
$html .= '<br> $html .= '<br>
<label>Set admin password:<input name="admin" type="password" placeholder="' . getconstStr('EnvironmentsDescription')['admin'] . '" size="' . strlen(getconstStr('EnvironmentsDescription')['admin']) . '"></label><br>'; <label>Set admin password:<input name="admin" type="password" placeholder="' . getconstStr('EnvironmentsDescription')['admin'] . '" size="' . strlen(getconstStr('EnvironmentsDescription')['admin']) . '"></label><br>';
$html .= ' $html .= '
<input type="submit" value="'.getconstStr('Submit').'"> <input type="submit" value="'.getconstStr('Submit').'">
</form> </form>
<div id="showerror"></div>
<script> <script>
var nowtime= new Date(); var nowtime= new Date();
var timezone = 0-nowtime.getTimezoneOffset()/60; var timezone = 0-nowtime.getTimezoneOffset()/60;
@ -225,6 +221,7 @@ language:<br>';
expd.setTime(expd.getTime()+(2*60*60*1000)); expd.setTime(expd.getTime()+(2*60*60*1000));
var expires = "expires="+expd.toGMTString(); var expires = "expires="+expd.toGMTString();
document.cookie="timezone="+timezone+"; path=/; "+expires; document.cookie="timezone="+timezone+"; path=/; "+expires;
var errordiv = document.getElementById("showerror");
function changelanguage(str) function changelanguage(str)
{ {
var expd = new Date(); var expd = new Date();
@ -238,26 +235,69 @@ language:<br>';
if (t.admin.value==\'\') { if (t.admin.value==\'\') {
alert(\'input admin\'); alert(\'input admin\');
return false; return false;
}'; }
if (getConfig('APIKey')=='') $html .= '
if (t.APIKey.value==\'\') { if (t.APIKey.value==\'\') {
alert(\'input API Key\'); alert(\'input Token\');
return false; return false;
}'; }
$html .= ' t.style.display = "none";
return true; errordiv.innerHTML = "' . getconstStr('Wait') . '";
var xhr = new XMLHttpRequest();
xhr.open("POST", t.action);
xhr.onload = function(e) {
if (xhr.status==201) {
var res = JSON.parse(xhr.responseText);
getStatus(res.dplId, t.APIKey.value);
} else {
t.style.display = "";
errordiv.innerHTML = xhr.status + "<br>" + xhr.responseText;
}
}
xhr.send("admin=" + t.admin.value + "&APIKey=" + t.APIKey.value);
var x = "";
var min = 0;
function getStatus(id, VercelToken) {
x += ".";
min++;
var xhr = new XMLHttpRequest();
var url = "https://api.vercel.com/v11/now/deployments/" + id;
xhr.open("GET", url);
xhr.setRequestHeader("Authorization", "Bearer " + VercelToken);
xhr.onload = function(e) {
if (xhr.status==200) {
var deployStat = JSON.parse(xhr.responseText).readyState;
if (deployStat=="READY") {
x = "";
min = 0;
errordiv.innerHTML = "Deploy done.";
location.href = "/";
} else {
errordiv.innerHTML = deployStat + ", " + min + ".<br>' . getconstStr('Wait') . ' " + x;
if (deployStat!=="ERROR") setTimeout(function() { getStatus(id, VercelToken) }, 1000);
}
} else {
t.style.display = "";
console.log(xhr.status);
console.log(xhr.responseText);
}
}
xhr.send(null);
}
return false;
} }
</script>'; </script>';
$title = getconstStr('SelectLanguage'); $title = getconstStr('SelectLanguage');
return message($html, $title, 201); return message($html, $title, 201);
} }
if (substr($_SERVER["host"], -10)=="vercel.app") { if (substr($_SERVER["host"], -10)=="vercel.app") {
$html .= '<a href="?install0">' . getconstStr('ClickInstall') . '</a>, ' . getconstStr('LogintoBind'); $html .= '<a href="?install0">' . getconstStr('ClickInstall') . '</a>, ' . getconstStr('LogintoBind');
$html .= "<br>Remember: you MUST wait 30-60s after each operate / do some change, that make sure Vercel has done the building<br>" ; $html .= "<br>Remember: you MUST wait 30-60s after each operate / do some change, that make sure Vercel has done the building<br>" ;
} else { } else {
$html.= "Please visit form *.vercel.app"; $html.= "Please visit form *.vercel.app";
} }
$title = 'Install'; $title = 'Install';
return message($html, $title, 201); return message($html, $title, 201);
} }
@ -265,52 +305,54 @@ language:<br>';
// POST /v8/projects/:id/env // POST /v8/projects/:id/env
function setVercelConfig($envs, $appId, $token) function setVercelConfig($envs, $appId, $token)
{ {
$url = "https://api.vercel.com/v8/projects/" . $appId . "/env"; $url = "https://api.vercel.com/v8/projects/" . $appId . "/env";
$header["Authorization"] = "Bearer " . $token; $header["Authorization"] = "Bearer " . $token;
$header["Content-Type"] = "application/json"; $header["Content-Type"] = "application/json";
$response = curl("GET", $url, "", $header); $response = curl("GET", $url, "", $header);
$result = json_decode($response['body'], true); $result = json_decode($response['body'], true);
foreach ($result["envs"] as $key => $value) { foreach ($result["envs"] as $key => $value) {
$existEnvs[$value["key"]] = $value["id"]; $existEnvs[$value["key"]] = $value["id"];
} }
$response = null; $response = null;
foreach ($envs as $key => $value) { foreach ($envs as $key => $value) {
$tmp = null; $tmp = null;
$tmp["type"] = "encrypted"; $tmp["type"] = "encrypted";
$tmp["key"] = $key; $tmp["key"] = $key;
$tmp["value"] = $value; $tmp["value"] = $value;
$tmp["target"] = [ "development", "production", "preview" ]; $tmp["target"] = [ "development", "production", "preview" ];
if (isset($existEnvs[$key])) { if (isset($existEnvs[$key])) {
if ($value) $response = curl("PATCH", $url . "/" . $existEnvs[$key], json_encode($tmp), $header); if ($value) $response = curl("PATCH", $url . "/" . $existEnvs[$key], json_encode($tmp), $header);
else $response = curl("DELETE", $url . "/" . $existEnvs[$key], "", $header); else $response = curl("DELETE", $url . "/" . $existEnvs[$key], "", $header);
} else { } else {
if ($value) $response = curl("POST", $url, json_encode($tmp), $header); if ($value) $response = curl("POST", $url, json_encode($tmp), $header);
} }
//echo $key . ":" . $value . ", " . json_encode($response, JSON_PRETTY_PRINT) . "<br>"; //echo $key . ":" . $value . ", " . json_encode($response, JSON_PRETTY_PRINT) . "<br>";
} }
return VercelUpdate($appId, $token); return VercelUpdate($appId, $token);
//return $response; //return $response;
} }
function VercelUpdate($appId, $token, $sourcePath = "") function VercelUpdate($appId, $token, $sourcePath = "")
{ {
$url = "https://api.vercel.com/v12/now/deployments"; $url = "https://api.vercel.com/v12/now/deployments";
$header["Authorization"] = "Bearer " . $token; $header["Authorization"] = "Bearer " . $token;
$header["Content-Type"] = "application/json"; $header["Content-Type"] = "application/json";
$data["name"] = "OneManager"; $data["name"] = "OneManager";
$data["project"] = $appId; $data["project"] = $appId;
$data["target"] = "production"; $data["target"] = "production";
$data["routes"][0]["src"] = "/(.*)"; $data["routes"][0]["src"] = "/(.*)";
$data["routes"][0]["dest"] = "/api/index.php"; $data["routes"][0]["dest"] = "/api/index.php";
$data["functions"]["api/index.php"]["runtime"] = "vercel-php@0.4.0"; $data["functions"]["api/index.php"]["runtime"] = "vercel-php@0.4.0";
if ($sourcePath=="") $sourcePath = splitlast(splitlast(__DIR__, "/")[0], "/")[0]; if ($sourcePath=="") $sourcePath = splitlast(splitlast(__DIR__, "/")[0], "/")[0];
//echo $sourcePath . "<br>"; //echo $sourcePath . "<br>";
getEachFiles($file, $sourcePath); getEachFiles($file, $sourcePath);
$data["files"] = $file; $data["files"] = $file;
//echo json_encode($data, JSON_PRETTY_PRINT) . " ,data<br>"; //echo json_encode($data, JSON_PRETTY_PRINT) . " ,data<br>";
$response = curl("POST", $url, json_encode($data), $header); $response = curl("POST", $url, json_encode($data), $header);
return $response["body"]; $result = json_decode($response["body"], true);
$result['status'] = $result['id'];
return json_encode($result);
} }
function getEachFiles(&$file, $base, $path = "") function getEachFiles(&$file, $base, $path = "")
@ -321,13 +363,13 @@ function getEachFiles(&$file, $base, $path = "")
while($filename=readdir($handler)) { while($filename=readdir($handler)) {
if($filename != '.' && $filename != '..' && $filename != '.git'){ if($filename != '.' && $filename != '..' && $filename != '.git'){
$fromfile = path_format($base . "/" . $path . "/" . $filename); $fromfile = path_format($base . "/" . $path . "/" . $filename);
//echo $fromfile . "<br>"; //echo $fromfile . "<br>";
if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归 if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归
$response = getEachFiles($file, $base, path_format($path . "/" . $filename)); $response = getEachFiles($file, $base, path_format($path . "/" . $filename));
if (api_error(setConfigResponse($response))) return $response; if (api_error(setConfigResponse($response))) return $response;
}else{ }else{
$tmp['file'] = path_format($path . "/" . $filename); $tmp['file'] = path_format($path . "/" . $filename);
$tmp['data'] = file_get_contents($fromfile); $tmp['data'] = file_get_contents($fromfile);
$file[] = $tmp; $file[] = $tmp;
} }
} }
@ -379,9 +421,25 @@ function OnekeyUpate($auth = 'qkqpttgf', $project = 'OneManager-php', $branch =
break; break;
} }
} }
//echo $outPath . "<br>"; //echo $outPath . "<br>";
//error_log1($outPath); //error_log1($outPath);
if ($outPath=='') return '{"error":{"message":"no outpath"}}'; if ($outPath=='') return '{"error":{"message":"no outpath"}}';
return VercelUpdate(getConfig('HerokuappId'), getConfig('APIKey'), $outPath); return VercelUpdate(getConfig('HerokuappId'), getConfig('APIKey'), $outPath);
} }
function WaitFunction($deployid) {
$header["Authorization"] = "Bearer " . getConfig('APIKey');
$header["Content-Type"] = "application/json";
$url = "https://api.vercel.com/v11/now/deployments/" . $deployid;
$response = curl("GET", $url, "", $header);
if ($response['stat']==200) {
$result = json_decode($response['body'], true);
if ($result['readyState']=="READY") return true;
if ($result['readyState']=="ERROR") return $response;
return false;
} else {
$response['body'] .= $url;
return $response;
}
}