Skip to content

Commit

Permalink
Add list folders option
Browse files Browse the repository at this point in the history
  • Loading branch information
JakubAndrysek committed Sep 6, 2024
1 parent 149e5e3 commit 9a41bc9
Show file tree
Hide file tree
Showing 13 changed files with 364 additions and 55 deletions.
6 changes: 4 additions & 2 deletions forester-game-app/app/custom_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ def get_source(self, environment, template):
template_path = pathlib.Path(current_app.config["TEMPLATES_FOLDER_LIVE"]) / template[10:]
else:
template_path = pathlib.Path(current_app.config["TEMPLATES_FOLDER"]) / template[10:]
elif current_app.config.get("LIVE_DATA_USED") and Path(current_app.config["GAMES_FOLDER_LIVE"]).exists():
elif current_app.config.get("LIVE_DATA_USED") and Path(current_app.config["GAMES_FOLDER_LIVE"]/template).exists():
template_path = pathlib.Path(current_app.config["GAMES_FOLDER_LIVE"]) / template
else:
elif Path(current_app.config["GAMES_FOLDER"]/template).exists():
template_path = pathlib.Path(current_app.config["GAMES_FOLDER"]) / template
else:
template_path = pathlib.Path(current_app.config["TEMPLATES_FOLDER"]) / "menu.html"

if not template_path.exists():
raise TemplateNotFound(template)
Expand Down
66 changes: 55 additions & 11 deletions forester-game-app/app/routes.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from pathlib import Path

from app.init import db
from app.utils import get_local_ip_address
from flask import Blueprint, render_template, abort, send_from_directory, current_app, jsonify, request
Expand All @@ -6,9 +8,38 @@
main = Blueprint('main', __name__)


def get_html_and_folders(folder: Path):
res = []
if folder.exists():
for folder_iter in folder.iterdir():
if folder_iter.is_dir():
res.append({
"name": folder_iter.name,
"is_dir": True,
})
elif folder_iter.suffix == ".html" and folder_iter.stem != "index":
res.append({
"name": folder_iter.stem,
"is_dir": False,
})
return res


def get_selected_level_routes(folder: str):
top_level_routes = []
folders_live = Path(current_app.config.get("GAMES_FOLDER_LIVE", "")) / folder
if current_app.config.get("GAMES_FOLDER_LIVE") and folders_live.exists():
top_level_routes = get_html_and_folders(folders_live)
folders = current_app.config.get("GAMES_FOLDER", "") / folder
if folders.exists():
top_level_routes.extend(get_html_and_folders(folders))
# top_level_routes.sort(key=lambda x: x.lower())
return top_level_routes


@main.route('/')
def index():
return render_template('menu/index.html')
return render_template('index.html', title='Menu', same_level_routes=get_selected_level_routes('.'))


@main.route('/download-data')
Expand Down Expand Up @@ -48,21 +79,34 @@ def render_page(folder: str, page: str):
try:
# if page contains a dot, it is a file extension - serve as static file
if '.' in page:
return send_from_directory(current_app.config.get("GAMES_FOLDER"), f'{folder}/{page}')
return render_template(
f'{folder}/{page}.html',
title=f'{folder.capitalize()}',
folder=folder,
page=page,
data=db.get_data(),
ip_address=get_local_ip_address(),
config=current_app.config,
)
path_to_file = Path(f'{current_app.config.get("GAMES_FOLDER")}/{folder}/{page}')
path_to_file_live = Path(f'{current_app.config.get("GAMES_FOLDER_LIVE")}/{folder}/{page}')
if path_to_file_live.exists():
return send_from_directory(path_to_file_live.parent, path_to_file_live.name)
elif path_to_file.exists():
return send_from_directory(path_to_file.parent, path_to_file.name)
return abort(404)
else:
return render_template(
f'{folder}/{page}.html',
title=f'{folder.capitalize()}',
folder=folder,
page=page,
data=db.get_data(),
ip_address=get_local_ip_address(),
config=current_app.config,
same_level_routes=get_selected_level_routes(folder),
)

except TemplateNotFound:
abort(404)


@main.route('/<path:filename>')
def not_allowed(filename):
return "Not allowed depth level 3", 404


# Serve static files
@main.route('/assets/<path:filename>')
def static_files(filename):
Expand Down
6 changes: 4 additions & 2 deletions forester-game-app/app/socketio_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,10 @@ def handle_exists_key(key: str) -> dict:


