Plugin system modification

This commit is contained in:
GamerClassN7 2020-10-22 16:42:49 +02:00
parent 1a3e659ca7
commit 946a93a23b
9 changed files with 282 additions and 155 deletions

View File

@ -1,26 +1,38 @@
<?php <?php
class CronApi extends ApiController { class CronApi extends ApiController
{
public function clean(){ public function clean()
$logKeeper = new LogMaintainer(); {
$logKeeper->purge(LOGTIMOUT); //Log Cleaning
$this->response(['Value' => 'OK']); $logKeeper = new LogMaintainer();
} $logKeeper->purge(LOGTIMOUT);
public function fetch(){ //Database Backup Cleanup
//echo (new VirtualDeviceManager)->fetch(''); $backupWorker = new DatabaseBackup();
echo (new Covid)->fetch(''); $backupWorker->purge(5);
echo (new OpenWeatherMap)->fetch('');
echo (new UsaElection)->fetch('');
echo (new AirQuality)->fetch('');
// Database Backup $this->response(['Value' => 'OK']);
$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);
}
} }

View File

@ -3,7 +3,7 @@
class RoomsApi extends ApiController{ class RoomsApi extends ApiController{
public function default(){ public function default(){
$this->requireAuth(); //$this->requireAuth();
$response = []; $response = [];
$roomIds = []; $roomIds = [];
$roomsData = RoomManager::getRoomsDefault(); $roomsData = RoomManager::getRoomsDefault();
@ -12,7 +12,28 @@ class RoomsApi extends ApiController{
$roomIds[] = $room['room_id']; $roomIds[] = $room['room_id'];
} }
//Translation Of Numeric Walues
$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds($roomIds); $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) { foreach ($roomsData as $roomKey => $roomData) {
if ($roomData['device_count'] == 0) continue; if ($roomData['device_count'] == 0) continue;

View File

@ -7,26 +7,45 @@ class AirQuality extends VirtualDeviceManager
private $virtual_device_name = "Air Quality"; private $virtual_device_name = "Air Quality";
private $subdevice_type = "air-quality"; private $subdevice_type = "air-quality";
function fetch($url) function make()
{ {
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();
if (DeviceManager::registeret($this->virtual_device_name)) { $finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; $json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) { RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi']);
SubDeviceManager::create($deviceId, $this->subdevice_type, ''); } else {
sleep(1); DeviceManager::create($this->virtual_device_name, $this->virtual_device_name);
DeviceManager::approved($this->virtual_device_name);
} }
return 'sucessful';
//if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die(); } catch(Exception $e) {
return 'exception: ' . $e->getMessage();
$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);
} }
} }
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 '';
}
} }

View File

@ -5,29 +5,34 @@ class Covid extends VirtualDeviceManager
private $api_uri = 'https://api.covid19api.com/live/country/%s/status/confirmed'; // Your redirect uri private $api_uri = 'https://api.covid19api.com/live/country/%s/status/confirmed'; // Your redirect uri
private $virtual_device_name = "Covid"; private $virtual_device_name = "Covid";
function fetch($url = 'true') function make()
{ {
if (DeviceManager::registeret($this->virtual_device_name)) { try {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; if (DeviceManager::registeret($this->virtual_device_name)) {
$dataItems = ['Confirmed', 'Deaths', 'Recovered', 'Active']; $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
foreach ($dataItems as $dataItem) { $dataItems = ['Confirmed', 'Deaths', 'Recovered', 'Active'];
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) { foreach ($dataItems as $dataItem) {
SubDeviceManager::create($deviceId, strtolower($dataItem), $dataItem); if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) {
sleep(1); 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);
} }
return 'sucessful';
if (!$this->fetchEnabled($deviceId, $subDevice['subdevice_id'])) die(); } catch (Exception $e) {
return 'exception: ' . $e->getMessage();
$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);
} }
} }
} }

View File

@ -1,27 +1,46 @@
<?php <?php
class DatabaseBackup { class DatabaseBackup
public function scheme(){ {
$backupfile = $_SERVER['DOCUMENT_ROOT'] . BASEDIR ."/backup/" . DBNAME.'_scheme_'.date("Y-m-d", time()).'.sql'; public function make()
$command = "mysqldump --skip-comments --no-create-info -h localhost -u ". DBUSER . " -p" . DBPASS ." ". DBNAME ." -r $backupfile 2>&1"; {
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); $this->executeCommand($command);
return $backupfile; return $backupfile;
} }
public function data(){ 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"; $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); $this->executeCommand($command);
return $backupfile; return $backupfile;
} }
private function executeCommand($command){ private function executeCommand($command)
{
ini_set('date.timezone', 'Europe/Prague'); ini_set('date.timezone', 'Europe/Prague');
exec($command); exec($command);
} }
public function compress($filename, $files = []) { private function compress($filename, $files = [])
{
$zip = new ZipArchive(); $zip = new ZipArchive();
if($zip->open($filename,ZipArchive::CREATE|ZipArchive::OVERWRITE)) { if ($zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
foreach ($files as $file) { foreach ($files as $file) {
$zip->addFile($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);
}
} }

View File

@ -0,0 +1,11 @@
<?php
class AirQuality extends VirtualDeviceManager
{
function make(){
//Getting Data
}
function translate($value){
//Translation of numeric values
}
}

View File

@ -7,24 +7,29 @@ class OpenWeatherMap extends VirtualDeviceManager
private $virtual_device_name = "Weather"; private $virtual_device_name = "Weather";
private $subdevice_type = "weather"; private $subdevice_type = "weather";
function fetch($url) function make()
{ {
if (DeviceManager::registeret($this->virtual_device_name)) { try {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; if (DeviceManager::registeret($this->virtual_device_name)) {
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) { $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
SubDeviceManager::create($deviceId, $this->subdevice_type, ''); if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) {
sleep(1); 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);
} }
return 'sucessful';
if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die(); } catch (Exception $e) {
return 'exception: ' . $e->getMessage();
$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);
} }
} }
} }

