Compare commits

..

No commits in common. "a3fbdf58594b5fc2dce28622bbacc2b487f782f0" and "15ddca379f4324a8b3d2aa6f2b02174daad7e44a" have entirely different histories.

4 changed files with 64 additions and 229 deletions

View File

@ -1,22 +1,3 @@
<?php
if (null !== $_POST['set_pwd']) {
$pwd = $_POST['set_pwd'];
file_put_contents('data/admin_pwd', password_hash($pwd, PASSWORD_DEFAULT));
setcookie('owe_admin', base64_encode($pwd), ['httponly' => true]);
header('location: admin.php');
} elseif (null !== $_POST['pwd']) {
$pwd = $_POST['pwd'];
if (password_verify($pwd, file_get_contents('data/admin_pwd'))) {
setcookie('owe_admin', base64_encode($pwd), ['httponly' => true]);
header('location: admin.php');
print("DER KEKS MÜSSTE GESETZT SEIN");
} else {
print("Nope, falsch");
}
}
?>
<!DOCTYPE html> <!DOCTYPE html>
<?php <?php
@ -66,6 +47,13 @@ $config_data = json_decode($raw_json_config, false);
<?php <?php
if (null !== $_POST['set_pwd']) {
$pwd = $_POST['set_pwd'];
file_put_contents('data/admin_pwd', password_hash($pwd, PASSWORD_DEFAULT));
setcookie('owe_admin', base64_encode($pwd), ['httponly' => true]);
header('location: admin.php');
}
endif; endif;
if ($login): if ($login):
@ -108,8 +96,17 @@ $config_data = json_decode($raw_json_config, false);
</form> </form>
<?php <?php
endif; if (null !== $_POST['pwd']) {
?> $pwd = $_POST['pwd'];
if (password_verify($pwd, file_get_contents('data/admin_pwd'))) {
setcookie('owe_admin', base64_encode($pwd), ['httponly' => true]);
header('location: admin.php');
} else {
print("Nope, falsch");
}
}
endif; ?>
</p> </p>
<script> <script>

View File