@socketio.on('get_key')
def handle_get_key(key: str, default=None) -> dict:
return {'status': 'ok', 'data': db.get_data_key(key, default)}
def handle_get_key(json: dict) -> dict:
key = json.get('key')
default_value = json.get('defaultValue')
return {'status': 'ok', 'data': db.get_data_key(key, default_value)}


@socketio.on('delete_key')
Expand Down
12 changes: 2 additions & 10 deletions forester-game-app/assets/js/forrestHubLib.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,6 @@ class ForrestHubLib {
}
});

this.addEventListenerKey('full_screen', async (data) => {
if (data === true) {
await document.documentElement.requestFullscreen();
} else {
await document.exitFullscreen();
}
});

this.addEventListenerKey("game_status", (data) => {
this.updateGameStatusUI(data);
});
Expand Down Expand Up @@ -107,8 +99,8 @@ class ForrestHubLib {
await this.emitWithResponse('set_key_broadcast', { key, value });
}

async getKey(key) {
const response = await this.emitWithResponse('get_key', key);
async getKey(key, defaultValue = null) {
const response = await this.emitWithResponse('get_key', { key, defaultValue });
return response.data;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ <h2>Menu</h2>
<p class="mt-4">Verze aplikace: <span class="game_status badge bg-primary">{{ config.VERSION }}</span></p>
{% include "templates/author.html" %}

{% include "templates/menu.html" %}
{% include "templates/list_folders.html" %}

<div class="mt-5">
<a href="https://helceletka.cz" target="_blank" rel="noopener noreferrer">
Expand Down
File renamed without changes.
1 change: 1 addition & 0 deletions forester-game-app/games/pošta/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
https://chatgpt.com/share/dc75c8d2-06a6-4459-9698-8513f33aee3d
82 changes: 82 additions & 0 deletions forester-game-app/games/pošta/fronty.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
{#https://chatgpt.com/share/dc75c8d2-06a6-4459-9698-8513f33aee3d#}
{% extends "templates/base.html" %}
{% set game_name = "Pošta - Tabule" %}
{% block content %}
<div class="container">
<h1>Informace o frontách</h1>
<div class="row" id="queue_info">
<div class="col-md-4">
<div class="card">
<div class="card-body">
<h3 class="card-title">Příjem</h3>
<p>Čekajících: <span id="prijem_count">0</span></p>
<ul id="prijem_list" class="list-group"></ul>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-body">
<h3 class="card-title">Odeslání</h3>
<p>Čekajících: <span id="odeslani_count">0</span></p>
<ul id="odeslani_list" class="list-group"></ul>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-body">
<h3 class="card-title">Los</h3>
<p>Čekajících: <span id="los_count">0</span></p>
<ul id="los_list" class="list-group"></ul>
</div>
</div>
</div>
</div>
</div>

<script>
const forrestLib = new ForrestHubLib();

const updateQueueDisplay = (queue, countElement, listElement) => {
const count = queue ? queue.length : 0;
countElement.innerText = count;
listElement.innerHTML = '';

(queue || []).slice(0, 3).forEach(ticket => {
const li = document.createElement('li');
li.className = 'list-group-item';
li.textContent = `Číslo: ${ticket.number}`;
listElement.appendChild(li);
});
};

const updateAllQueues = () => {
Promise.all([
forrestLib.getKey('prijem_queue', []),
forrestLib.getKey('odeslani_queue', []),
forrestLib.getKey('los_queue', [])
]).then(([prijem, odeslani, los]) => {
updateQueueDisplay(prijem, document.getElementById('prijem_count'), document.getElementById('prijem_list'));
updateQueueDisplay(odeslani, document.getElementById('odeslani_count'), document.getElementById('odeslani_list'));
updateQueueDisplay(los, document.getElementById('los_count'), document.getElementById('los_list'));
});
};

// Automatické aktualizace přes addEventListenerKey
forrestLib.addEventListenerKey('prijem_queue', (data) => {
updateQueueDisplay(data, document.getElementById('prijem_count'), document.getElementById('prijem_list'));
});

forrestLib.addEventListenerKey('odeslani_queue', (data) => {
updateQueueDisplay(data, document.getElementById('odeslani_count'), document.getElementById('odeslani_list'));
});

forrestLib.addEventListenerKey('los_queue', (data) => {
updateQueueDisplay(data, document.getElementById('los_count'), document.getElementById('los_list'));
});

// Počáteční načtení stavu front
updateAllQueues();
</script>
{% endblock %}
92 changes: 92 additions & 0 deletions forester-game-app/games/pošta/generuj.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
{#https://chatgpt.com/share/dc75c8d2-06a6-4459-9698-8513f33aee3d#}
{% extends "templates/base.html" %}
{% set game_name = "Pošta - Generování lístečků" %}
{% block content %}
<div class="container">
<h1>Generování čekacích lístečků</h1>
<p>Vyberte kategorii:</p>
<button id="generate_prijem" class="btn btn-primary">Příjem</button>
<button id="generate_odeslani" class="btn btn-secondary">Odeslání</button>
<button id="generate_los" class="btn btn-success">Los</button>
<div id="generated_number" style="margin-top: 20px;"></div>
<div id="waiting_message" style="margin-top: 20px; display:none;"></div>
<div id="last_generated" style="margin-top: 30px;">
<h4>Poslední 3 čísla</h4>
<ul id="last_tickets" class="list-group"></ul>
</div>
</div>

<script>
const forrestLib = new ForrestHubLib();
let lastGeneratedTickets = JSON.parse(localStorage.getItem('lastTickets')) || [];
let hideInfoTimer, hideGeneratedTicketTimer;

const updateLastTicketsDisplay = () => {
const listElement = document.getElementById('last_tickets');
listElement.innerHTML = '';

lastGeneratedTickets.slice(-3).forEach(ticket => {
const li = document.createElement('li');
li.className = 'list-group-item';
li.innerHTML = `Číslo: ${ticket.number} (${ticket.category}), Čas: ${ticket.time}`;
listElement.appendChild(li);
});
};

const generateTicket = (category) => {
const randomNum = Math.floor(100 + Math.random() * 900);
const timestamp = new Date().toLocaleTimeString();
const ticket = { number: randomNum, time: timestamp, category };

forrestLib.getKey(category, []).then((queue = []) => {
queue.push(ticket);
return forrestLib.setKeyBroadcast(category, queue);
}).then(() => {
const generatedNumberElement = document.getElementById('generated_number');
generatedNumberElement.innerHTML = `
<h2>Číslo ${ticket.number}</h2>
<p>Kategorie: ${category}</p>
<p>Čas: ${ticket.time}</p>
`;
generatedNumberElement.style.display = 'block';

// Resetovat timer pro schování informace o posledním lístku
if (hideGeneratedTicketTimer) clearTimeout(hideGeneratedTicketTimer);
hideGeneratedTicketTimer = setTimeout(() => {
generatedNumberElement.style.display = 'none';
}, 10000);

// Zobraz informaci o čekání
forrestLib.getKey(category, []).then((queue = []) => {
const positionInQueue = queue.length - 1; // Kolik lidí je před vámi
const waitingMessageElement = document.getElementById('waiting_message');
waitingMessageElement.style.display = 'block';
waitingMessageElement.innerHTML = `
<p>Před vámi je ${positionInQueue} lidí. Prosím, počkejte.</p>
`;

// Resetovat timer pro schování informace o čekání
if (hideInfoTimer) clearTimeout(hideInfoTimer);
hideInfoTimer = setTimeout(() => {
waitingMessageElement.style.display = 'none';
}, 10000);
});

// Ulož lístek do paměti prohlížeče
lastGeneratedTickets.push(ticket);
if (lastGeneratedTickets.length > 3) lastGeneratedTickets.shift(); // Udržuj jen poslední 3
localStorage.setItem('lastTickets', JSON.stringify(lastGeneratedTickets));

// Aktualizovat zobrazení posledních lístků
updateLastTicketsDisplay();
});
};

document.getElementById('generate_prijem').addEventListener('click', () => generateTicket('prijem_queue'));
document.getElementById('generate_odeslani').addEventListener('click', () => generateTicket('odeslani_queue'));
document.getElementById('generate_los').addEventListener('click', () => generateTicket('los_queue'));

// Načíst poslední generovaná čísla při načtení stránky
document.addEventListener('DOMContentLoaded', updateLastTicketsDisplay);
</script>
{% endblock %}
Loading

0 comments on commit 9a41bc9

Please sign in to comment.