protected-resources-list/plugins/netsync/Netsync.php

79 lines
2.3 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);
$remote_config = $header["result"] ?? null;
$networks = $remote_config["networks"] ?? null;
if ($remote_config === 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();
}
$last_hash = $this->config["last_hash"] ?? "";
$current_hash = md5(json_encode($remote_config));
if ($last_hash != $current_hash) {
foreach ($this->context->getRPC()->getPlugins() as $plugin) {
/**
* @var IPluggable $plugin
*/
$plugin->onSync($remote_config);
}
$this->config["last_hash"] = $current_hash;
$this->saveConfig();
}
return $diff;
}
}