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
class CronApi extends ApiController {
class CronApi extends ApiController
{
public function clean(){
$logKeeper = new LogMaintainer();
$logKeeper->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);
}
}

View File

@ -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[] = [

View File

@ -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 '';
}
}

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 $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();
}
}
}

View File

@ -1,27 +1,46 @@
<?php
class DatabaseBackup {
public 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";
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);
}
}

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 $subdevice_type = "weather";
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['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();
}
}
}

View File

@ -1,55 +1,66 @@
<?php
class Spotify extends VirtualDeviceManager {
class Spotify extends VirtualDeviceManager
{
private $token = "";
private $client_id = '76840e2199e34dcd903d19877bd726dd'; // Your client id
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
$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;
}
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();
// }
// }
}

View File

@ -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();
}
}
}