lighter design

This commit is contained in:
Radek Davidek 2025-11-16 01:04:04 +01:00
parent 2f3eeebe72
commit 2a0721040b
3 changed files with 227 additions and 125 deletions

View File

@ -13,9 +13,6 @@ import java.util.List;
public class HttpServerApp { public class HttpServerApp {
// Statický API klíč
private static final String API_KEY = "6666-1234";
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
TransmissionService service = new TransmissionService(); TransmissionService service = new TransmissionService();
@ -26,8 +23,6 @@ public class HttpServerApp {
server.createContext("/transmissions", exchange -> { server.createContext("/transmissions", exchange -> {
try { try {
setCors(exchange); setCors(exchange);
if (!checkApiKey(exchange))
return;
URI uri = exchange.getRequestURI(); URI uri = exchange.getRequestURI();
String query = uri.getQuery(); String query = uri.getQuery();
@ -59,8 +54,6 @@ public class HttpServerApp {
server.createContext("/search", exchange -> { server.createContext("/search", exchange -> {
try { try {
setCors(exchange); setCors(exchange);
if (!checkApiKey(exchange))
return;
URI uri = exchange.getRequestURI(); URI uri = exchange.getRequestURI();
String query = null; String query = null;
@ -84,8 +77,6 @@ public class HttpServerApp {
server.createContext("/refresh", exchange -> { server.createContext("/refresh", exchange -> {
try { try {
setCors(exchange); setCors(exchange);
if (!checkApiKey(exchange))
return;
if ("GET".equalsIgnoreCase(exchange.getRequestMethod())) { if ("GET".equalsIgnoreCase(exchange.getRequestMethod())) {
// přečti volitelné datum z query stringu // přečti volitelné datum z query stringu
@ -138,8 +129,6 @@ public class HttpServerApp {
return; return;
} }
if (!checkApiKey(exchange))
return;
if ("/".equals(path) || path.isEmpty() || path.equals("/index.html")) { if ("/".equals(path) || path.isEmpty() || path.equals("/index.html")) {
String html = readResource("/index.html"); String html = readResource("/index.html");
if (html == null) { if (html == null) {
@ -164,9 +153,9 @@ public class HttpServerApp {
server.start(); server.start();
System.out.println("🚀 HTTP server běží na http://localhost:8080"); System.out.println("🚀 HTTP server běží na http://localhost:8080");
System.out.println(" ➜ /transmissions (všechny přenosy JSON, vyžaduje X-API-KEY)"); System.out.println(" ➜ /transmissions (všechny přenosy JSON)");
System.out.println(" ➜ /search?q=Brno (vyhledávání JSON, vyžaduje X-API-KEY)"); System.out.println(" ➜ /search?q=Brno (vyhledávání JSON)");
System.out.println(" ➜ /refresh (spustí opětovné načtení dat, vyžaduje X-API-KEY)"); System.out.println(" ➜ /refresh (spustí opětovné načtení dat)");
System.out.println(" ➜ / (web UI)"); System.out.println(" ➜ / (web UI)");
} }
@ -187,32 +176,6 @@ public class HttpServerApp {
} }
} }
// ======= API Key ochrana =======
private static boolean checkApiKey(HttpExchange exchange) throws IOException {
String query = exchange.getRequestURI().getQuery(); // např. apiKey=xxxx
String key = null;
if (query != null) {
for (String part : query.split("&")) {
if (part.startsWith("apiKey=")) {
key = java.net.URLDecoder.decode(part.substring(7), StandardCharsets.UTF_8);
break;
}
}
}
if (!API_KEY.equals(key)) {
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
byte[] bytes = "{\"error\":\"Unauthorized\"}".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(401, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
return false;
}
return true;
}
// ======= CORS ======= // ======= CORS =======
private static void setCors(HttpExchange exchange) { private static void setCors(HttpExchange exchange) {
Headers h = exchange.getResponseHeaders(); Headers h = exchange.getResponseHeaders();

View File

@ -27,46 +27,122 @@ h1 {
} }
input, select, button { input, select, button {
padding: 6px 10px; padding: 8px 16px;
font-size: 15px; font-size: 15px;
border: 1px solid #ddd;
border-radius: 5px;
cursor: pointer;
} }
.grid { button {
display: grid; background: white;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); transition: all 0.2s;
gap: 15px;
} }
.card { button:hover {
background: #f0f0f0;
}
button.active {
background: #4a90e2;
color: white;
border-color: #4a90e2;
}
.sport-buttons {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: center;
margin-bottom: 20px;
}
.table-container {
background: white; background: white;
border-radius: 10px; border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden; overflow: hidden;
transition: transform 0.2s;
} }
.card:hover { table {
transform: scale(1.02);
}
.card img {
width: 100%; width: 100%;
height: 160px; border-collapse: collapse;
}
thead {
background: #4a90e2;
color: white;
}
th {
padding: 12px;
text-align: left;
font-weight: 600;
font-size: 14px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
td {
padding: 12px;
border-bottom: 1px solid #e0e0e0;
}
tbody tr {
transition: background-color 0.2s;
}
tbody tr:hover {
background-color: #f8f9fa;
}
tbody tr:last-child td {
border-bottom: none;
}
.thumbnail {
width: 80px;
height: 60px;
object-fit: cover; object-fit: cover;
border-radius: 5px;
} }
.card-content { .title-cell {
padding: 10px; font-weight: 500;
color: #333;
} }
.title { .title-cell a {
font-weight: bold; color: #333;
margin-bottom: 5px; text-decoration: none;
} }
.meta { .title-cell a:hover {
font-size: 0.9em; color: #4a90e2;
text-decoration: underline;
}
.time-cell {
white-space: nowrap;
color: #666; color: #666;
font-size: 14px;
}
.sport-cell {
color: #666;
font-size: 14px;
}
.league-cell {
color: #888;
font-size: 13px;
}
.no-results {
text-align: center;
padding: 40px;
color: #666;
font-size: 16px;
} }
#loading { #loading {
@ -75,9 +151,19 @@ input, select, button {
margin-top: 30px; margin-top: 30px;
} }
@media ( max-width : 500px) { @media (max-width: 768px) {
.card img { th, td {
height: 120px; padding: 8px;
font-size: 13px;
}
.thumbnail {
width: 60px;
height: 45px;
}
th:nth-child(4), td:nth-child(4) {
display: none;
} }
} }
</style> </style>
@ -86,30 +172,36 @@ input, select, button {
<h1>📺 TVCOM Přenosy</h1> <h1>📺 TVCOM Přenosy</h1>
<div class="filters"> <div class="filters">
<input id="search" type="text" placeholder="Hledat přenos..." /> <input <input id="search" type="text" placeholder="Hledat přenos..." />
id="datePicker" type="date" /> <select id="sportFilter"> <input id="datePicker" type="date" />
<option value="">Všechny sporty</option>
</select>
<button id="refreshBtn">♻️ Obnovit data</button>
</div> </div>
<div class="sport-buttons" id="sportButtons"></div>
<div id="loading">Načítám data...</div> <div id="loading">Načítám data...</div>
<div id="list" class="grid" style="display: none"></div> <div id="list" style="display: none"></div>
<script> <script>
const API_BASE = ""; const API_BASE = "";
const urlParams = new URLSearchParams(window.location.search);
const apiKey = urlParams.get('apiKey');
const listEl = document.getElementById('list'); const listEl = document.getElementById('list');
const loadingEl = document.getElementById('loading'); const loadingEl = document.getElementById('loading');
const searchEl = document.getElementById('search'); const searchEl = document.getElementById('search');
const sportFilterEl = document.getElementById('sportFilter'); const sportButtonsEl = document.getElementById('sportButtons');
const datePicker = document.getElementById('datePicker'); const datePicker = document.getElementById('datePicker');
const refreshBtn = document.getElementById('refreshBtn');
let all = []; let all = [];
let selectedSport = 'Basketbal';
// === funkce pro získání lokálního data ===
function getLocalDateString() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// === inicializace === // === inicializace ===
const today = new Date().toISOString().substring(0, 10); const today = getLocalDateString();
datePicker.value = today; datePicker.value = today;
fetchForDate(today); fetchForDate(today);
@ -131,37 +223,12 @@ function debounce(func, wait) {
// === vyhledávání === // === vyhledávání ===
const debouncedApplyFilters = debounce(applyFilters, 300); const debouncedApplyFilters = debounce(applyFilters, 300);
searchEl.addEventListener('input', debouncedApplyFilters); searchEl.addEventListener('input', debouncedApplyFilters);
sportFilterEl.addEventListener('change', applyFilters);
// === tlačítko obnovit ===
refreshBtn.addEventListener('click', () => {
loadingEl.style.display = 'block';
listEl.style.display = 'none';
const now = new Date().toISOString().substring(0, 10);
datePicker.value = now;
fetch(`${API_BASE}/refresh?apiKey=${apiKey}`)
.then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
})
.then(() => {
// po úspěšném refresh načteme aktuální den
const now = new Date().toISOString().substring(0, 10);
datePicker.value = now;
return fetchForDate(now);
})
.catch(err => {
console.error(err);
loadingEl.textContent = "❌ Chyba při obnově dat: " + err;
});
});
// === načtení dat pro daný den === // === načtení dat pro daný den ===
function fetchForDate(dateStr) { function fetchForDate(dateStr) {
loadingEl.style.display = 'block'; loadingEl.style.display = 'block';
listEl.style.display = 'none'; listEl.style.display = 'none';
return fetch(`${API_BASE}/transmissions?date=${encodeURIComponent(dateStr)}&apiKey=${apiKey}`) return fetch(`${API_BASE}/transmissions?date=${encodeURIComponent(dateStr)}`)
.then(r => { .then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`); if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json(); return r.json();
@ -171,7 +238,7 @@ function fetchForDate(dateStr) {
populateSports(); populateSports();
applyFilters(); applyFilters();
loadingEl.style.display = 'none'; loadingEl.style.display = 'none';
listEl.style.display = 'grid'; listEl.style.display = 'block';
}) })
.catch(err => { .catch(err => {
console.error(err); console.error(err);
@ -182,56 +249,122 @@ function fetchForDate(dateStr) {
// === naplnění filtrů podle dostupných sportů === // === naplnění filtrů podle dostupných sportů ===
function populateSports() { function populateSports() {
const sports = [...new Set(all.map(t => t.sport).filter(Boolean))].sort(); const sports = [...new Set(all.map(t => t.sport).filter(Boolean))].sort();
sportFilterEl.innerHTML = '<option value="">Všechny sporty</option>'; sportButtonsEl.innerHTML = '';
// Tlačítka pro jednotlivé sporty
for (const s of sports) { for (const s of sports) {
const opt = document.createElement('option'); const btn = document.createElement('button');
opt.value = s; btn.textContent = s;
opt.textContent = s; btn.className = selectedSport === s ? 'active' : '';
sportFilterEl.appendChild(opt); btn.addEventListener('click', () => {
selectedSport = s;
updateSportButtons();
applyFilters();
});
sportButtonsEl.appendChild(btn);
} }
// Tlačítko "Všechny sporty" jako poslední
const allBtn = document.createElement('button');
allBtn.textContent = 'Všechny sporty';
allBtn.className = selectedSport === '' ? 'active' : '';
allBtn.addEventListener('click', () => {
selectedSport = '';
updateSportButtons();
applyFilters();
});
sportButtonsEl.appendChild(allBtn);
}
// === aktualizace aktivního tlačítka ===
function updateSportButtons() {
const buttons = sportButtonsEl.querySelectorAll('button');
buttons.forEach(btn => {
if (btn.textContent === 'Všechny sporty') {
btn.className = selectedSport === '' ? 'active' : '';
} else {
btn.className = selectedSport === btn.textContent ? 'active' : '';
}
});
} }
// === aplikace filtrů a vykreslení === // === aplikace filtrů a vykreslení ===
function applyFilters() { function applyFilters() {
const query = searchEl.value.toLowerCase(); const query = searchEl.value.toLowerCase();
const sport = sportFilterEl.value;
const filtered = all.filter(t => { const filtered = all.filter(t => {
return (!query || t.title.toLowerCase().includes(query) || (t.league||'').toLowerCase().includes(query)) && return (!query || t.title.toLowerCase().includes(query) || (t.league||'').toLowerCase().includes(query)) &&
(!sport || t.sport === sport); (!selectedSport || t.sport === selectedSport);
}); });
renderList(filtered); renderList(filtered);
} }
// === formátování data a času === // === formátování data a času ===
function formatDateTime(dateStr, timeStr) { function formatDateTime(dateStr, timeStr) {
if (!dateStr || !timeStr) return ''; if (!dateStr || !timeStr) return '—';
const dt = new Date(dateStr + 'T' + timeStr); try {
return dt.toLocaleString('cs-CZ', { dateStyle: 'short', timeStyle: 'short' }); // Normalizuj čas na formát HH:MM (přidej vedoucí nulu, pokud chybí)
const timeParts = timeStr.split(':');
if (timeParts.length === 2) {
const hours = timeParts[0].padStart(2, '0');
const minutes = timeParts[1].padStart(2, '0');
timeStr = `${hours}:${minutes}`;
}
const dt = new Date(dateStr + 'T' + timeStr);
if (isNaN(dt.getTime())) return '—';
return dt.toLocaleString('cs-CZ', { dateStyle: 'short', timeStyle: 'short' });
} catch (e) {
return '—';
}
} }
// === vykreslení seznamu === // === vykreslení seznamu ===
function renderList(items) { function renderList(items) {
listEl.innerHTML = '';
if (!items.length) { if (!items.length) {
listEl.innerHTML = '<div style="grid-column:1/-1;text-align:center;">Žádné přenosy</div>'; listEl.innerHTML = '<div class="no-results">Žádné přenosy pro vybrané datum a filtry</div>';
return; return;
} }
let tableHTML = `
<div class="table-container">
<table>
<thead>
<tr>
<th>Náhled</th>
<th>Název</th>
<th>Čas</th>
<th>Sport</th>
<th>Liga</th>
</tr>
</thead>
<tbody>
`;
for (const t of items) { for (const t of items) {
const div = document.createElement('div');
div.className = 'card';
const dateTimeStr = formatDateTime(t.date, t.time); const dateTimeStr = formatDateTime(t.date, t.time);
div.innerHTML = ` const imgSrc = t.image || 'https://via.placeholder.com/80x60?text=Bez+náhledu';
<a href="${t.link}" target="_blank"> const league = t.league || '';
<img src="${t.image || 'https://via.placeholder.com/400x160?text=Žádný+obrázek'}" alt=""> const leaguePart = t.leaguePart || '';
<div class="card-content"> const fullLeague = `${league} ${leaguePart}`.trim();
<div class="title">${t.title}</div>
<div class="meta">${dateTimeStr}</div> tableHTML += `
<div class="meta">${t.sport} • ${t.league || ''} ${t.leaguePart || ''}</div> <tr>
</div> <td><img src="${imgSrc}" alt="" class="thumbnail"></td>
</a> <td class="title-cell"><a href="${t.link}" target="_blank">${t.title}</a></td>
<td class="time-cell">${dateTimeStr}</td>
<td class="sport-cell">${t.sport || ''}</td>
<td class="league-cell">${fullLeague}</td>
</tr>
`; `;
listEl.appendChild(div);
} }
tableHTML += `
</tbody>
</table>
</div>
`;
listEl.innerHTML = tableHTML;
} }
</script> </script>
</body> </body>

6
tvcom.log Normal file
View File

@ -0,0 +1,6 @@
nohup: ignoring input
🚀 HTTP server běží na http://localhost:8080
➜ /transmissions (přenosy pro zadaný den přes ?date=YYYY-MM-DD, vyžaduje apiKey)
➜ /search?q=Brno (vyhledávání JSON, vyžaduje apiKey)
➜ /refresh (spustí opětovné načtení dat, volitelně ?date=YYYY-MM-DD)
➜ / (web UI)