71 lines
2.0 KiB
PHP
71 lines
2.0 KiB
PHP
<?php
|
|
|
|
class Netsync extends Plugin
|
|
{
|
|
public function sync()
|
|
{
|
|
$host = $this->config["master"];
|
|
$key = $this->config["key"];
|
|
|
|
if (empty($key)) {
|
|
throw new RuntimeException("API key is empty");
|
|
}
|
|
|
|
$ch = curl_init("http://" . $host . "/rpc");
|
|
|
|
|
|
curl_setopt($ch, CURLOPT_HEADER, false);
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
|
|
"jsonrpc" => "2.0",
|
|
"id" => "1",
|
|
"method" => "getConfig",
|
|
"params" => []
|
|
]));
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
"X-Auth: " . md5($key),
|
|
"Content-type: application/json"
|
|
]);
|
|
|
|
$output = curl_exec($ch);
|
|
try {
|
|
if ($err = curl_error($ch)) {
|
|
throw new RuntimeException("Failed to fetch remote API: " . $err);
|
|
}
|
|
} finally {
|
|
curl_close($ch);
|
|
}
|
|
|
|
$header = @json_decode($output, true);
|
|
|
|
$result = $header["result"] ?? null;
|
|
|
|
$networks = $result["networks"] ?? null;
|
|
if ($result === null or $networks === null) {
|
|
throw new RuntimeException("Response has invalid data");
|
|
}
|
|
|
|
$available = array_keys((new NetworkConfigReader())->getConfigs());
|
|
|
|
$remote_enabled = array_filter($networks, function ($e) use ($available) {
|
|
return in_array($e, $available);
|
|
});
|
|
$wrapper = $this->context->getConfig();
|
|
$local_enabled = $wrapper["networks"];
|
|
$diff = array_diff($remote_enabled, $local_enabled);
|
|
if (count($diff) > 0) {
|
|
$wrapper["networks"] = array_values($remote_enabled);
|
|
$wrapper->save();
|
|
}
|
|
foreach ($this->context->getRPC()->getPlugins() as $plugin) {
|
|
/**
|
|
* @var IPluggable $plugin
|
|
*/
|
|
|
|
$plugin->onSync();
|
|
}
|
|
return $diff;
|
|
}
|
|
} |