From d8c9e3d388ce2b8f3133a972e465165d230f36d7 Mon Sep 17 00:00:00 2001 From: Maximilian Giller Date: Tue, 21 Feb 2023 05:19:48 +0100 Subject: [PATCH] Implemented custom activity, to not always rely on timeout --- index.php | 51 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 20 deletions(-) diff --git a/index.php b/index.php index d8fb73c..5fc4f0d 100755 --- a/index.php +++ b/index.php @@ -3,56 +3,67 @@ // Config $SECRET_KEY = "ENTER_SECRET_HERE"; $FILENAME = "last_activity.txt"; +$SEPARATOR = " "; $IDLE_DURATION_THRESHOLD = 60 * 30; // In seconds -$SLEEP_DURATION_THRESHOLD = 60 * 60 * 4; // In seconds +$SLEEP_DURATION_THRESHOLD = 60 * 60 * 3; // In seconds $EXPECTED_SLEEP_DURATION = 60 * 60 * 9.5; // In seconds -function storeTime($time) +function storeActivity($time, $activity = "") { - global $FILENAME; + global $FILENAME, $SEPARATOR; $file = fopen($FILENAME, "w"); - fwrite($file, $time); + fwrite($file, $time . $SEPARATOR . $activity); fclose($file); } -function getTime() +function getActivity() { - global $FILENAME; + global $FILENAME, $SEPARATOR; $file = fopen($FILENAME, "r"); - $time = fread($file, filesize($FILENAME)); + $line = fgets($file); fclose($file); - return (int)$time; + $parts = explode($SEPARATOR, $line, 2); + return array( + "time" => (int)$parts[0], + "activity" => $parts[1] + ); } // Is secret given? if (isset($_GET['secret']) && $_GET['secret'] == $SECRET_KEY) { + $activity = isset($_GET['activity']) ? $_GET['activity'] : ""; + // Update the file - storeTime(time()); - echo "Last activity udpated"; + storeActivity(time(), $activity); + echo "Last activity updated"; die(); } // Current status requested -$last_activity = getTime(); +$last_activity = getActivity(); $response = array( - "last_activity" => $last_activity + "last_activity" => $last_activity['time'], + "status" => $last_activity['activity'], ); // Estimate current activity $now = time(); -$diff = $now - $last_activity; // DIFFERENCE IN SECONDS -if ($diff >= $SLEEP_DURATION_THRESHOLD) { - $response['status'] = "Sleeping"; -} else if ($diff >= $IDLE_DURATION_THRESHOLD) { - $response['status'] = "Idle"; -} else { - $response['status'] = "Active"; +$diff = $now - $last_activity["time"]; // DIFFERENCE IN SECONDS + +if ($response['status'] == "") { + if ($diff >= $SLEEP_DURATION_THRESHOLD) { + $response['status'] = "Sleeping"; + } else if ($diff >= $IDLE_DURATION_THRESHOLD) { + $response['status'] = "Awake"; + } else { + $response['status'] = "Busy"; + } } // Estimated time until wake up -if ($response['status'] == "Sleeping") { +if (strtolower($response['status']) == "sleeping") { $response['time_until_wake'] = $EXPECTED_SLEEP_DURATION - $diff; } else { $response['time_until_wake'] = 0;