View File

@ -1,55 +1,66 @@
<?php <?php
class Spotify extends VirtualDeviceManager { class Spotify extends VirtualDeviceManager
{
private $token = ""; private $token = "";
private $client_id = '76840e2199e34dcd903d19877bd726dd'; // Your client id private $client_id = '76840e2199e34dcd903d19877bd726dd'; // Your client id
private $redirect_uri = 'https://dev.steelants.cz/vasek/home-update/plugins/spotify/callback'; // Your redirect uri private $redirect_uri = 'https://dev.steelants.cz/vasek/home-update/plugins/spotify/callback'; // Your redirect uri
public function oAuth(){ public function oAuth()
{
$client_secret = 'CLIENT_SECRET'; // Your secret $client_secret = 'CLIENT_SECRET'; // Your secret
$scopes = 'user-read-private user-read-email'; $scopes = 'user-read-private user-read-email';
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'); 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; $this->token = $token;
} }
public function callback(){ public function callback()
{
var_dump($_REQUEST); var_dump($_REQUEST);
(new SettingsManager)->create('spotify_token', $token); (new SettingsManager)->create('spotify_token', $token);
} }
public function autorize(){ public function autorize()
{
$client_secret = '0f94ed2c0bd64bf791ea13b7e6310ba3'; $client_secret = '0f94ed2c0bd64bf791ea13b7e6310ba3';
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token' ); curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 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_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_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']); $this->setToken(json_decode($result, true)['access_token']);
echo $result; echo $result;
} }
private function getPlayerData(){ private function getPlayerData()
{
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.spotify.com/v1/me/player' ); curl_setopt($ch, CURLOPT_URL, 'https://api.spotify.com/v1/me/player');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . (new SettingsManager)->getByName('spotify_token')['value'])); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . (new SettingsManager)->getByName('spotify_token')['value']));
$result=curl_exec($ch); $result = curl_exec($ch);
echo $result; echo $result;
} }
function fetch($url = 'true') // function make()
{ // {
$this->autorize(); // try {
$this->getPlayerData(); // //$this->autorize();
} // //$this->getPlayerData();
// return 'sucessful';
// } catch (Exception $e) {
// return 'exception: ' . $e->getMessage();
// }
// }
} }

View File

@ -5,61 +5,61 @@ class UsaElection extends VirtualDeviceManager
private $virtual_device_name = "Election"; private $virtual_device_name = "Election";
private $subdevice_type = "election"; private $subdevice_type = "election";
function fetch($url = 'true') function make()
{ {
if (DeviceManager::registeret($this->virtual_device_name)) { try {
$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id']; if (DeviceManager::registeret($this->virtual_device_name)) {
$dataItems = ['Trump', 'Biden', 'Unknown']; $deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
foreach ($dataItems as $dataItem) { $dataItems = ['Trump', 'Biden', 'Unknown'];
if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) { foreach ($dataItems as $dataItem) {
SubDeviceManager::create($deviceId, strtolower($dataItem), '% ' . $dataItem); if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($dataItem))) {
sleep(1); 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; $finalUrl = $this->api_uri;
$json = json_decode(Utilities::CallAPI('GET', $finalUrl), true); $json = json_decode(Utilities::CallAPI('GET', $finalUrl), true);
$voteSpectrum = [ $voteSpectrum = [
'republican' => [ 'republican' => [
'solid' => 0, 'solid' => 0,
'leaning' => 0, 'leaning' => 0,
], ],
'democrat' => [ 'democrat' => [
'solid' => 0, 'solid' => 0,
'leaning' => 0, 'leaning' => 0,
], ],
'tossup' => 0 'tossup' => 0
]; ];
foreach ($json as $state){ foreach ($json as $state) {
if ($state['raceCategory'] != 'tossup'){ if ($state['raceCategory'] != 'tossup') {
$raceCategory = explode('-',$state['raceCategory']); $raceCategory = explode('-', $state['raceCategory']);
$voteSpectrum[$raceCategory[0]][$raceCategory[1]] = $voteSpectrum[$raceCategory[0]][$raceCategory[1]] + $state['raceDelegates']; $voteSpectrum[$raceCategory[0]][$raceCategory[1]] = $voteSpectrum[$raceCategory[0]][$raceCategory[1]] + $state['raceDelegates'];
} else { } else {
$voteSpectrum['tossup'] = $voteSpectrum['tossup'] + $state['raceDelegates']; $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);
} }
return 'sucessful';
$Trump = $voteSpectrum['republican']['solid'] + $voteSpectrum['republican']['leaning']; } catch (Exception $e) {
$Biden = $voteSpectrum['democrat']['solid'] + $voteSpectrum['democrat']['leaning']; return 'exception: ' . $e->getMessage();
$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);
} }
} }
} }