diff --git a/.htaccess b/.htaccess index 20d82ef..f334076 100644 --- a/.htaccess +++ b/.htaccess @@ -2,6 +2,7 @@ RewriteEngine On # require https RewriteCond %{HTTPS} off +RewriteCond %{REQUEST_URI} !^/api/update RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] #token to HTTP_AUTHORIZATION diff --git a/api.php b/api.php deleted file mode 100644 index 8433449..0000000 --- a/api.php +++ /dev/null @@ -1,319 +0,0 @@ -write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO); -} - -//zabespecit proti Ddosu -if (isset($obj['user']) && $obj['user'] != ''){ - //user at home - $user = UserManager::getUser($obj['user']); - $userAtHome = $user['at_home']; - if (!empty($user)) { - $userId = $user['user_id']; - $atHome = $obj['atHome']; - if($userAtHome != $atHome){ - UserManager::atHome($userId, $atHome); - $logManager->write("[USER] user " . $userId . " changet his home state to " . $atHome , LogRecordType::INFO); - } - echo 'Saved: ' . $atHome; - header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); - die(); - } -} - -//Filtrování IP adress -if (DEBUGMOD != 1) { - if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) { - echo json_encode(array( - 'state' => 'unsuccess', - 'errorMSG' => "Using API from your IP insnt alowed!", - ), JSON_PRETTY_PRINT); - header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); - $logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING); - exit(); - } -} - -//automationExecution -try { - AutomationManager::executeAll(); - $fallbackManager = new FallbackManager(RANGES); - $fallbackManager->check(); - //LogKeeper::purge(LOGTIMOUT); -} catch (\Exception $e) { - $logManager->write("[Automation] Something happen during automation execution", LogRecordType::ERROR); -} - -//Record Cleaning -try { - RecordManager::clean(RECORDTIMOUT); -} catch (\Exception $e) { - $logManager->write("[Record] cleaning record older that " . RECORDTIMOUT , LogRecordType::ERROR); -} - -//Variables -$token = $obj['token']; -$values = null; -$settings = null; -$deviceLogs = null; -$command = "null"; - -if (isset($obj['values'])) { - $values = $obj['values']; -} - -if (isset($obj['settings'])) { - $settings = $obj['settings']; -} - -if (isset($obj['logs'])) { - $deviceLogs = $obj['logs']; -} - - - -//Checks -if ($token == null || $token == "") { - echo json_encode(array( - 'state' => 'unsuccess', - 'errorMSG' => "Missing Value Token in JSON payload", - ), JSON_PRETTY_PRINT); - header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); - die(); -} - -//Vstupní Checky -if (!DeviceManager::registeret($token)) { - //Notification data setup - $notificationMng = new NotificationManager; - $notificationData = [ - 'title' => 'Info', - 'body' => 'New device Detected Found', - 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', - ]; - - //Subdevice Registration - $deviceId = DeviceManager::create($token, $token); - foreach ($values as $key => $value) { - if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) { - SubDeviceManager::create($deviceId, $key, UNITS[$key]); - } - } - - //Notification for newly added Device - if ($notificationData != []) { - $subscribers = $notificationMng::getSubscription(); - foreach ($subscribers as $key => $subscriber) { - $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO); - $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); - } - } - - header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); - echo json_encode(array( - 'state' => 'unsuccess', - 'errorMSG' => "Device not registeret", - ), JSON_PRETTY_PRINT); - $logManager->write("[API] Registering Device", LogRecordType::INFO); - exit(); -} - -if (!DeviceManager::approved($token)) { - header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); - echo json_encode(array( - 'state' => 'unsuccess', - 'errorMSG' => "Unaproved Device", - ), JSON_PRETTY_PRINT); - exit(); -} - -// Diagnostic Data Write to DB -if ($settings != null && $settings != ""){ - $data = ['mac' => $settings["network"]["mac"], 'ip_address' => $settings["network"]["ip"]]; - if (array_key_exists("firmware_hash", $settings)) { - $data['firmware_hash'] = $settings["firmware_hash"]; - } - DeviceManager::editByToken($token, $data); - $jsonAnswer = [ - 'state' => 'succes', - 'command' => $command, - ]; - echo json_encode($jsonAnswer, JSON_PRETTY_PRINT); - header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); - die(); -} - -// Issuing command -if ($command == "null"){ - $device = DeviceManager::getDeviceByToken($token); - $deviceId = $device['device_id']; - $deviceCommand = $device["command"]; - if ($deviceCommand != '' && $deviceCommand != null && $deviceCommand != "null") - { - $command = $deviceCommand; - $data = [ - 'command'=>'null' - ]; - DeviceManager::editByToken($token, $data); - $logManager->write("[API] Device_ID " . $deviceId . " executing command " . $command, LogRecordType::INFO); - } -} - -// Diagnostic Logs Write To log File -if ($deviceLogs != null && $deviceLogs != ""){ - foreach ($deviceLogs as $log) { - $logManager->write("[Device Log Msg] Device_ID " . $deviceId . "->" . $log, LogRecordType::ERROR); - } - $jsonAnswer = [ - 'state' => 'succes', - 'command' => $command, - ]; - echo json_encode($jsonAnswer, JSON_PRETTY_PRINT); - header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); - die(); -} - -// Subdevices first data! -if ($values != null && $values != "") { - - //ZAPIS - $device = DeviceManager::getDeviceByToken($token); - $deviceId = $device['device_id']; - foreach ($values as $key => $value) { - if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) { - SubDeviceManager::create($deviceId, $key, UNITS[$key]); - } - RecordManager::create($deviceId, $key, round($value['value'],3)); - $logManager->write("[API] Device_ID " . $deviceId . " writed value " . $key . ' ' . $value['value'], LogRecordType::INFO); - - //notification - if ($key == 'door' || $key == 'water') { - $notificationMng = new NotificationManager; - $notificationData = []; - - switch ($key) { - case 'door': - $notificationData = [ - 'title' => 'Info', - 'body' => 'Someone just open up '.$device['name'], - 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', - ]; - - break; - case 'water': - $notificationData = [ - 'title' => 'Alert', - 'body' => 'Wather leak detected by '.$device['name'], - 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', - ]; - break; - } - if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value']; - if ($notificationData != []) { - $subscribers = $notificationMng::getSubscription(); - foreach ($subscribers as $key => $subscriber) { - $logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO); - $notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); - } - } - } - } - - $hostname = strtolower($device['name']); - $hostname = str_replace(' ', '_', $hostname); - //upravit format na setings-> netvork etc - $jsonAnswer = [ - 'device' => [ - 'hostname' => $hostname, - 'ipAddress' => $device['ip_address'], - 'subnet' => $device['subnet'], - 'gateway' => $device['gateway'], - ], - 'state' => 'succes', - 'command' => $command, - ]; - - $subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($deviceId); - if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) { - $jsonAnswer['device']['sleepTime'] = $device['sleep_time']; - } - echo json_encode($jsonAnswer, JSON_PRETTY_PRINT); - header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); -} else { - //Vypis - $device = DeviceManager::getDeviceByToken($token); - $deviceId = $device['device_id']; - - if (count(SubDeviceManager::getAllSubDevices($deviceId)) == 0) { - SubDeviceManager::create($deviceId, 'on/off', UNITS[$key]); - //RecordManager::create($deviceId, 'on/off', 0); - } - - $subDeviceId = SubDeviceManager::getAllSubDevices($deviceId)[0]['subdevice_id']; - $subDeviceLastReord = RecordManager::getLastRecord($subDeviceId); - $subDeviceLastReordValue = $subDeviceLastReord['value']; - - if ($subDeviceLastReord['execuded'] == 0){ - $logManager->write("[API] subDevice_ID ".$subDeviceId . " executed comand with value " .$subDeviceLastReordValue . " record id " . $subDeviceLastReord['record_id'] . " executed " . $subDeviceLastReord['execuded'], LogRecordType::INFO); - RecordManager::setExecuted($subDeviceLastReord['record_id']); - } - - echo json_encode(array( - 'device' => [ - 'hostname' => $device['name'], - 'ipAddress' => $device['ip_address'], - 'subnet' => $device['subnet'], - 'gateway' => $device['gateway'], - ], - 'state' => 'succes', - 'value' => $subDeviceLastReordValue, - 'command' => $command, - ), JSON_PRETTY_PRINT); - header($_SERVER["SERVER_PROTOCOL"]." 200 OK"); -} - -unset($logManager); -Db::disconect(); -die(); diff --git a/app/Routes.php b/app/Routes.php index d2e7dad..9a68dbc 100644 --- a/app/Routes.php +++ b/app/Routes.php @@ -33,7 +33,7 @@ $router->any('/api/HA', 'GoogleHomeApi@response'); //Endpoints API $router->post('/api/endpoint/', 'EndpointsApi@default'); -$router->any('/api/update/', 'EndpointsApi@update'); +$router->any('/api/update/', 'UpdatesApi@default'); $router->any('/api/users/status', 'UsersApi@status'); // examples diff --git a/app/api/EndpointsApi.php b/app/api/EndpointsApi.php index be37d2b..2d4f07e 100644 --- a/app/api/EndpointsApi.php +++ b/app/api/EndpointsApi.php @@ -177,69 +177,4 @@ class EndpointsApi extends ApiController{ $this->response($jsonAnswer); // this method returns response as json } - - private function sendFile($path) { - header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK', true, 200); - header('Content-Type: application/octet-stream', true); - header('Content-Disposition: attachment; filename=' . basename($path)); - header('Content-Length: ' . filesize($path), true); - header('x-MD5: ' . md5_file($path), true); - readfile($path); - } - - public function update() { - $logManager = new LogManager(); - - header('Content-type: text/plain; charset=utf8', true); - - //Filtrování IP adress - if (DEBUGMOD != 1) { - if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) { - echo json_encode(array( - 'state' => 'unsuccess', - 'errorMSG' => "Using API from your IP insnt alowed!", - )); - header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); - $logManager->write("[Updater] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING); - exit(); - } - } - - $macAddress = $_SERVER['HTTP_X_ESP8266_STA_MAC']; - $localBinary = "./app/updater/" . str_replace(':', '', $macAddress) . ".bin"; - $logManager->write("[Updater] url: " . $localBinary, LogRecordType::INFO); - $logManager->write("[Updater] version: " . $_SERVER['HTTP_X_ESP8266_SKETCH_MD5'], LogRecordType::INFO); - if (file_exists($localBinary)) { - $logManager->write("[Updater] version PHP: \n" . md5_file($localBinary), LogRecordType::INFO); - if ($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'] != md5_file($localBinary)) { - sendFile($localBinary); - //get device data - $device = DeviceManager::getDeviceByMac($macAddress); - $deviceName = $device['name']; - $deviceId = $device['device_id']; - //logfile write - $logManager->write("[Device] device_ID " . $deviceId . " was just updated to new version", LogRecordType::WARNING); - $logManager->write("[Device] version hash: \n" . md5_file($localBinary), LogRecordType::INFO); - //notification - $notificationMng = new NotificationManager; - $notificationData = [ - 'title' => 'Info', - 'body' => $deviceName.' was just updated to new version', - 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', - ]; - if ($notificationData != []) { - $subscribers = $notificationMng->getSubscription(); - foreach ($subscribers as $key => $subscriber) { - $logManager->write("[NOTIFICATION] SENDING TO " . $subscriber['id'] . " ", LogRecordType::INFO); - $answer = $notificationMng->sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); - } - } - } else { - header($_SERVER["SERVER_PROTOCOL"].' 304 Not Modified', true, 304); - } - } else { - header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); - } - die(); - } } diff --git a/app/api/UpdatesApi.php b/app/api/UpdatesApi.php new file mode 100644 index 0000000..020e04e --- /dev/null +++ b/app/api/UpdatesApi.php @@ -0,0 +1,66 @@ + 'unsuccess', + 'errorMSG' => "Using API from your IP insnt alowed!", + )); + header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); + $logManager->write("[Updater] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING); + exit(); + } + } + + $macAddress = $_SERVER['HTTP_X_ESP8266_STA_MAC']; + $localBinary = "../updater/" . str_replace(':', '', $macAddress) . ".bin"; + $logManager->write("[Updater] url: " . $localBinary, LogRecordType::INFO); + $logManager->write("[Updater] version: " . $_SERVER['HTTP_X_ESP8266_SKETCH_MD5'], LogRecordType::INFO); + if (file_exists($localBinary)) { + $logManager->write("[Updater] version PHP: \n" . md5_file($localBinary), LogRecordType::INFO); + if ($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'] != md5_file($localBinary)) { + sendFile($localBinary); + //get device data + $device = DeviceManager::getDeviceByMac($macAddress); + $deviceName = $device['name']; + $deviceId = $device['device_id']; + //logfile write + $logManager->write("[Device] device_ID " . $deviceId . " was just updated to new version", LogRecordType::WARNING); + $logManager->write("[Device] version hash: \n" . md5_file($localBinary), LogRecordType::INFO); + //notification + $notificationMng = new NotificationManager; + $notificationData = [ + 'title' => 'Info', + 'body' => $deviceName.' was just updated to new version', + 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', + ]; + if ($notificationData != []) { + $subscribers = $notificationMng->getSubscription(); + foreach ($subscribers as $key => $subscriber) { + $logManager->write("[NOTIFICATION] SENDING TO " . $subscriber['id'] . " ", LogRecordType::INFO); + $answer = $notificationMng->sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); + } + } + } else { + header($_SERVER["SERVER_PROTOCOL"].' 304 Not Modified', true, 304); + } + } else { + header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); + } + die(); + } +} \ No newline at end of file diff --git a/public/.htaccess b/public/.htaccess index 3ad65e5..c0d1475 100644 --- a/public/.htaccess +++ b/public/.htaccess @@ -12,8 +12,7 @@ RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule . - [e=HTTP_AUTHORIZATION:%1] RewriteCond %{HTTPS} off -RewriteCond %{REQUEST_FILENAME} !api.php -RewriteCond %{REQUEST_FILENAME} !apiFront.php +RewriteCond %{REQUEST_URI} !^/api/update RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] AddType application/x-httpd-php .php .phtml diff --git a/update.php b/update.php deleted file mode 100644 index 51d1c5b..0000000 --- a/update.php +++ /dev/null @@ -1,91 +0,0 @@ - 'unsuccess', - 'errorMSG' => "Using API from your IP insnt alowed!", - )); - header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); - $logManager->write("[Updater] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING); - exit(); - } -} - -function sendFile($path) -{ - header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK', true, 200); - header('Content-Type: application/octet-stream', true); - header('Content-Disposition: attachment; filename=' . basename($path)); - header('Content-Length: ' . filesize($path), true); - header('x-MD5: ' . md5_file($path), true); - readfile($path); -} - -$macAddress = $_SERVER['HTTP_X_ESP8266_STA_MAC']; -$localBinary = "./app/updater/" . str_replace(':', '', $macAddress) . ".bin"; -$logManager->write("[Updater] url: " . $localBinary, LogRecordType::INFO); -$logManager->write("[Updater] version: " . $_SERVER['HTTP_X_ESP8266_SKETCH_MD5'], LogRecordType::INFO); -if (file_exists($localBinary)) { - $logManager->write("[Updater] version PHP: \n" . md5_file($localBinary), LogRecordType::INFO); - if ($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'] != md5_file($localBinary)) { - sendFile($localBinary); - //get device data - $device = DeviceManager::getDeviceByMac($macAddress); - $deviceName = $device['name']; - $deviceId = $device['device_id']; - //logfile write - $logManager->write("[Device] device_ID " . $deviceId . " was just updated to new version", LogRecordType::WARNING); - $logManager->write("[Device] version hash: \n" . md5_file($localBinary), LogRecordType::INFO); - //notification - $notificationMng = new NotificationManager; - $notificationData = [ - 'title' => 'Info', - 'body' => $deviceName.' was just updated to new version', - 'icon' => BASEDIR . '/app/templates/images/icon-192x192.png', - ]; - if ($notificationData != []) { - $subscribers = $notificationMng->getSubscription(); - foreach ($subscribers as $key => $subscriber) { - $logManager->write("[NOTIFICATION] SENDING TO " . $subscriber['id'] . " ", LogRecordType::INFO); - $answer = $notificationMng->sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData); - } - } - } else { - header($_SERVER["SERVER_PROTOCOL"].' 304 Not Modified', true, 304); - } -} else { - header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); -} -die();