@ -1,21 +1,21 @@
<?php
header("Cache-Control: no-cache, no-store, must-revalidate");
?>
<!DOCTYPE html> <!DOCTYPE html>
<?php <?php
function get_color_from_userdata($data) { function get_color_from_ip($ip) {
$ip_elem = explode(".", $ip);
$css = "background-color: hsl("; $css = "background-color: hsl(";
$number = abs(crc32($data)); $number = abs(crc32($ip));
$css .= ($number % 360).", "; $css .= ($number % 360).", ";
$css .= (50 + (($number >> 3) % 51))."%, "; $css .= (50 + (($number >> 3) % 51))."%, ";
$css .= (50 + (($number >> 5) % 31))."%);"; // maximal 80%, es soll nicht einfach weiß sein $css .= (50 + (($number >> 5) % 51))."%);";
return $css; return $css;
} }
//header("refresh: 28");
header("Cache-Control: no-cache, no-store, must-revalidate");
if (!is_dir("data")) { if (!is_dir("data")) {
// initialize everything // initialize everything
mkdir("data", 0755); mkdir("data", 0755);
@ -46,8 +46,7 @@ if (array_key_exists("submitted", $_REQUEST)) {
if ($botrequest) { if ($botrequest) {
$content .= "background-color: darksalmon; color: white;'>"; $content .= "background-color: darksalmon; color: white;'>";
} else { } else {
// Farbe hängt ab von Benutzer und ändert sich nach gewisser Zeit. $content .= get_color_from_ip($_SERVER['REMOTE_ADDR'])."'>";
$content .= get_color_from_userdata($_REQUEST["user"].strval(intdiv(time(),60*60*24*7)))."'>";
} }
$ends_of_sentence = ['.', '!', '?']; $ends_of_sentence = ['.', '!', '?'];

218
owe.js
View File

@ -2,7 +2,7 @@ var previousTextLength;
var config_data; var config_data;
var unread_words = 0; var unread_words = 0;
async function loadSentences(alertIfNew = false, increaseUnread = true) { function loadSentences(alertIfNew = false, increaseUnread = true) {
fetch("./data/sentences.txt", {headers: {"Cache-Control": "no-cache, no-store"}}) fetch("./data/sentences.txt", {headers: {"Cache-Control": "no-cache, no-store"}})
.then((response) => { .then((response) => {
return response.text().then((text) => { return response.text().then((text) => {
@ -31,20 +31,17 @@ async function loadSentences(alertIfNew = false, increaseUnread = true) {
// color // color
var spans = document.querySelector(".sentences").getElementsByTagName("span"); var spans = document.querySelector(".sentences").getElementsByTagName("span");
// we expect this to be from the user who's turn it is now (2 users)
if (spans.length >= config_data.users.length) { var histurnspan = spans[spans.length - 2];
var histurnspan = spans[spans.length - config_data.users.length];
//console.log(histurnspan.getAttribute("style")); //console.log(histurnspan.getAttribute("style"));
document.getElementById("wordinput").setAttribute("style", histurnspan.getAttribute("style")); document.getElementById("wordinput").setAttribute("style", histurnspan.getAttribute("style"));
} else {
console.error('Not enough spans available for users.');
}
initializeLoginArea(); initializeLoginArea();
}); });
}); });
} }
async function loadConfig() { function loadConfig() {
fetch("./data/config.json", {headers: {"Cache-Control": "no-cache, no-store"}}).then((response) => { fetch("./data/config.json", {headers: {"Cache-Control": "no-cache, no-store"}}).then((response) => {
return response.text().then((text) => { return response.text().then((text) => {
config_data = JSON.parse(text); config_data = JSON.parse(text);
@ -55,29 +52,6 @@ async function loadConfig() {
}); });
} }
function getUsernameFromCookie() {
// Split the document.cookie string into individual cookie key-value pairs
var cookies = document.cookie.split(';').map(cookie => cookie.trim());
// Loop through the cookies to find the 'owe_user' cookie
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
if (cookie.startsWith('owe_user=')) {
// Extract the username from the 'owe_user' cookie
return decodeURIComponent(cookie.substring('owe_user='.length));
}
}
// Return null if the 'owe_user' cookie is not set
return null;
}
function deleteUsernameCookie() {
// Set the 'owe_user' cookie to expire by setting its expiration date to a time in the past
document.cookie = 'owe_user=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=.;';
}
function onReloadClicked() { function onReloadClicked() {
loadSentences(); loadSentences();
document.querySelector("#but-reload").style.visibility = "hidden"; document.querySelector("#but-reload").style.visibility = "hidden";
@ -86,31 +60,18 @@ function onReloadClicked() {
}, 100); }, 100);
} }
async function sendWord() { function sendWord() {
try {
var data = new FormData(); var data = new FormData();
var wordInput = document.getElementById("wordinput"); data.append('submitted', encodeURI(document.getElementById("wordinput").value));
data.append('submitted', encodeURI(wordInput.value)); data.append('user', getNextPlayer());
// Use await to get the next player asynchronously
var nextPlayer = await getNextPlayer();
data.append('user', nextPlayer);
const Http = new XMLHttpRequest(); const Http = new XMLHttpRequest();
Http.open('POST', '.'); Http.open('POST', '.');
Http.onreadystatechange = (e) => { Http.onreadystatechange=(e)=>{
wordInput.value = ""; document.getElementById("wordinput").value = "";
loadSentences(false, false); loadSentences(false, false);
resetUnread(); resetUnread();
};
// Set the 'owe_user' cookie with the value obtained from getNextPlayer
document.cookie = `owe_user=${encodeURIComponent(nextPlayer)}; path=.`;
Http.send(data);
} catch (error) {
console.error("Error in sendWord:", error);
} }
Http.send(data);
} }
function displayNotification(word) { function displayNotification(word) {
@ -144,151 +105,30 @@ function resetUnread() {
} }
function getNextPlayer() { function getNextPlayer() {
var sentencesDiv = document.querySelector(".sentences"); var spans = document.querySelector(".sentences").getElementsByTagName("span");
var spans = sentencesDiv.getElementsByTagName("span"); var lastspan = spans[spans.length - 1];
var lastplayer = lastspan.dataset.user;
if (spans.length > 0) { var idx_next = (config_data.users.indexOf(lastplayer) + 1) % config_data.users.length;
var lastSpan = spans[spans.length - 1]; return config_data.users[idx_next];
var lastPlayer = lastSpan.dataset.user;
var idxNext = (config_data.users.indexOf(lastPlayer) + 1) % config_data.users.length;
return config_data.users[idxNext];
} else {
// If there are no spans, determine the next user from the archive file
var archiveFileUrl = getArchiveFileUrl(); // Replace with the actual function that returns the archive file URL
return getLastUserFromArchive(archiveFileUrl)
.then(lastUser => {
if (lastUser) {
// Calculate the next user's index based on the list of users
var idxNext = (config_data.users.indexOf(lastUser) + 1) % config_data.users.length;
return config_data.users[idxNext];
} else {
// Handle the case when the archive file is empty or contains no spans
console.error("Archive file is empty or contains no spans.");
return null;
}
})
.catch(error => {
console.error("Error fetching archive file:", error);
return null;
});
}
} }
function getTimeSinceLast() {
function getLastUserFromArchive(archiveFileUrl) { var spans = document.querySelector(".sentences").getElementsByTagName("span");
// Fetch the last span from the archive file and extract the username var lastspan = spans[spans.length - 1];
return getLastSpanFromArchive(archiveFileUrl) var lasttime = lastspan.dataset.time;
.then(lastArchiveSpan => { return Date.now()/1e3 - lasttime; // in seconds
if (lastArchiveSpan) {
return lastArchiveSpan.dataset.user;
} else {
// Handle the case when the archive file is empty or contains no spans
console.error("Archive file is empty or contains no spans.");
return null;
}
})
.catch(error => {
console.error("Error fetching archive file:", error);
return null;
});
} }
function getLastSpanFromArchive(archiveFileUrl) { function initializeLoginArea() {
// Make an asynchronous request to fetch the content of the archive file
return fetch(archiveFileUrl)
.then(response => response.text())
.then(htmlContent => {
// Parse the HTML content to get the last span
var parser = new DOMParser();
var doc = parser.parseFromString(htmlContent, 'text/html');
var archiveSpans = doc.querySelectorAll("span");
if (archiveSpans.length > 0) {
return archiveSpans[archiveSpans.length - 1];
} else {
// Return null if the archive file is empty or contains no spans
return null;
}
});
}
// bullshit implementation:
function getArchiveFileUrl() {
return "./data/sentences-archive-25-nov-23-26-jan-24.txt";
}
async function getTimeSinceLast() {
var sentencesDiv = document.querySelector(".sentences");
var spans = sentencesDiv.getElementsByTagName("span");
if (spans.length > 0) {
var lastSpan = spans[spans.length - 1];
var lastTime = lastSpan.dataset.time;
return Date.now() / 1e3 - lastTime; // in seconds
} else {
// If there are no spans, determine the last time from the archive file
var archiveFileUrl = getArchiveFileUrl(); // Replace with the actual function that returns the archive file URL
return getLastTimeFromArchive(archiveFileUrl);
}
}
async function getLastTimeFromArchive(archiveFileUrl) {
try {
// Fetch the last span from the archive file
var lastSpan = await getLastSpanFromArchive(archiveFileUrl);
if (lastSpan) {
var lastTime = lastSpan.dataset.time;
return Date.now() / 1e3 - lastTime; // in seconds
} else {
// Handle the case when the archive file is empty or contains no spans
console.error("Archive file is empty or contains no spans.");
return null;
}
} catch (error) {
console.error("Error fetching archive file:", error);
return null;
}
}
function logoutUser() {
deleteUsernameCookie();
initializeLoginArea(); // Reload everything in the login area
}
async function initializeLoginArea() {
var loginArea = document.getElementById('login_area'); var loginArea = document.getElementById('login_area');
//loginArea.innerHTML = "Eingeloggt als NOCH NICHT IMPLEMENTIERT";
var sendButton = document.getElementById('sendbut'); loginArea.innerHTML = ""; // first clear it out
sendButton.style.display = "unset" loginArea.innerHTML += getNextPlayer() + " ist dran!<br>\n";
var wordInput = document.getElementById('wordinput'); var relative_time = getTimeSinceLast();
wordInput.disabled = false; var days = Math.floor(relative_time/(3600*24));
var hours = Math.floor(relative_time/(3600))%24;
// Use async/await to wait for the result of getNextPlayer var minutes = Math.floor(relative_time/(60))%60;
try {
var loggedInPlayer = getUsernameFromCookie();
var nextPlayer = await getNextPlayer();
var relative_time = await getTimeSinceLast();
// Clear the login area
loginArea.innerHTML = "";
if (loggedInPlayer != null) {
loginArea.innerHTML += "Du bist angemeldet als " + loggedInPlayer + "."
loginArea.innerHTML += " <button onclick='logoutUser()'>abmelden</button><br>\n";
if (loggedInPlayer != nextPlayer) {
sendButton.style.display = "none";
wordInput.disabled = true;
}
}
loginArea.innerHTML += nextPlayer + " ist dran!<br>\n";
var days = Math.floor(relative_time / (3600 * 24));
var hours = Math.floor(relative_time / 3600) % 24;
var minutes = Math.floor(relative_time / 60) % 60;
loginArea.innerHTML += "Schon seit " + days + " Tagen, " + hours + " Stunden und " + minutes + " Minuten!"; loginArea.innerHTML += "Schon seit " + days + " Tagen, " + hours + " Stunden und " + minutes + " Minuten!";
} catch (error) {
// Handle any errors that may occur in the getNextPlayer function
console.error("Error in initializeLoginArea:", error);
}
} }
window.onfocus = resetUnread; window.onfocus = resetUnread;

View File

@ -115,7 +115,6 @@ input, .send_button {
.word_input_area { .word_input_area {
border: 2px solid white; border: 2px solid white;
display: inline-flex; display: inline-flex;
margin: 30px 0px;
width: 100%; width: 100%;
} }