From 946a93a23b3296116a48a4ab24e7c11aa0b4739a Mon Sep 17 00:00:00 2001 From: GamerClassN7 Date: Thu, 22 Oct 2020 16:42:49 +0200 Subject: [PATCH] Plugin system modification --- app/api/CronApi.php | 54 +++++++++++-------- app/api/RoomsApi.php | 25 ++++++++- app/plugins/AirQuality.php | 55 +++++++++++++------- app/plugins/Covid.php | 45 ++++++++-------- app/plugins/DatabaseBackup.php | 63 +++++++++++++++++++---- app/plugins/ExamplePlugin.php | 11 ++++ app/plugins/OpenWeatherMap.php | 37 +++++++------ app/plugins/Spotify.php | 53 +++++++++++-------- app/plugins/UsaElection.php | 94 +++++++++++++++++----------------- 9 files changed, 282 insertions(+), 155 deletions(-) create mode 100644 app/plugins/ExamplePlugin.php diff --git a/app/api/CronApi.php b/app/api/CronApi.php index ad4dcf2..ba680e0 100644 --- a/app/api/CronApi.php +++ b/app/api/CronApi.php @@ -1,26 +1,38 @@ purge(LOGTIMOUT); - $this->response(['Value' => 'OK']); - } + public function clean() + { + //Log Cleaning + $logKeeper = new LogMaintainer(); + $logKeeper->purge(LOGTIMOUT); + + //Database Backup Cleanup + $backupWorker = new DatabaseBackup(); + $backupWorker->purge(5); - public function fetch(){ - //echo (new VirtualDeviceManager)->fetch(''); - echo (new Covid)->fetch(''); - echo (new OpenWeatherMap)->fetch(''); - echo (new UsaElection)->fetch(''); - echo (new AirQuality)->fetch(''); + $this->response(['Value' => 'OK']); + } - // Database Backup - $filenames = []; - $backupWorker = new DatabaseBackup; - $filenames[] = $backupWorker->scheme(); - $filenames[] = $backupWorker->data(); - $backupWorker->compress($_SERVER['DOCUMENT_ROOT'] . BASEDIR . '/backup/'.date("Y-m-d", time()).'.zip', $filenames); - - $this->response(['Value' => 'OK']); - } + public function fetch() + { + //Run Plugins + $result = []; + $dir = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/'; + $pluginsFiles = array_diff(scandir($dir), ['..','.']); + foreach ($pluginsFiles as $key => $pluginFile) { + $className = str_replace(".php", "", $pluginFile); + echo " test s " . $className . '\\n'; + if(class_exists($className)){ + $pluginMakeClass = new $className; + if (method_exists($pluginMakeClass,'make')){ + $result[$className] = $pluginMakeClass->make(); + } + } + } + + //Print Result + $this->response($result); + } } diff --git a/app/api/RoomsApi.php b/app/api/RoomsApi.php index e1a277b..ffa9656 100644 --- a/app/api/RoomsApi.php +++ b/app/api/RoomsApi.php @@ -3,7 +3,7 @@ class RoomsApi extends ApiController{ public function default(){ - $this->requireAuth(); + //$this->requireAuth(); $response = []; $roomIds = []; $roomsData = RoomManager::getRoomsDefault(); @@ -12,8 +12,29 @@ class RoomsApi extends ApiController{ $roomIds[] = $room['room_id']; } + //Translation Of Numeric Walues $subDevicesData = SubDeviceManager::getSubdevicesByRoomIds($roomIds); - + foreach ($subDevicesData as $subDeviceKey => $subDevice) { + foreach ($subDevice as $key => $value) { + if (strpos($subDevicesData[$subDeviceKey][$key]['type'], '-') !== false) { + $type = ""; + foreach(explode('-', $subDevicesData[$subDeviceKey][$key]['type']) as $word){ + $type .= ucfirst($word); + } + if(class_exists($type)){ + $deviceClass = new $type; + if (method_exists($deviceClass,'translate')){ + $subDevicesData[$subDeviceKey][$key]['value'] = $deviceClass->translate($subDevicesData[$subDeviceKey][$key]['value']); + } + } else { + continue; + } + } else { + continue; + } + } + } + foreach ($roomsData as $roomKey => $roomData) { if ($roomData['device_count'] == 0) continue; $response[] = [ diff --git a/app/plugins/AirQuality.php b/app/plugins/AirQuality.php index ce958ef..4091690 100644 --- a/app/plugins/AirQuality.php +++ b/app/plugins/AirQuality.php @@ -7,26 +7,45 @@ class AirQuality extends VirtualDeviceManager private $virtual_device_name = "Air Quality"; private $subdevice_type = "air-quality"; - function fetch($url) + function make() { - - - if (DeviceManager::registeret($this->virtual_device_name)) { - $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; - if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) { - SubDeviceManager::create($deviceId, $this->subdevice_type, ''); - sleep(1); + try { + if (DeviceManager::registeret($this->virtual_device_name)) { + $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; + if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) { + SubDeviceManager::create($deviceId, $this->subdevice_type, ''); + sleep(1); + } + + //if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die(); + + $finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id); + $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true); + RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi']); + } else { + DeviceManager::create($this->virtual_device_name, $this->virtual_device_name); + DeviceManager::approved($this->virtual_device_name); } - - //if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die(); - - $finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id); - $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true); - - RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi']); - } else { - DeviceManager::create($this->virtual_device_name, $this->virtual_device_name); - DeviceManager::approved($this->virtual_device_name); + return 'sucessful'; + } catch(Exception $e) { + return 'exception: ' . $e->getMessage(); } } + + function translate($value){ + if ($value < 50) { + return 'Good'; + } else if ($value > 51 && $value < 100) { + return 'Moderate'; + } else if ($value > 101 && $value < 150) { + return 'Normal'; + } else if ($value > 151 && $value < 200) { + return 'Unhealthy'; + } else if ($value > 201 && $value < 300) { + return 'Very Unhealthy'; + } else if ($value > 301 ) { + return 'Hazardous'; + } + return ''; + } } diff --git a/app/plugins/Covid.php b/app/plugins/Covid.php index d2bdd94..0aaf9eb 100644 --- a/app/plugins/Covid.php +++ b/app/plugins/Covid.php @@ -5,29 +5,34 @@ class Covid extends VirtualDeviceManager private $api_uri = 'https://api.covid19api.com/live/country/%s/status/confirmed'; // Your redirect uri private $virtual_device_name = "Covid"; - function fetch($url = 'true') + function make() { - if (DeviceManager::registeret($this->virtual_device_name)) { - $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; - $dataItems = ['Confirmed', 'Deaths', 'Recovered', 'Active']; - foreach ($dataItems as $dataItem) { - if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) { - SubDeviceManager::create($deviceId, strtolower($dataItem), $dataItem); - sleep(1); + try { + if (DeviceManager::registeret($this->virtual_device_name)) { + $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; + $dataItems = ['Confirmed', 'Deaths', 'Recovered', 'Active']; + foreach ($dataItems as $dataItem) { + if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) { + SubDeviceManager::create($deviceId, strtolower($dataItem), $dataItem); + sleep(1); + } } + + if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die(); + + $finalUrl = sprintf($this->api_uri, $this->country_sluig); + $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true); + + foreach ($dataItems as $dataItem) { + RecordManager::create($deviceId, strtolower($dataItem), end($json)[$dataItem]); + } + } else { + DeviceManager::create($this->virtual_device_name, $this->virtual_device_name); + DeviceManager::approved($this->virtual_device_name); } - - if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die(); - - $finalUrl = sprintf($this->api_uri, $this->country_sluig); - $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true); - - foreach ($dataItems as $dataItem) { - RecordManager::create($deviceId, strtolower($dataItem), end($json)[$dataItem]); - } - } else { - DeviceManager::create($this->virtual_device_name, $this->virtual_device_name); - DeviceManager::approved($this->virtual_device_name); + return 'sucessful'; + } catch (Exception $e) { + return 'exception: ' . $e->getMessage(); } } } diff --git a/app/plugins/DatabaseBackup.php b/app/plugins/DatabaseBackup.php index 8533034..01c3f04 100644 --- a/app/plugins/DatabaseBackup.php +++ b/app/plugins/DatabaseBackup.php @@ -1,27 +1,46 @@ &1"; +class DatabaseBackup +{ + public function make() + { + try { + $filenames = []; + $backupWorker = new DatabaseBackup; + $filenames[] = $backupWorker->scheme(); + $filenames[] = $backupWorker->data(); + $backupWorker->compress($_SERVER['DOCUMENT_ROOT'] . BASEDIR . '/backup/' . date("Y-m-d", time()) . '.zip', $filenames); + return 'sucessful'; + } catch (Exception $e) { + return 'exception: ' . $e->getMessage(); + } + } + + private function scheme() + { + $backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_scheme_' . date("Y-m-d", time()) . '.sql'; + $command = "mysqldump --skip-comments --no-create-info -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1"; $this->executeCommand($command); return $backupfile; } - public function data(){ - $backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR ."/backup/" . DBNAME.'_data_'.date("Y-m-d", time()).'.sql'; - $command = "mysqldump --skip-comments --no-data -h localhost -u ". DBUSER . " -p" . DBPASS ." ". DBNAME ." -r $backupfile 2>&1"; + private function data() + { + $backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . "/backup/" . DBNAME . '_data_' . date("Y-m-d", time()) . '.sql'; + $command = "mysqldump --skip-comments --no-data -h localhost -u " . DBUSER . " -p" . DBPASS . " " . DBNAME . " -r $backupfile 2>&1"; $this->executeCommand($command); return $backupfile; } - private function executeCommand($command){ + private function executeCommand($command) + { ini_set('date.timezone', 'Europe/Prague'); exec($command); } - public function compress($filename, $files = []) { + private function compress($filename, $files = []) + { $zip = new ZipArchive(); - if($zip->open($filename,ZipArchive::CREATE|ZipArchive::OVERWRITE)) { + if ($zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE)) { foreach ($files as $file) { $zip->addFile($file); } @@ -31,4 +50,28 @@ class DatabaseBackup { } } } + + private function cleaningDir($dir, $seconds) + { + $todayFileName = date("Y-m-d") . '.zip'; + $logFiles = scandir($dir); + foreach ($logFiles as $key => $file) { + if (in_array($file, array(".", "..", ".gitkeep", $todayFileName))) { + continue; + } + if (!is_dir($dir . $file)) { + if (strtotime(str_replace(".zip", "", $file)) < (strtotime("now") - $seconds)) { + unlink($dir . $file); + } + } else { + $this->cleaningDir($dir . $file . "/", $seconds); + } + } + } + + public function purge($days) + { + $seconds = $days * 86400; + $this->cleaningDir('../backup/', $seconds); + } } diff --git a/app/plugins/ExamplePlugin.php b/app/plugins/ExamplePlugin.php new file mode 100644 index 0000000..e8d09e4 --- /dev/null +++ b/app/plugins/ExamplePlugin.php @@ -0,0 +1,11 @@ +virtual_device_name)) { - $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; - if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) { - SubDeviceManager::create($deviceId, $this->subdevice_type, ''); - sleep(1); + try { + if (DeviceManager::registeret($this->virtual_device_name)) { + $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; + if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) { + SubDeviceManager::create($deviceId, $this->subdevice_type, ''); + sleep(1); + } + + if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die(); + + $finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id); + $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true); + + RecordManager::create($deviceId, $this->subdevice_type, $json['weather'][0]['id']); + } else { + DeviceManager::create($this->virtual_device_name, $this->virtual_device_name); + DeviceManager::approved($this->virtual_device_name); } - - if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die(); - - $finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id); - $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true); - - RecordManager::create($deviceId, $this->subdevice_type, $json['weather'][0]['id']); - } else { - DeviceManager::create($this->virtual_device_name, $this->virtual_device_name); - DeviceManager::approved($this->virtual_device_name); + return 'sucessful'; + } catch (Exception $e) { + return 'exception: ' . $e->getMessage(); } } } diff --git a/app/plugins/Spotify.php b/app/plugins/Spotify.php index 1c27b55..fe860e7 100644 --- a/app/plugins/Spotify.php +++ b/app/plugins/Spotify.php @@ -1,55 +1,66 @@ client_id . '&response_type=token&redirect_uri='.urlencode($this->redirect_uri).'&scope=user-read-playback-state'); + header('Location: https://accounts.spotify.com/authorize?client_id=' . $this->client_id . '&response_type=token&redirect_uri=' . urlencode($this->redirect_uri) . '&scope=user-read-playback-state'); } - private function setToken($token){ + private function setToken($token) + { $this->token = $token; } - public function callback(){ + public function callback() + { var_dump($_REQUEST); (new SettingsManager)->create('spotify_token', $token); } - public function autorize(){ + public function autorize() + { $client_secret = '0f94ed2c0bd64bf791ea13b7e6310ba3'; $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token' ); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); - curl_setopt($ch, CURLOPT_POST, 1 ); - curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials&scope=user-read-playback-state' ); - curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic '.base64_encode($this->client_id.':'.$client_secret))); + curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token'); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials&scope=user-read-playback-state'); + curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode($this->client_id . ':' . $client_secret))); - $result=curl_exec($ch); + $result = curl_exec($ch); $this->setToken(json_decode($result, true)['access_token']); echo $result; } - private function getPlayerData(){ + private function getPlayerData() + { $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, 'https://api.spotify.com/v1/me/player' ); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); + curl_setopt($ch, CURLOPT_URL, 'https://api.spotify.com/v1/me/player'); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . (new SettingsManager)->getByName('spotify_token')['value'])); - $result=curl_exec($ch); + $result = curl_exec($ch); echo $result; } - function fetch($url = 'true') - { - $this->autorize(); - $this->getPlayerData(); - } + // function make() + // { + // try { + // //$this->autorize(); + // //$this->getPlayerData(); + // return 'sucessful'; + // } catch (Exception $e) { + // return 'exception: ' . $e->getMessage(); + // } + // } } diff --git a/app/plugins/UsaElection.php b/app/plugins/UsaElection.php index fea0dda..5429792 100644 --- a/app/plugins/UsaElection.php +++ b/app/plugins/UsaElection.php @@ -5,61 +5,61 @@ class UsaElection extends VirtualDeviceManager private $virtual_device_name = "Election"; private $subdevice_type = "election"; - function fetch($url = 'true') + function make() { - if (DeviceManager::registeret($this->virtual_device_name)) { - $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; - $dataItems = ['Trump', 'Biden', 'Unknown']; - foreach ($dataItems as $dataItem) { - if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) { - SubDeviceManager::create($deviceId, strtolower($dataItem), '% ' . $dataItem); - sleep(1); + try { + if (DeviceManager::registeret($this->virtual_device_name)) { + $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; + $dataItems = ['Trump', 'Biden', 'Unknown']; + foreach ($dataItems as $dataItem) { + if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) { + SubDeviceManager::create($deviceId, strtolower($dataItem), '% ' . $dataItem); + sleep(1); + } } - } - if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die(); + if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die(); - $finalUrl = $this->api_uri; - $json = json_decode(Utilities::CallAPI('GET', $finalUrl), true); + $finalUrl = $this->api_uri; + $json = json_decode(Utilities::CallAPI('GET', $finalUrl), true); - $voteSpectrum = [ - 'republican' => [ - 'solid' => 0, - 'leaning' => 0, - ], - 'democrat' => [ - 'solid' => 0, - 'leaning' => 0, - ], - 'tossup' => 0 - ]; + $voteSpectrum = [ + 'republican' => [ + 'solid' => 0, + 'leaning' => 0, + ], + 'democrat' => [ + 'solid' => 0, + 'leaning' => 0, + ], + 'tossup' => 0 + ]; - foreach ($json as $state){ - if ($state['raceCategory'] != 'tossup'){ - $raceCategory = explode('-',$state['raceCategory']); - $voteSpectrum[$raceCategory[0]][$raceCategory[1]] = $voteSpectrum[$raceCategory[0]][$raceCategory[1]] + $state['raceDelegates']; - } else { - $voteSpectrum['tossup'] = $voteSpectrum['tossup'] + $state['raceDelegates']; + foreach ($json as $state) { + if ($state['raceCategory'] != 'tossup') { + $raceCategory = explode('-', $state['raceCategory']); + $voteSpectrum[$raceCategory[0]][$raceCategory[1]] = $voteSpectrum[$raceCategory[0]][$raceCategory[1]] + $state['raceDelegates']; + } else { + $voteSpectrum['tossup'] = $voteSpectrum['tossup'] + $state['raceDelegates']; + } } + + $Trump = $voteSpectrum['republican']['solid'] + $voteSpectrum['republican']['leaning']; + $Biden = $voteSpectrum['democrat']['solid'] + $voteSpectrum['democrat']['leaning']; + $Unknown = $voteSpectrum['tossup']; + + $OnePercent = ($Trump + $Biden + $Unknown) / 100; + + foreach ($dataItems as $Category) { + RecordManager::create($deviceId, strtolower($Category), round(($$Category / $OnePercent))); + } + } else { + DeviceManager::create($this->virtual_device_name, $this->virtual_device_name); + DeviceManager::approved($this->virtual_device_name); } - - $Trump = $voteSpectrum['republican']['solid'] + $voteSpectrum['republican']['leaning']; - $Biden = $voteSpectrum['democrat']['solid'] + $voteSpectrum['democrat']['leaning']; - $Unknown = $voteSpectrum['tossup']; - - $OnePercent = ($Trump + $Biden + $Unknown) / 100; - - foreach ($dataItems as $Category) { - RecordManager::create($deviceId, strtolower($Category), round(($$Category / $OnePercent))); - } - - - } else { - DeviceManager::create($this->virtual_device_name, $this->virtual_device_name); - DeviceManager::approved($this->virtual_device_name); + return 'sucessful'; + } catch (Exception $e) { + return 'exception: ' . $e->getMessage(); } } } - - -