Compare commits
No commits in common. "853f88c66b51cc979843cac0b3b27a14fa0e0378" and "2bf2fc37ebdcfbfb9ed2ede4b7284221681f6991" have entirely different histories.
853f88c66b
...
2bf2fc37eb
24 changed files with 9198 additions and 1540 deletions
|
|
@ -2,13 +2,13 @@ name: Deploy to Pages
|
|||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
branches: ['main']
|
||||
pull_request:
|
||||
branches: ["main"]
|
||||
branches: ['main']
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: "pages"
|
||||
group: 'pages'
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
|
|
@ -18,6 +18,11 @@ jobs:
|
|||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Validate static frontend
|
||||
run: |
|
||||
test -f frontend/index.html
|
||||
test -f frontend/fizika.json
|
||||
|
||||
- name: Copy frontend to host pages mount
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
uses: http://forgejo:3000/andras/ci-actions/deploy-pages@main
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ name: Build and Publish Docker Image
|
|||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
branches: ['main']
|
||||
tags: ['v*']
|
||||
pull_request:
|
||||
branches: ["main"]
|
||||
branches: ['main']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
|
|
|||
|
|
@ -1,30 +0,0 @@
|
|||
name: Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
pull_request:
|
||||
branches: ["main"]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: docker
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: https://code.forgejo.org/actions/checkout@v4
|
||||
|
||||
- name: Install root tooling
|
||||
run: npm ci
|
||||
|
||||
- name: Check formatting
|
||||
run: npm run format:check
|
||||
|
||||
- name: Install backend dependencies
|
||||
run: npm ci
|
||||
working-directory: backend
|
||||
|
||||
- name: Run backend tests
|
||||
run: npm test
|
||||
working-directory: backend
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
node_modules
|
||||
backend/node_modules
|
||||
|
||||
# Lockfiles are managed by npm
|
||||
package-lock.json
|
||||
backend/package-lock.json
|
||||
|
||||
# Vendored / generated assets
|
||||
frontend/js/jquery.min.js
|
||||
*.min.js
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
{
|
||||
"printWidth": 80,
|
||||
"tabWidth": 2,
|
||||
"semi": true,
|
||||
"singleQuote": false
|
||||
}
|
||||
105
README.md
105
README.md
|
|
@ -1,106 +1 @@
|
|||
# Fizika
|
||||
|
||||
Practice web app for the Hungarian **emelt szintű fizika** (advanced-level
|
||||
physics) written school-leaving exam. Students generate quizzes from a bank of
|
||||
past exam questions — by topic, by exam paper, or as a random "érettségi"
|
||||
set — answer them, and review their past results (stored locally in the
|
||||
browser).
|
||||
|
||||
Live at <https://fizika.schmelczer.dev>.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
frontend/ Static site (HTML + CSS + jQuery, no build step).
|
||||
Deployed to Pages. Fetches questions from the backend API.
|
||||
|
||||
backend/ Express server. Serves the admin panel and a small REST API for
|
||||
editing questions and images. Reads/writes a single JSON file plus
|
||||
an images directory.
|
||||
```
|
||||
|
||||
The **backend is the single source of truth** for question data. The frontend
|
||||
always fetches it from `GET /api/fizika` (see `frontend/js/load.js`); the
|
||||
question JSON is no longer shipped with the static site.
|
||||
|
||||
### Access control
|
||||
|
||||
Authentication is handled at the reverse proxy (nginx + basic auth), not in the
|
||||
app. The proxy exposes only two endpoints publicly; everything else (the admin
|
||||
panel and all `/api/admin/*` routes) requires a login:
|
||||
|
||||
| Path | Access | Purpose |
|
||||
| --------------- | ------- | -------------------------------- |
|
||||
| `/api/fizika` | public | question data for the public app |
|
||||
| `/api/pics/*` | public | question images |
|
||||
| everything else | private | admin panel + edit API |
|
||||
|
||||
The app trusts the proxy, so **do not expose the backend port directly** without
|
||||
adding authentication in front of it.
|
||||
|
||||
## API
|
||||
|
||||
| Method | Route | Description |
|
||||
| -------- | ----------------------------- | --------------------- |
|
||||
| `GET` | `/api/fizika` | All questions |
|
||||
| `GET` | `/api/images` | List image filenames |
|
||||
| `GET` | `/api/pics/:file` | Serve an image |
|
||||
| `GET` | `/api/admin/questions` | All questions (admin) |
|
||||
| `POST` | `/api/admin/questions` | Create a question |
|
||||
| `PUT` | `/api/admin/questions/:id` | Update a question |
|
||||
| `DELETE` | `/api/admin/questions/:id` | Delete a question |
|
||||
| `POST` | `/api/admin/images/upload` | Upload an image |
|
||||
| `DELETE` | `/api/admin/images/:filename` | Delete an image |
|
||||
|
||||
## Configuration
|
||||
|
||||
The backend is configured via environment variables:
|
||||
|
||||
| Variable | Default | Description |
|
||||
| -------------- | ------------------------- | --------------------------------- |
|
||||
| `PORT` | `3001` | Port to listen on |
|
||||
| `DATA_PATH` | `../frontend/fizika.json` | Path to the questions JSON file |
|
||||
| `PICS_PATH` | `../frontend/pics` | Directory holding question images |
|
||||
| `FRONTEND_URL` | `*` | Allowed CORS origin |
|
||||
|
||||
In production `DATA_PATH` and `PICS_PATH` point at mounted volumes that hold the
|
||||
canonical data. The defaults are dev conveniences only — set both explicitly to
|
||||
a JSON file and a directory that exist before starting.
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
cd backend
|
||||
npm install
|
||||
DATA_PATH=/path/to/fizika.json PICS_PATH=/path/to/pics npm run dev
|
||||
```
|
||||
|
||||
Then open `frontend/index.html` (or serve `frontend/` statically). On
|
||||
`localhost` the frontend talks to the backend on port 3001 automatically.
|
||||
|
||||
## Tests
|
||||
|
||||
Backend tests use Node's built-in test runner (no extra dependencies):
|
||||
|
||||
```sh
|
||||
cd backend
|
||||
npm test
|
||||
```
|
||||
|
||||
## Formatting
|
||||
|
||||
[Prettier](https://prettier.io) formats the whole repo. Run from the repo root:
|
||||
|
||||
```sh
|
||||
npm install # once, to install Prettier
|
||||
npm run format # write
|
||||
npm run format:check # verify (also run in CI)
|
||||
```
|
||||
|
||||
## CI / Deployment
|
||||
|
||||
Forgejo Actions workflows in `.forgejo/workflows/`:
|
||||
|
||||
- `test.yml` — formatting check + backend tests on every push/PR.
|
||||
- `docker-publish.yml` — builds and publishes the backend image from `backend/`.
|
||||
- `deploy.yml` — deploys `frontend/` to Pages.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
node_modules
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
*.test.js
|
||||
851
backend/package-lock.json
generated
851
backend/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -5,17 +5,16 @@
|
|||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "nodemon server.js",
|
||||
"test": "node --test"
|
||||
"dev": "nodemon server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^5.2.1",
|
||||
"multer": "^2.1.1",
|
||||
"cors": "^2.8.6",
|
||||
"helmet": "^8.2.0"
|
||||
"express": "^4.18.2",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"cors": "^2.8.5",
|
||||
"helmet": "^7.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.1.14"
|
||||
"nodemon": "^3.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
|
|
|
|||
|
|
@ -6,21 +6,6 @@ window.plausible =
|
|||
(window.plausible.q = window.plausible.q || []).push(arguments);
|
||||
};
|
||||
|
||||
// Escape user-supplied text before interpolating it into HTML, to prevent XSS.
|
||||
function escapeHtml(value) {
|
||||
return String(value).replace(
|
||||
/[&<>"']/g,
|
||||
(ch) =>
|
||||
({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
})[ch],
|
||||
);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
loadQuestions();
|
||||
loadImages();
|
||||
|
|
@ -28,31 +13,23 @@ document.addEventListener("DOMContentLoaded", function () {
|
|||
});
|
||||
|
||||
function setupEventListeners() {
|
||||
document.querySelectorAll(".tab[data-tab]").forEach((tab) => {
|
||||
tab.addEventListener("click", (e) => {
|
||||
document.querySelectorAll('.tab[data-tab]').forEach(tab => {
|
||||
tab.addEventListener('click', (e) => {
|
||||
switchTab(e.target.dataset.tab);
|
||||
});
|
||||
});
|
||||
|
||||
document
|
||||
.getElementById("addQuestionBtn")
|
||||
.addEventListener("click", showAddQuestionModal);
|
||||
document.getElementById('addQuestionBtn').addEventListener('click', showAddQuestionModal);
|
||||
|
||||
document
|
||||
.getElementById("imageUpload")
|
||||
.addEventListener("change", uploadImage);
|
||||
document.getElementById('imageUpload').addEventListener('change', uploadImage);
|
||||
|
||||
document
|
||||
.getElementById("closeModalBtn")
|
||||
.addEventListener("click", closeModal);
|
||||
document.getElementById("cancelBtn").addEventListener("click", closeModal);
|
||||
document.getElementById('closeModalBtn').addEventListener('click', closeModal);
|
||||
document.getElementById('cancelBtn').addEventListener('click', closeModal);
|
||||
|
||||
document
|
||||
.getElementById("questionForm")
|
||||
.addEventListener("submit", saveQuestion);
|
||||
document.getElementById('questionForm').addEventListener('submit', saveQuestion);
|
||||
|
||||
document.getElementById("questionModal").addEventListener("click", (e) => {
|
||||
if (e.target.id === "questionModal") {
|
||||
document.getElementById('questionModal').addEventListener('click', (e) => {
|
||||
if (e.target.id === 'questionModal') {
|
||||
closeModal();
|
||||
}
|
||||
});
|
||||
|
|
@ -93,37 +70,39 @@ function displayQuestions(questions) {
|
|||
.map(
|
||||
(q) => `
|
||||
<div class="question-item">
|
||||
<h4>ID: ${q.id} - ${escapeHtml(q.source)}</h4>
|
||||
<p><strong>Kérdés:</strong> ${escapeHtml(
|
||||
q.description.substring(0, 100),
|
||||
)}...</p>
|
||||
<p><strong>Típus:</strong> ${escapeHtml(q.type)} | <strong>Helyes válasz:</strong> ${
|
||||
["A", "B", "C", "D"][q.correct - 1]
|
||||
}</p>
|
||||
<h4>ID: ${q.id} - ${q.source}</h4>
|
||||
<p><strong>Kérdés:</strong> ${q.description.substring(
|
||||
0,
|
||||
100
|
||||
)}...</p>
|
||||
<p><strong>Típus:</strong> ${q.type
|
||||
} | <strong>Helyes válasz:</strong> ${["A", "B", "C", "D"][q.correct - 1]
|
||||
}</p>
|
||||
<div class="question-actions">
|
||||
<button data-edit-id="${q.id}">Szerkesztés</button>
|
||||
<button class="danger" data-delete-id="${q.id}">Törlés</button>
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
`
|
||||
)
|
||||
.join("");
|
||||
|
||||
container.querySelectorAll("[data-edit-id]").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
container.querySelectorAll('[data-edit-id]').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
editQuestion(parseInt(e.target.dataset.editId));
|
||||
});
|
||||
});
|
||||
|
||||
container.querySelectorAll("[data-delete-id]").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
container.querySelectorAll('[data-delete-id]').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
deleteQuestion(parseInt(e.target.dataset.deleteId));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function showAddQuestionModal() {
|
||||
document.getElementById("modalTitle").textContent = "Új kérdés hozzáadása";
|
||||
document.getElementById("modalTitle").textContent =
|
||||
"Új kérdés hozzáadása";
|
||||
document.getElementById("questionForm").reset();
|
||||
document.getElementById("questionId").value = "";
|
||||
document.getElementById("questionModal").style.display = "block";
|
||||
|
|
@ -147,9 +126,11 @@ async function editQuestion(id) {
|
|||
document.getElementById("questionB").value = question.b;
|
||||
document.getElementById("questionC").value = question.c;
|
||||
document.getElementById("questionD").value = question.d;
|
||||
document.getElementById("questionCorrect").value = question.correct;
|
||||
document.getElementById("questionCorrect").value =
|
||||
question.correct;
|
||||
document.getElementById("questionType").value = question.type;
|
||||
document.getElementById("questionImage").value = question.image || "";
|
||||
document.getElementById("questionImage").value =
|
||||
question.image || "";
|
||||
document.getElementById("questionModal").style.display = "block";
|
||||
}
|
||||
}
|
||||
|
|
@ -185,7 +166,7 @@ async function saveQuestion(event) {
|
|||
method: isEdit ? "PUT" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
|
|
@ -197,7 +178,7 @@ async function saveQuestion(event) {
|
|||
showAlert(
|
||||
"questionsAlert",
|
||||
error.error || "Hiba a mentés során",
|
||||
"danger",
|
||||
"danger"
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
|
|
@ -209,9 +190,10 @@ async function deleteQuestion(id) {
|
|||
if (!confirm("Biztosan törölni szeretnéd ezt a kérdést?")) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/admin/questions/${id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
const response = await fetch(
|
||||
`${API_BASE}/api/admin/questions/${id}`,
|
||||
{ method: "DELETE" }
|
||||
);
|
||||
if (response.ok) {
|
||||
loadQuestions();
|
||||
showAlert("questionsAlert", "Kérdés törölve!", "success");
|
||||
|
|
@ -244,20 +226,16 @@ function displayImages(images) {
|
|||
.map(
|
||||
(image) => `
|
||||
<div class="image-item">
|
||||
<img src="${API_BASE}/api/pics/${encodeURIComponent(
|
||||
image,
|
||||
)}" alt="${escapeHtml(image)}">
|
||||
<p>${escapeHtml(image)}</p>
|
||||
<button class="danger" data-delete-image="${escapeHtml(
|
||||
image,
|
||||
)}">Törlés</button>
|
||||
<img src="${API_BASE}/api/pics/${image}" alt="${image}">
|
||||
<p>${image}</p>
|
||||
<button class="danger" data-delete-image="${image}">Törlés</button>
|
||||
</div>
|
||||
`,
|
||||
`
|
||||
)
|
||||
.join("");
|
||||
|
||||
container.querySelectorAll("[data-delete-image]").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
container.querySelectorAll('[data-delete-image]').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
deleteImage(e.target.dataset.deleteImage);
|
||||
});
|
||||
});
|
||||
|
|
@ -287,7 +265,7 @@ async function uploadImage() {
|
|||
showAlert(
|
||||
"imagesAlert",
|
||||
error.error || "Hiba a feltöltés során",
|
||||
"danger",
|
||||
"danger"
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
|
|
@ -303,7 +281,7 @@ async function deleteImage(filename) {
|
|||
`${API_BASE}/api/admin/images/${encodeURIComponent(filename)}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
<!doctype html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="hu">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
|
|
|
|||
|
|
@ -1,58 +1,41 @@
|
|||
const express = require("express");
|
||||
const cors = require("cors");
|
||||
const multer = require("multer");
|
||||
const path = require("path");
|
||||
const fs = require("fs").promises;
|
||||
const helmet = require("helmet");
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const fs = require('fs').promises;
|
||||
const helmet = require('helmet');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3001;
|
||||
|
||||
// Security middleware
|
||||
app.use(
|
||||
helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: [
|
||||
"'self'",
|
||||
"https://stats.schmelczer.dev",
|
||||
"'unsafe-inline'",
|
||||
],
|
||||
scriptSrc: [
|
||||
"'self'",
|
||||
"https://stats.schmelczer.dev",
|
||||
"'unsafe-inline'",
|
||||
],
|
||||
},
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: [
|
||||
"'self'",
|
||||
"https://stats.schmelczer.dev",
|
||||
"'unsafe-inline'",
|
||||
],
|
||||
scriptSrc: [
|
||||
"'self'",
|
||||
"https://stats.schmelczer.dev",
|
||||
"'unsafe-inline'",
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.use(
|
||||
cors({
|
||||
origin: process.env.FRONTEND_URL || "*",
|
||||
credentials: true,
|
||||
}),
|
||||
);
|
||||
},
|
||||
}));
|
||||
app.use(cors({
|
||||
origin: process.env.FRONTEND_URL || '*',
|
||||
credentials: true
|
||||
}));
|
||||
|
||||
app.use(express.json({ limit: "100mb" }));
|
||||
app.use(express.static("public"));
|
||||
app.use(express.json({ limit: '100mb' }));
|
||||
app.use(express.static('public'));
|
||||
|
||||
// File paths
|
||||
const DATA_PATH =
|
||||
process.env.DATA_PATH || path.join(__dirname, "../frontend/fizika.json");
|
||||
const PICS_PATH =
|
||||
process.env.PICS_PATH || path.join(__dirname, "../frontend/pics");
|
||||
|
||||
// Reject any name that could escape the target directory (path traversal).
|
||||
const isUnsafeFilename = (name) =>
|
||||
typeof name !== "string" ||
|
||||
name.length === 0 ||
|
||||
name.includes("/") ||
|
||||
name.includes("\\") ||
|
||||
name.includes("\0") ||
|
||||
name === "." ||
|
||||
name === ".." ||
|
||||
path.isAbsolute(name);
|
||||
const DATA_PATH = process.env.DATA_PATH || path.join(__dirname, '../frontend/fizika.json');
|
||||
const PICS_PATH = process.env.PICS_PATH || path.join(__dirname, '../frontend/pics');
|
||||
|
||||
// Multer configuration for image uploads
|
||||
const storage = multer.diskStorage({
|
||||
|
|
@ -60,31 +43,25 @@ const storage = multer.diskStorage({
|
|||
cb(null, PICS_PATH);
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
// Strip any directory components the client may have sent so an upload
|
||||
// named e.g. "../../server.js" can never escape PICS_PATH.
|
||||
const name = path.basename(file.originalname);
|
||||
if (isUnsafeFilename(name)) {
|
||||
return cb(new Error("Invalid filename"));
|
||||
}
|
||||
cb(null, name);
|
||||
},
|
||||
cb(null, file.originalname);
|
||||
}
|
||||
});
|
||||
|
||||
const upload = multer({
|
||||
storage: storage,
|
||||
limits: { fileSize: 50 * 1024 * 1024 }, // 50MB
|
||||
limits: { fileSize: 50 * 1024 * 1024 }, // 5MB
|
||||
fileFilter: (req, file, cb) => {
|
||||
if (file.mimetype.startsWith("image/")) {
|
||||
if (file.mimetype.startsWith('image/')) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error("Only images allowed"));
|
||||
cb(new Error('Only images allowed'));
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
// Utility functions
|
||||
const readData = async () => {
|
||||
const data = await fs.readFile(DATA_PATH, "utf8");
|
||||
const data = await fs.readFile(DATA_PATH, 'utf8');
|
||||
return JSON.parse(data);
|
||||
};
|
||||
|
||||
|
|
@ -92,42 +69,44 @@ const writeData = async (data) => {
|
|||
await fs.writeFile(DATA_PATH, JSON.stringify(data, null, 2));
|
||||
};
|
||||
|
||||
|
||||
|
||||
// Public routes
|
||||
app.get("/api/fizika", async (req, res) => {
|
||||
app.get('/api/fizika', async (req, res) => {
|
||||
try {
|
||||
const data = await readData();
|
||||
res.json(data);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Failed to read data" });
|
||||
res.status(500).json({ error: 'Failed to read data' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/api/images", async (req, res) => {
|
||||
app.get('/api/images', async (req, res) => {
|
||||
try {
|
||||
const files = await fs.readdir(PICS_PATH);
|
||||
const images = files.filter((f) => /\.(jpg|jpeg|png|gif|bmp)$/i.test(f));
|
||||
const images = files.filter(f => /\.(jpg|jpeg|png|gif|bmp)$/i.test(f));
|
||||
res.json(images);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Failed to read images" });
|
||||
res.status(500).json({ error: 'Failed to read images' });
|
||||
}
|
||||
});
|
||||
|
||||
app.use("/api/pics", express.static(PICS_PATH));
|
||||
app.use('/api/pics', express.static(PICS_PATH));
|
||||
|
||||
// Admin routes (no auth required)
|
||||
app.get("/api/admin/questions", async (req, res) => {
|
||||
app.get('/api/admin/questions', async (req, res) => {
|
||||
try {
|
||||
const data = await readData();
|
||||
res.json(data);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Failed to read questions" });
|
||||
res.status(500).json({ error: 'Failed to read questions' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/admin/questions", async (req, res) => {
|
||||
app.post('/api/admin/questions', async (req, res) => {
|
||||
try {
|
||||
const data = await readData();
|
||||
const maxId = Math.max(...data.map((q) => q.id), 0);
|
||||
const maxId = Math.max(...data.map(q => q.id), 0);
|
||||
|
||||
const newQuestion = { id: maxId + 1, ...req.body };
|
||||
data.push(newQuestion);
|
||||
|
|
@ -135,17 +114,17 @@ app.post("/api/admin/questions", async (req, res) => {
|
|||
|
||||
res.status(201).json(newQuestion);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Failed to create question" });
|
||||
res.status(500).json({ error: 'Failed to create question' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put("/api/admin/questions/:id", async (req, res) => {
|
||||
app.put('/api/admin/questions/:id', async (req, res) => {
|
||||
try {
|
||||
const data = await readData();
|
||||
const index = data.findIndex((q) => q.id === parseInt(req.params.id));
|
||||
const index = data.findIndex(q => q.id === parseInt(req.params.id));
|
||||
|
||||
if (index === -1) {
|
||||
return res.status(404).json({ error: "Question not found" });
|
||||
return res.status(404).json({ error: 'Question not found' });
|
||||
}
|
||||
|
||||
data[index] = { ...data[index], ...req.body };
|
||||
|
|
@ -153,70 +132,61 @@ app.put("/api/admin/questions/:id", async (req, res) => {
|
|||
|
||||
res.json(data[index]);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Failed to update question" });
|
||||
res.status(500).json({ error: 'Failed to update question' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete("/api/admin/questions/:id", async (req, res) => {
|
||||
app.delete('/api/admin/questions/:id', async (req, res) => {
|
||||
try {
|
||||
const data = await readData();
|
||||
const index = data.findIndex((q) => q.id === parseInt(req.params.id));
|
||||
const index = data.findIndex(q => q.id === parseInt(req.params.id));
|
||||
|
||||
if (index === -1) {
|
||||
return res.status(404).json({ error: "Question not found" });
|
||||
return res.status(404).json({ error: 'Question not found' });
|
||||
}
|
||||
|
||||
data.splice(index, 1);
|
||||
await writeData(data);
|
||||
|
||||
res.json({ message: "Question deleted" });
|
||||
res.json({ message: 'Question deleted' });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Failed to delete question" });
|
||||
res.status(500).json({ error: 'Failed to delete question' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/admin/images/upload", upload.single("image"), (req, res) => {
|
||||
app.post('/api/admin/images/upload', upload.single('image'), (req, res) => {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: "No image provided" });
|
||||
return res.status(400).json({ error: 'No image provided' });
|
||||
}
|
||||
|
||||
res.json({
|
||||
filename: req.file.filename,
|
||||
path: `/api/pics/${req.file.filename}`,
|
||||
path: `/api/pics/${req.file.filename}`
|
||||
});
|
||||
});
|
||||
|
||||
app.delete("/api/admin/images/:filename", async (req, res) => {
|
||||
if (isUnsafeFilename(req.params.filename)) {
|
||||
return res.status(400).json({ error: "Invalid filename" });
|
||||
}
|
||||
|
||||
app.delete('/api/admin/images/:filename', async (req, res) => {
|
||||
try {
|
||||
await fs.unlink(path.join(PICS_PATH, req.params.filename));
|
||||
res.json({ message: "Image deleted" });
|
||||
res.json({ message: 'Image deleted' });
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") {
|
||||
return res.status(404).json({ error: "Image not found" });
|
||||
if (error.code === 'ENOENT') {
|
||||
return res.status(404).json({ error: 'Image not found' });
|
||||
}
|
||||
res.status(500).json({ error: "Failed to delete image" });
|
||||
res.status(500).json({ error: 'Failed to delete image' });
|
||||
}
|
||||
});
|
||||
|
||||
// Error handling
|
||||
app.use((error, req, res, next) => {
|
||||
console.error("Error:", error.message);
|
||||
res.status(500).json({ error: "Server error" });
|
||||
console.error('Error:', error.message);
|
||||
res.status(500).json({ error: 'Server error' });
|
||||
});
|
||||
|
||||
app.use((req, res) => {
|
||||
res.status(404).json({ error: "Not found" });
|
||||
res.status(404).json({ error: 'Not found' });
|
||||
});
|
||||
|
||||
// Only start listening when run directly, so tests can import the app.
|
||||
if (require.main === module) {
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Fizika Admin Backend running on port ${PORT}`);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { app, isUnsafeFilename };
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Fizika Admin Backend running on port ${PORT}`);
|
||||
});
|
||||
|
|
@ -1,156 +0,0 @@
|
|||
const { test, before, after, beforeEach } = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
|
||||
// Point the server at a throwaway data dir before importing it, so tests never
|
||||
// touch real question data.
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "fizika-test-"));
|
||||
const dataPath = path.join(tmpDir, "fizika.json");
|
||||
const picsPath = path.join(tmpDir, "pics");
|
||||
fs.mkdirSync(picsPath, { recursive: true });
|
||||
|
||||
process.env.DATA_PATH = dataPath;
|
||||
process.env.PICS_PATH = picsPath;
|
||||
|
||||
const { app, isUnsafeFilename } = require("./server");
|
||||
|
||||
const seedQuestions = [
|
||||
{
|
||||
id: 1,
|
||||
source: "2016/m1/1",
|
||||
description: "q1",
|
||||
a: "a",
|
||||
b: "b",
|
||||
c: "c",
|
||||
d: "d",
|
||||
correct: 1,
|
||||
type: "mk",
|
||||
image: null,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
source: "2016/m1/2",
|
||||
description: "q2",
|
||||
a: "a",
|
||||
b: "b",
|
||||
c: "c",
|
||||
d: "d",
|
||||
correct: 2,
|
||||
type: "md",
|
||||
image: null,
|
||||
},
|
||||
];
|
||||
|
||||
let server;
|
||||
let baseUrl;
|
||||
|
||||
const api = (route, options) => fetch(`${baseUrl}${route}`, options);
|
||||
const sendJson = (route, method, body) =>
|
||||
api(route, {
|
||||
method,
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
before(async () => {
|
||||
server = app.listen(0);
|
||||
await new Promise((resolve) => server.once("listening", resolve));
|
||||
baseUrl = `http://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
server.close();
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fs.writeFileSync(dataPath, JSON.stringify(seedQuestions, null, 2));
|
||||
});
|
||||
|
||||
test("GET /api/fizika returns every question", async () => {
|
||||
const res = await api("/api/fizika");
|
||||
assert.equal(res.status, 200);
|
||||
const body = await res.json();
|
||||
assert.equal(body.length, 2);
|
||||
});
|
||||
|
||||
test("POST creates a question with an incremented id", async () => {
|
||||
const res = await sendJson("/api/admin/questions", "POST", {
|
||||
source: "2020/1/1",
|
||||
description: "new",
|
||||
a: "a",
|
||||
b: "b",
|
||||
c: "c",
|
||||
d: "d",
|
||||
correct: 3,
|
||||
type: "h",
|
||||
image: null,
|
||||
});
|
||||
assert.equal(res.status, 201);
|
||||
const created = await res.json();
|
||||
assert.equal(created.id, 3);
|
||||
|
||||
const all = await (await api("/api/fizika")).json();
|
||||
assert.equal(all.length, 3);
|
||||
});
|
||||
|
||||
test("PUT updates an existing question", async () => {
|
||||
const res = await sendJson("/api/admin/questions/1", "PUT", {
|
||||
description: "updated",
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
const updated = await res.json();
|
||||
assert.equal(updated.description, "updated");
|
||||
// unchanged fields are preserved
|
||||
assert.equal(updated.source, "2016/m1/1");
|
||||
});
|
||||
|
||||
test("PUT returns 404 for a missing question", async () => {
|
||||
const res = await sendJson("/api/admin/questions/999", "PUT", { a: "x" });
|
||||
assert.equal(res.status, 404);
|
||||
});
|
||||
|
||||
test("DELETE removes a question", async () => {
|
||||
const res = await api("/api/admin/questions/1", { method: "DELETE" });
|
||||
assert.equal(res.status, 200);
|
||||
const all = await (await api("/api/fizika")).json();
|
||||
assert.equal(all.length, 1);
|
||||
assert.equal(all[0].id, 2);
|
||||
});
|
||||
|
||||
test("DELETE returns 404 for a missing question", async () => {
|
||||
const res = await api("/api/admin/questions/999", { method: "DELETE" });
|
||||
assert.equal(res.status, 404);
|
||||
});
|
||||
|
||||
test("DELETE image rejects an unsafe filename", async () => {
|
||||
// Percent-encoded so the path survives client-side URL normalization and
|
||||
// reaches the route with a separator the guard must reject.
|
||||
const res = await api(`/api/admin/images/${encodeURIComponent("a\\b")}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
assert.equal(res.status, 400);
|
||||
});
|
||||
|
||||
test("DELETE image returns 404 for a missing but valid filename", async () => {
|
||||
const res = await api("/api/admin/images/nope.png", { method: "DELETE" });
|
||||
assert.equal(res.status, 404);
|
||||
});
|
||||
|
||||
test("unknown routes return 404 JSON", async () => {
|
||||
const res = await api("/api/does-not-exist");
|
||||
assert.equal(res.status, 404);
|
||||
const body = await res.json();
|
||||
assert.equal(body.error, "Not found");
|
||||
});
|
||||
|
||||
test("isUnsafeFilename blocks traversal but allows plain names", () => {
|
||||
for (const bad of ["../etc", "a/b", "a\\b", "..", ".", "/abs.png", ""]) {
|
||||
assert.equal(isUnsafeFilename(bad), true, `${bad} should be unsafe`);
|
||||
}
|
||||
for (const ok of ["pic.png", "image_1.jpg", "2016-m1-1.png"]) {
|
||||
assert.equal(isUnsafeFilename(ok), false, `${ok} should be safe`);
|
||||
}
|
||||
});
|
||||
|
|
@ -1,32 +1,31 @@
|
|||
.button {
|
||||
font-family: "Roboto", serif;
|
||||
color: #003366;
|
||||
font-weight: 400;
|
||||
font-size: 1.5em;
|
||||
padding: 0.75em;
|
||||
margin: 1em;
|
||||
width: auto;
|
||||
cursor: pointer;
|
||||
background-color: rgba(0, 0, 0, 0);
|
||||
display: inline-block;
|
||||
border-style: solid;
|
||||
border-width: 3px;
|
||||
border-color: #003366;
|
||||
box-shadow:
|
||||
0 8px 16px 0 rgba(0, 0, 0, 0.15),
|
||||
0 6px 20px 0 rgba(0, 0, 0, 0.15);
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
font-family: "Roboto", serif;
|
||||
color: #003366;
|
||||
font-weight: 400;
|
||||
font-size: 1.5em;
|
||||
padding: 0.75em;
|
||||
margin: 1em;
|
||||
width: auto;
|
||||
cursor: pointer;
|
||||
background-color: rgba(0,0,0,0);
|
||||
display: inline-block;
|
||||
border-style: solid;
|
||||
border-width: 3px;
|
||||
border-color: #003366;
|
||||
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.15), 0 6px 20px 0 rgba(0,0,0,0.15);
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
.button:hover {
|
||||
box-shadow: none;
|
||||
box-shadow:none;
|
||||
}
|
||||
@media only screen and (max-width: 1000px) {
|
||||
.button {
|
||||
font-size: 1.45em;
|
||||
padding: 0.3em;
|
||||
margin: 0.15em;
|
||||
}
|
||||
@media only screen and (max-width: 1000px){
|
||||
.button {
|
||||
font-size: 1.45em;
|
||||
padding: 0.3em;
|
||||
margin: 0.15em;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,47 +1,45 @@
|
|||
.card {
|
||||
background-color: #fff;
|
||||
padding: 2em;
|
||||
text-align: left;
|
||||
margin: 2em 0em 2em 0em;
|
||||
box-shadow:
|
||||
0 8px 16px 0 rgba(0, 0, 0, 0.5),
|
||||
0 6px 20px 0 rgba(0, 0, 0, 0.09);
|
||||
height: auto;
|
||||
width: auto;
|
||||
overflow: auto;
|
||||
background-color: #fff;
|
||||
padding: 2em;
|
||||
text-align: left;
|
||||
margin: 2em 0em 2em 0em;
|
||||
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.5), 0 6px 20px 0 rgba(0,0,0,0.09);
|
||||
height: auto;
|
||||
width: auto;
|
||||
overflow: auto;
|
||||
}
|
||||
h2 {
|
||||
font-family: "Roboto", sans-serif;
|
||||
font-weight: 300;
|
||||
font-size: 2em;
|
||||
margin: auto;
|
||||
text-align: center;
|
||||
color: #0a0f14;
|
||||
font-family: "Roboto", sans-serif;
|
||||
font-weight: 300;
|
||||
font-size: 2em;
|
||||
margin: auto;
|
||||
text-align: center;
|
||||
color: #0A0F14;
|
||||
}
|
||||
pre {
|
||||
text-align: justify;
|
||||
font-family: "Open sans", sans-serif;
|
||||
font-weight: 300;
|
||||
font-size: 1.5em;
|
||||
white-space: normal;
|
||||
width: 100%;
|
||||
text-align: justify;
|
||||
font-family: "Open sans", sans-serif;
|
||||
font-weight: 300;
|
||||
font-size: 1.5em;
|
||||
white-space: normal;
|
||||
width: 100%;
|
||||
}
|
||||
img {
|
||||
display: block;
|
||||
max-height: 100%;
|
||||
float: right;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
margin: 1px;
|
||||
max-width: 500px;
|
||||
display: block;
|
||||
max-height: 100%;
|
||||
float: right;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
margin: 1px;
|
||||
max-width: 500px;
|
||||
}
|
||||
@media only screen and (max-width: 1000px) {
|
||||
h2 {
|
||||
@media only screen and (max-width: 1000px){
|
||||
h2 {
|
||||
font-size: 1.6em;
|
||||
}
|
||||
pre {
|
||||
}
|
||||
pre {
|
||||
font-size: 1em;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,276 +1,268 @@
|
|||
body {
|
||||
font-size: 1em;
|
||||
text-align: center;
|
||||
color: #003366;
|
||||
background-image: url("../auxIMG/bg.jpg");
|
||||
background-color: #fff;
|
||||
background-repeat: repeat;
|
||||
word-wrap: break-word;
|
||||
margin-bottom: 1em;
|
||||
body {
|
||||
font-size: 1em;
|
||||
text-align: center;
|
||||
color: #003366;
|
||||
background-image: url("../auxIMG/bg.jpg");
|
||||
background-color: #fff;
|
||||
background-repeat: repeat;
|
||||
word-wrap: break-word;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
::-moz-selection {
|
||||
background: #003366;
|
||||
color: #fff;
|
||||
text-shadow: none;
|
||||
background: #003366;
|
||||
color: #fff;
|
||||
text-shadow: none;
|
||||
}
|
||||
::selection {
|
||||
background: #003366;
|
||||
color: #fff;
|
||||
text-shadow: none;
|
||||
background: #003366;
|
||||
color: #fff;
|
||||
text-shadow: none;
|
||||
}
|
||||
h1:hover {
|
||||
text-shadow:
|
||||
0.3px 0.3px #002d5b,
|
||||
0.6px 0.6px #002851,
|
||||
1px 1px #002347,
|
||||
1.3px 1.3px #001e3d,
|
||||
1.6px 1.6px #001933,
|
||||
2px 2px #001326,
|
||||
2.3px 2.3px #000e1c,
|
||||
2.6px 2.6px #000a14,
|
||||
3px 3px #00070f,
|
||||
3.3px 3.3px #00050a,
|
||||
3.6px 3.6px #000205,
|
||||
4px 4px #000000;
|
||||
text-shadow: 0.3px 0.3px #002D5B,
|
||||
0.6px 0.6px #002851,
|
||||
1px 1px #002347,
|
||||
1.3px 1.3px #001E3D,
|
||||
1.6px 1.6px #001933,
|
||||
2px 2px #001326,
|
||||
2.3px 2.3px #000E1C,
|
||||
2.6px 2.6px #000A14,
|
||||
3px 3px #00070F,
|
||||
3.3px 3.3px #00050A,
|
||||
3.6px 3.6px #000205,
|
||||
4px 4px #000000;
|
||||
}
|
||||
h1 {
|
||||
font-family: "Poiret One", "Montserrat", serif;
|
||||
font-size: 5em;
|
||||
text-align: center;
|
||||
margin: 0.2em 0 0.3em 0;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
display: inline;
|
||||
transition: all 0.6s ease-out;
|
||||
font-family: "Poiret One", "Montserrat", serif;
|
||||
font-size: 5em;
|
||||
text-align: center;
|
||||
margin: 0.2em 0 0.3em 0;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
display: inline;
|
||||
transition: all 0.6s ease-out;
|
||||
}
|
||||
#titlebox {
|
||||
padding-bottom: 0.5em;
|
||||
padding-bottom: 0.5em;
|
||||
}
|
||||
hr {
|
||||
border-bottom: 2px solid #003366;
|
||||
width: 35%;
|
||||
border-bottom: 2px solid #003366;
|
||||
width: 35%;
|
||||
}
|
||||
.menu {
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
margin: auto;
|
||||
font-weight: 400;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
margin: auto;
|
||||
font-weight: 400;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
ul {
|
||||
list-style-type: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style-type: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
li {
|
||||
font-family: "Roboto", serif;
|
||||
font-weight: 300;
|
||||
display: inline-block;
|
||||
padding: 0.5em 1em;
|
||||
font-size: 1.5em;
|
||||
font-family: "Roboto", serif;
|
||||
font-weight: 300;
|
||||
display: inline-block;
|
||||
padding: 0.5em 1em;
|
||||
font-size: 1.5em;
|
||||
}
|
||||
li:hover {
|
||||
cursor: pointer;
|
||||
text-shadow: 1px 1px 1px #0a0f14;
|
||||
cursor: pointer;
|
||||
text-shadow: 1px 1px 1px #0A0F14;
|
||||
}
|
||||
#wrapper {
|
||||
width: 75%;
|
||||
margin: auto;
|
||||
padding-top: 0.5em;
|
||||
width: 75%;
|
||||
margin: auto;
|
||||
padding-top: 0.5em;
|
||||
}
|
||||
#bfooldal {
|
||||
font-weight: 700;
|
||||
font-weight: 700;
|
||||
}
|
||||
.szoveg,
|
||||
#buttonwrapper {
|
||||
width: 80%;
|
||||
margin: auto;
|
||||
.szoveg, #buttonwrapper {
|
||||
width: 80%;
|
||||
margin: auto;
|
||||
}
|
||||
p:first-of-type {
|
||||
padding-top: 2em;
|
||||
padding-top: 2em;
|
||||
}
|
||||
p {
|
||||
font-family: "Open sans", sans-serif;
|
||||
font-weight: 300;
|
||||
font-size: 1.3em;
|
||||
color: #0a0f14;
|
||||
text-align: justify;
|
||||
margin: auto;
|
||||
padding: 0.5em 0;
|
||||
font-family: "Open sans", sans-serif;
|
||||
font-weight: 300;
|
||||
font-size: 1.3em;
|
||||
color: #0A0F14;
|
||||
text-align: justify;
|
||||
margin: auto;
|
||||
padding: 0.5em 0;
|
||||
}
|
||||
p:last-of-type {
|
||||
padding-bottom: 2em;
|
||||
padding-bottom: 2em;
|
||||
}
|
||||
.buttonwrapper {
|
||||
text-align: center;
|
||||
text-align: center;
|
||||
}
|
||||
#teszt,
|
||||
#eredmenyek,
|
||||
#kereses,
|
||||
#temakor {
|
||||
display: none;
|
||||
#teszt, #eredmenyek, #kereses, #temakor {
|
||||
display: none;
|
||||
}
|
||||
#temak {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
text-align: left;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
text-align: left;
|
||||
}
|
||||
.fele {
|
||||
width: 40%;
|
||||
display: block;
|
||||
width: 40%;
|
||||
display: block;
|
||||
}
|
||||
#bal {
|
||||
float: left;
|
||||
margin-left: 20%;
|
||||
float: left;
|
||||
margin-left: 20%;
|
||||
}
|
||||
#jobb {
|
||||
float: right;
|
||||
float: right;
|
||||
}
|
||||
.negyzet {
|
||||
margin-left: 1.5em;
|
||||
font-family: "Open sans", sans-serif;
|
||||
font-weight: 400;
|
||||
margin-left: 1.5em;
|
||||
font-family: "Open sans", sans-serif;
|
||||
font-weight: 400;
|
||||
}
|
||||
.main {
|
||||
font-size: 1.5em;
|
||||
margin-left: 0;
|
||||
font-family: "Roboto", serif;
|
||||
font-size: 1.5em;
|
||||
margin-left: 0;
|
||||
font-family: "Roboto", serif;
|
||||
}
|
||||
#numberof {
|
||||
box-sizing: border-box;
|
||||
border: 2px solid #ccc;
|
||||
border-radius: 4px;
|
||||
font-size: 1.2em;
|
||||
font-weight: 300;
|
||||
background-color: white;
|
||||
width: 63%;
|
||||
box-sizing: border-box;
|
||||
border: 2px solid #ccc;
|
||||
border-radius: 4px;
|
||||
font-size: 1.2em;
|
||||
font-weight: 300;
|
||||
background-color: white;
|
||||
width: 63%;
|
||||
}
|
||||
.f2006,
|
||||
.f2016 {
|
||||
display: none;
|
||||
.f2006, .f2016 {
|
||||
display: none;
|
||||
}
|
||||
#load,
|
||||
#loadingGif {
|
||||
display: none;
|
||||
#load, #loadingGif {
|
||||
display: none;
|
||||
}
|
||||
#loading {
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
height: auto;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
height: auto;
|
||||
}
|
||||
#loadingGif {
|
||||
float: none;
|
||||
margin: auto;
|
||||
padding-bottom: 2em;
|
||||
float: none;
|
||||
margin: auto;
|
||||
padding-bottom: 2em;
|
||||
}
|
||||
#megoldas {
|
||||
display: none;
|
||||
display: none;
|
||||
}
|
||||
#percentage {
|
||||
font-family: "Poiret One", "Montserrat", serif;
|
||||
font-size: 3em;
|
||||
text-align: center;
|
||||
font-family: "Poiret One", "Montserrat", serif;
|
||||
font-size: 3em;
|
||||
text-align: center;
|
||||
}
|
||||
#state,
|
||||
#state2 {
|
||||
font-weight: 300;
|
||||
font-size: 2em;
|
||||
text-align: center;
|
||||
padding: 0.6em;
|
||||
#state, #state2 {
|
||||
font-weight: 300;
|
||||
font-size: 2em;
|
||||
text-align: center;
|
||||
padding: 0.6em;
|
||||
}
|
||||
#content {
|
||||
margin: auto;
|
||||
margin: auto;
|
||||
}
|
||||
select {
|
||||
box-sizing: border-box;
|
||||
border: 2px solid #ccc;
|
||||
border-radius: 4px;
|
||||
font-size: 1.25em;
|
||||
color: #0a0f14;
|
||||
width: 26%;
|
||||
padding: 12px 20px 12px 40px;
|
||||
background-color: #fff;
|
||||
box-sizing: border-box;
|
||||
border: 2px solid #ccc;
|
||||
border-radius: 4px;
|
||||
font-size: 1.25em;
|
||||
color: #0A0F14;
|
||||
width: 26%;
|
||||
padding: 12px 20px 12px 40px;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
margin: auto;
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin : auto;
|
||||
width: 100%;
|
||||
}
|
||||
th,
|
||||
td {
|
||||
text-align: left;
|
||||
padding: 0.5em;
|
||||
th, td {
|
||||
text-align: left;
|
||||
padding: 0.5em;
|
||||
}
|
||||
tr:nth-child(even) {
|
||||
background-color: #f2f2f2;
|
||||
tr:nth-child(even){
|
||||
background-color: #f2f2f2;
|
||||
}
|
||||
th {
|
||||
background-color: #003366;
|
||||
color: white;
|
||||
background-color: #003366;
|
||||
color: white;
|
||||
}
|
||||
|
||||
h4 {
|
||||
margin: auto;
|
||||
font-size: 0.75em;
|
||||
margin: auto;
|
||||
font-size: 0.75em;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 1000px) {
|
||||
body {
|
||||
font-size: 1.75em;
|
||||
}
|
||||
h1 {
|
||||
font-size: 7em;
|
||||
}
|
||||
h1:hover {
|
||||
text-shadow: none;
|
||||
}
|
||||
#wrapper {
|
||||
width: 90%;
|
||||
}
|
||||
.szoveg {
|
||||
width: 90%;
|
||||
}
|
||||
#numberof {
|
||||
font-size: 0.6em;
|
||||
}
|
||||
img {
|
||||
max-width: 400px;
|
||||
}
|
||||
select {
|
||||
font-size: 0.8em;
|
||||
width: 30%;
|
||||
}
|
||||
hr {
|
||||
border-bottom-width: 4px;
|
||||
width: 50%;
|
||||
}
|
||||
li {
|
||||
font-size: 1.75em;
|
||||
padding: 0.25em;
|
||||
}
|
||||
p {
|
||||
font-size: 0.75em;
|
||||
}
|
||||
p:first-of-type {
|
||||
padding-top: 0.5em;
|
||||
}
|
||||
p:last-of-type {
|
||||
padding-bottom: 0.5em;
|
||||
}
|
||||
@media only screen and (max-width: 1000px){
|
||||
body {
|
||||
font-size: 1.75em;
|
||||
}
|
||||
h1 {
|
||||
font-size: 7em;
|
||||
}
|
||||
h1:hover {
|
||||
text-shadow: none;
|
||||
}
|
||||
#wrapper {
|
||||
width: 90%;
|
||||
}
|
||||
.szoveg {
|
||||
width: 90%;
|
||||
}
|
||||
#numberof {
|
||||
font-size: 0.6em;
|
||||
}
|
||||
img {
|
||||
max-width: 400px;
|
||||
}
|
||||
select {
|
||||
font-size: 0.8em;
|
||||
width: 30%;
|
||||
}
|
||||
hr {
|
||||
border-bottom-width: 4px;
|
||||
width: 50%;
|
||||
}
|
||||
li {
|
||||
font-size: 1.75em;
|
||||
padding: 0.25em;
|
||||
}
|
||||
p {
|
||||
font-size: 0.75em;
|
||||
}
|
||||
p:first-of-type {
|
||||
padding-top: 0.5em;
|
||||
}
|
||||
p:last-of-type {
|
||||
padding-bottom: 0.5em;
|
||||
}
|
||||
|
||||
#tablazat {
|
||||
font-size: 0.8em;
|
||||
}
|
||||
.mbcheck {
|
||||
font-size: 0.75em;
|
||||
}
|
||||
#bal {
|
||||
margin-left: 0;
|
||||
}
|
||||
#tablazat {
|
||||
font-size: 0.8em;
|
||||
}
|
||||
.mbcheck {
|
||||
font-size: 0.75em;
|
||||
}
|
||||
#bal {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,44 +1,44 @@
|
|||
#preload {
|
||||
display: none;
|
||||
display: none;
|
||||
}
|
||||
|
||||
input[type="radio"] {
|
||||
cursor: pointer;
|
||||
input[type=radio] {
|
||||
cursor: pointer;
|
||||
}
|
||||
input[type="radio"] {
|
||||
width: 28px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
opacity: 0;
|
||||
input[type=radio] {
|
||||
width: 28px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
opacity: 0;
|
||||
}
|
||||
input[type="radio"] + label {
|
||||
display: inline;
|
||||
font-family: "Open Sans", sans-serif;
|
||||
font-weight: 300;
|
||||
font-size: 1.3em;
|
||||
margin-left: -28px;
|
||||
padding-left: 28px;
|
||||
background: url("../auxIMG/unchecked.svg") no-repeat 0 50%;
|
||||
line-height: 35px;
|
||||
background-size: 28px 28px;
|
||||
margin-bottom: 6.25em;
|
||||
input[type=radio] + label {
|
||||
display: inline;
|
||||
font-family: "Open Sans", sans-serif;
|
||||
font-weight: 300;
|
||||
font-size: 1.3em;
|
||||
margin-left: -28px;
|
||||
padding-left: 28px;
|
||||
background: url('../auxIMG/unchecked.svg') no-repeat 0 50%;
|
||||
line-height: 35px;
|
||||
background-size: 28px 28px;
|
||||
margin-bottom: 6.25em;
|
||||
}
|
||||
input[type="radio"]:checked + label {
|
||||
background: url("../auxIMG/checked.svg") no-repeat 0 50%;
|
||||
background-size: 28px 28px;
|
||||
input[type=radio]:checked + label {
|
||||
background: url('../auxIMG/checked.svg') no-repeat 0 50%;
|
||||
background-size: 28px 28px;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 1000px) {
|
||||
input[type="radio"] {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
}
|
||||
input[type="radio"] + label {
|
||||
margin-left: -60px;
|
||||
padding-left: 60px;
|
||||
background-size: 60px 60px;
|
||||
}
|
||||
input[type="radio"]:checked + label {
|
||||
background-size: 60px 60px;
|
||||
}
|
||||
@media only screen and (max-width: 1000px){
|
||||
input[type=radio] {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
}
|
||||
input[type=radio] + label {
|
||||
margin-left: -60px;
|
||||
padding-left: 60px;
|
||||
background-size: 60px 60px;
|
||||
}
|
||||
input[type=radio]:checked + label {
|
||||
background-size: 60px 60px;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +1,19 @@
|
|||
{
|
||||
"name": "Fizika",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicons/android-chrome-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "favicons/android-chrome-384x384.png",
|
||||
"sizes": "384x384",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"theme_color": "#ffffff",
|
||||
"background_color": "#ffffff",
|
||||
"display": "standalone",
|
||||
"orientation": "portrait"
|
||||
"name": "Fizika",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicons/android-chrome-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "favicons/android-chrome-384x384.png",
|
||||
"sizes": "384x384",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"theme_color": "#ffffff",
|
||||
"background_color": "#ffffff",
|
||||
"display": "standalone",
|
||||
"orientation": "portrait"
|
||||
}
|
||||
8186
frontend/fizika.json
Normal file
8186
frontend/fizika.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,4 +1,4 @@
|
|||
<!doctype html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="hu-HU">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
|
|
@ -92,14 +92,10 @@
|
|||
<p>
|
||||
A Tesztek fülre kattintva juthatsz el a gyakorló feladatlapokig,
|
||||
amiket <b>a te beállításaid alapján</b> állít össze az alkalmazás. Ezt
|
||||
egy
|
||||
<b
|
||||
><span id="questionCount">682</span> kérdést tartalmazó
|
||||
adatbázisból</b
|
||||
>
|
||||
viszi véghez, melyet az előző <b>több mint 10 év</b> érettségijeinek
|
||||
feladatai alkotnak. Ebben a menüpontban nem csak témakör, hanem év
|
||||
alapján is <b>rákereshetsz a feladatokra</b>.
|
||||
egy <b>659 kérdést tartalmazó adatbázisból</b> viszi véghez, melyet az
|
||||
előző <b>több mint 10 év</b> érettségijeinek feladatai alkotnak. Ebben
|
||||
a menüpontban nem csak témakör, hanem év alapján is
|
||||
<b>rákereshetsz a feladatokra</b>.
|
||||
</p>
|
||||
<p>
|
||||
A teszteken elért pontjaidat, és azokkal kapcsolatos egyéb infókat, az
|
||||
|
|
|
|||
|
|
@ -29,13 +29,10 @@ async function ajaxLoad(type) {
|
|||
try {
|
||||
if (type == 1) {
|
||||
var source =
|
||||
"^" +
|
||||
$("#evszam").val() +
|
||||
$("#honap").val() +
|
||||
$("#feladat").val() +
|
||||
"$";
|
||||
"^" + $("#evszam").val() + $("#honap").val() + $("#feladat").val() + "$";
|
||||
for (var i = 0; i <= 3; i++) {
|
||||
source = source.replace("all", ".*");
|
||||
console.log(source);
|
||||
}
|
||||
result = await loadQuestions(true, undefined, source, 1000000);
|
||||
} else if (type == 2) {
|
||||
|
|
@ -59,7 +56,7 @@ async function ajaxLoad(type) {
|
|||
"v",
|
||||
],
|
||||
undefined,
|
||||
15,
|
||||
15
|
||||
);
|
||||
} else {
|
||||
var NOQ = $("#numberof").val() ? $("#numberof").val() : 15;
|
||||
|
|
@ -112,7 +109,7 @@ async function ajaxLoad(type) {
|
|||
</div>
|
||||
`);
|
||||
$("#state").html("Hiba a feladatok betöltésekor");
|
||||
console.error("Quiz loading error:", error);
|
||||
console.error('Quiz loading error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -120,15 +117,15 @@ function showCorrect(id, correctAns) {
|
|||
teszt(id, correctAns);
|
||||
eval(
|
||||
"$('" +
|
||||
"#label" +
|
||||
id +
|
||||
".rad" +
|
||||
correctAns +
|
||||
"').css('background-color', '#C6FF8C');",
|
||||
"#label" +
|
||||
id +
|
||||
".rad" +
|
||||
correctAns +
|
||||
"').css('background-color', '#C6FF8C');"
|
||||
);
|
||||
$("#state").html("Helyes válaszok bejelölve!");
|
||||
$("#state2").html(
|
||||
"(Ellenőrző mód, az itteni eredményeid nem kerülnek elmentésre, a módból való kilépéshez tölts be egy új tesztsort!)",
|
||||
"(Ellenőrző mód, az itteni eredményeid nem kerülnek elmentésre, a módból való kilépéshez tölts be egy új tesztsort!)"
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -143,6 +140,7 @@ function teszt(id, correctAns) {
|
|||
} else {
|
||||
$(div).animate({ backgroundColor: "#FF808C" }, 1100);
|
||||
}
|
||||
console.log(currentPoints, totalPoints, correctAnswersGiven);
|
||||
if (currentPoints >= totalPoints) {
|
||||
var percentage = (correctAnswersGiven / totalPoints) * 100;
|
||||
percentage = Math.round(percentage * 100) / 100;
|
||||
|
|
@ -153,34 +151,30 @@ function teszt(id, correctAns) {
|
|||
var datum = new Date();
|
||||
var ido = Math.round(timer / 60);
|
||||
eval(
|
||||
"localStorage.teszt" +
|
||||
numberOfPreviousTests +
|
||||
" = '" +
|
||||
percentage +
|
||||
"'",
|
||||
"localStorage.teszt" + numberOfPreviousTests + " = '" + percentage + "'"
|
||||
);
|
||||
eval(
|
||||
"localStorage.teszt" +
|
||||
numberOfPreviousTests +
|
||||
"date = '" +
|
||||
datum.toLocaleDateString() +
|
||||
"'",
|
||||
numberOfPreviousTests +
|
||||
"date = '" +
|
||||
datum.toLocaleDateString() +
|
||||
"'"
|
||||
);
|
||||
eval(
|
||||
"localStorage.teszt" + numberOfPreviousTests + "time = '" + ido + "'",
|
||||
"localStorage.teszt" + numberOfPreviousTests + "time = '" + ido + "'"
|
||||
);
|
||||
eval(
|
||||
"localStorage.teszt" +
|
||||
numberOfPreviousTests +
|
||||
"total = '" +
|
||||
totalPoints +
|
||||
"'",
|
||||
numberOfPreviousTests +
|
||||
"total = '" +
|
||||
totalPoints +
|
||||
"'"
|
||||
);
|
||||
startTimer = 0;
|
||||
timer = 0;
|
||||
$("#state2").show();
|
||||
$("#state2").html(
|
||||
"Eredményed mentésre került! Ellenőrző módba belépve az eredményeid nem kerülnek tárolásra. A módból való kilépéshez tölts be egy új tesztsort!",
|
||||
"Eredményed mentésre került! Ellenőrző módba belépve az eredményeid nem kerülnek tárolásra. A módból való kilépéshez tölts be egy új tesztsort!"
|
||||
);
|
||||
eredmeny();
|
||||
reviewMode = 1;
|
||||
|
|
@ -195,7 +189,7 @@ function scrollTo(where) {
|
|||
{
|
||||
scrollTop: $(where).offset().top - 100,
|
||||
},
|
||||
1000,
|
||||
1000
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -214,7 +208,7 @@ function eredmeny() {
|
|||
if (isLocal) {
|
||||
if (typeof localStorage.teszt1 !== "undefined") {
|
||||
$("#tablazat").html(
|
||||
'<table id="ered"><tr><th></th><th>Dátum</th><th>Időtartam</th><th>Eredmény</th><th>Pontszám</th></tr></table>',
|
||||
'<table id="ered"><tr><th></th><th>Dátum</th><th>Időtartam</th><th>Eredmény</th><th>Pontszám</th></tr></table>'
|
||||
);
|
||||
for (var i = 1; i < numberOfPreviousTests; i++) {
|
||||
var localString = "localStorage.teszt" + i;
|
||||
|
|
@ -224,21 +218,21 @@ function eredmeny() {
|
|||
var isGood = eval(localString);
|
||||
$("#ered tr:last").after(
|
||||
"<tr><td>" +
|
||||
i +
|
||||
".</td><td>" +
|
||||
eval(datumString) +
|
||||
"</td><td>" +
|
||||
eval(timeString) +
|
||||
" perc</td>" +
|
||||
"<td style='color: hsl(" +
|
||||
isGood +
|
||||
",100%,50%);''> <b>" +
|
||||
eval(localString) +
|
||||
"%</b></td><td>" +
|
||||
Math.round((eval(localString) * eval(totalString)) / 100) +
|
||||
"/" +
|
||||
eval(totalString) +
|
||||
" pont</td></tr>",
|
||||
i +
|
||||
".</td><td>" +
|
||||
eval(datumString) +
|
||||
"</td><td>" +
|
||||
eval(timeString) +
|
||||
" perc</td>" +
|
||||
"<td style='color: hsl(" +
|
||||
isGood +
|
||||
",100%,50%);''> <b>" +
|
||||
eval(localString) +
|
||||
"%</b></td><td>" +
|
||||
Math.round((eval(localString) * eval(totalString)) / 100) +
|
||||
"/" +
|
||||
eval(totalString) +
|
||||
" pont</td></tr>"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
|
|
@ -246,7 +240,7 @@ function eredmeny() {
|
|||
}
|
||||
} else {
|
||||
$("#tablazat").html(
|
||||
"<h2>Sajnos a böngésződ nem támogatja ezt a funkciót, tölts le egy modernebbet vagy jelentkezz be!</h2>",
|
||||
"<h2>Sajnos a böngésződ nem támogatja ezt a funkciót, tölts le egy modernebbet vagy jelentkezz be!</h2>"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -267,11 +261,11 @@ $(document).ready(function () {
|
|||
eredmeny();
|
||||
|
||||
// Initialize year dropdown with dynamic years from question data
|
||||
if (typeof initializeYearDropdown === "function") {
|
||||
if (typeof initializeYearDropdown === 'function') {
|
||||
initializeYearDropdown().then(() => {
|
||||
// Initialize month dropdown for default "all" year selection
|
||||
if (typeof initializeMonthDropdown === "function") {
|
||||
initializeMonthDropdown("all/");
|
||||
if (typeof initializeMonthDropdown === 'function') {
|
||||
initializeMonthDropdown('all/');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -336,7 +330,7 @@ $(document).ready(function () {
|
|||
const selectedYear = $("#evszam").val();
|
||||
|
||||
// Initialize month dropdown dynamically based on selected year
|
||||
if (typeof initializeMonthDropdown === "function") {
|
||||
if (typeof initializeMonthDropdown === 'function') {
|
||||
initializeMonthDropdown(selectedYear);
|
||||
} else {
|
||||
// Fallback to original logic if dynamic function not available
|
||||
|
|
@ -396,7 +390,7 @@ $(document).ready(function () {
|
|||
{
|
||||
scrollTop: $("#teszt").offset().top,
|
||||
},
|
||||
3000,
|
||||
3000
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -425,28 +419,28 @@ $(document).ready(function () {
|
|||
Math.max(
|
||||
Math.min(
|
||||
parseInt(g.pos * (g.end[0] - g.start[0]) + g.start[0]),
|
||||
255,
|
||||
255
|
||||
),
|
||||
0,
|
||||
0
|
||||
),
|
||||
Math.max(
|
||||
Math.min(
|
||||
parseInt(g.pos * (g.end[1] - g.start[1]) + g.start[1]),
|
||||
255,
|
||||
255
|
||||
),
|
||||
0,
|
||||
0
|
||||
),
|
||||
Math.max(
|
||||
Math.min(
|
||||
parseInt(g.pos * (g.end[2] - g.start[2]) + g.start[2]),
|
||||
255,
|
||||
255
|
||||
),
|
||||
0,
|
||||
0
|
||||
),
|
||||
].join(",") +
|
||||
")";
|
||||
};
|
||||
},
|
||||
}
|
||||
);
|
||||
function b(f) {
|
||||
var e;
|
||||
|
|
@ -454,18 +448,16 @@ $(document).ready(function () {
|
|||
return f;
|
||||
}
|
||||
if (
|
||||
(e =
|
||||
/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(
|
||||
f,
|
||||
))
|
||||
(e = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(
|
||||
f
|
||||
))
|
||||
) {
|
||||
return [parseInt(e[1]), parseInt(e[2]), parseInt(e[3])];
|
||||
}
|
||||
if (
|
||||
(e =
|
||||
/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(
|
||||
f,
|
||||
))
|
||||
(e = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(
|
||||
f
|
||||
))
|
||||
) {
|
||||
return [
|
||||
parseFloat(e[1]) * 2.55,
|
||||
|
|
|
|||
|
|
@ -6,69 +6,56 @@ const getApiBase = () => {
|
|||
const hostname = window.location.hostname;
|
||||
|
||||
// If running on localhost, assume backend is on port 3001
|
||||
if (hostname === "localhost" || hostname === "127.0.0.1") {
|
||||
if (hostname === 'localhost' || hostname === '127.0.0.1') {
|
||||
return `${protocol}//${hostname}:3001`;
|
||||
}
|
||||
|
||||
// For production, assume backend is on same origin
|
||||
return "https://fizika-backend.schmelczer.dev";
|
||||
return "https://fizika-backend.schmelczer.dev"
|
||||
};
|
||||
|
||||
const API_BASE = getApiBase();
|
||||
|
||||
// Fetch the question bank from the backend, which is the single source of
|
||||
// truth. Cached after the first successful load.
|
||||
const ensureQuestionsLoaded = async () => {
|
||||
if (questions !== null) return questions;
|
||||
|
||||
const response = await fetch(`${API_BASE}/api/fizika`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
questions = await response.json();
|
||||
return questions;
|
||||
};
|
||||
|
||||
const escapeHtml = (value) =>
|
||||
String(value).replace(
|
||||
/[&<>"']/g,
|
||||
(ch) =>
|
||||
({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
})[ch],
|
||||
);
|
||||
|
||||
// Question text is trusted but contains light markup (<sub>, <sup>, <br>) and
|
||||
// pre-encoded entities. Escape everything first, then restore only that
|
||||
// allowlist, so any other injected markup (e.g. <script>) stays inert.
|
||||
const sanitizeQuestionHtml = (value) =>
|
||||
escapeHtml(value)
|
||||
.replace(/<(\/?)(sub|sup)>/g, "<$1$2>")
|
||||
.replace(/<br\s*\/?>/g, "<br>")
|
||||
.replace(/&(lt|gt|amp|quot|#\d+|#x[0-9a-fA-F]+);/g, "&$1;");
|
||||
|
||||
const loadQuestions = async (
|
||||
isSearch,
|
||||
categories,
|
||||
sourceScheme,
|
||||
questionCount,
|
||||
questionCount
|
||||
) => {
|
||||
await ensureQuestionsLoaded();
|
||||
if (questions === null) {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/fizika`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
questions = await response.json();
|
||||
console.log('Questions loaded from backend API');
|
||||
} catch (error) {
|
||||
console.warn('Failed to load questions from API, falling back to local file:', error);
|
||||
try {
|
||||
const fallbackResponse = await fetch("fizika.json");
|
||||
if (!fallbackResponse.ok) {
|
||||
throw new Error(`Local file not available: ${fallbackResponse.status}`);
|
||||
}
|
||||
questions = await fallbackResponse.json();
|
||||
console.log('Questions loaded from local fallback file');
|
||||
} catch (fallbackError) {
|
||||
console.error('Both API and local file failed:', fallbackError);
|
||||
throw new Error('Unable to load quiz data from either backend API or local file');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let currentQuestions = questions.slice();
|
||||
|
||||
if (isSearch) {
|
||||
currentQuestions = currentQuestions.filter((q) =>
|
||||
q.source.match(sourceScheme),
|
||||
q.source.match(sourceScheme)
|
||||
);
|
||||
} else {
|
||||
shuffleArray(currentQuestions);
|
||||
currentQuestions = currentQuestions.filter((q) =>
|
||||
categories.includes(q.type),
|
||||
categories.includes(q.type)
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -77,49 +64,45 @@ const loadQuestions = async (
|
|||
currentQuestions = currentQuestions.slice(0, questionCount);
|
||||
currentQuestions.forEach(
|
||||
({ id, source, description, a, b, c, d, correct, image }, i) => {
|
||||
const qid = Number(id);
|
||||
const correctAnswer = Number(correct);
|
||||
const safeImage = image ? encodeURIComponent(image) : "";
|
||||
resultHtml += `
|
||||
<div class="feladat card" id="feladat${qid}">
|
||||
<h2 style="float: left;">${i + 1}.</h2><h2>${sanitizeQuestionHtml(source)}</h2>
|
||||
<pre>${sanitizeQuestionHtml(description)}</pre>
|
||||
${image ? `<img src="${API_BASE}/api/pics/${safeImage}" crossorigin="anonymous" onerror="this.src='pics/${safeImage}'"><br>` : ""}
|
||||
<form id="form${qid}">
|
||||
<div class="feladat card" id="feladat${id}">
|
||||
<h2 style="float: left;">${i + 1}.</h2><h2>${source}</h2>
|
||||
<pre>${description}</pre>
|
||||
${image ? `<img src="${API_BASE}/api/pics/${image}" crossorigin="anonymous" onerror="this.src='pics/${image}'"><br>` : ""}
|
||||
<form id="form${id}"">
|
||||
<input type="radio" id="rad1" name="group">
|
||||
<label id="label${qid}" class="rad1">${sanitizeQuestionHtml(a)}</label>
|
||||
<label id="label${id}" class="rad1">${a}</label>
|
||||
<br>
|
||||
<input type="radio" id="rad2" name="group">
|
||||
<label id="label${qid}" class="rad2">${sanitizeQuestionHtml(b)}</label>
|
||||
<label id="label${id}" class="rad2">${b}</label>
|
||||
<br>
|
||||
<input type="radio" id="rad3" name="group">
|
||||
<label id="label${qid}" class="rad3">${sanitizeQuestionHtml(c)}</label>
|
||||
<label id="label${id}" class="rad3">${c}</label>
|
||||
<br>
|
||||
${
|
||||
d
|
||||
? `
|
||||
${d
|
||||
? `
|
||||
<input type="radio" id="rad4" name="group">
|
||||
<label id="label${qid}" class="rad4">${sanitizeQuestionHtml(d)}</label>
|
||||
<label id="label${id}" class="rad4">${d}</label>
|
||||
<br>`
|
||||
: ""
|
||||
}
|
||||
: ""
|
||||
}
|
||||
</form>
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function(){
|
||||
totalPoints++;
|
||||
$("#ans").click(function(event){
|
||||
event.preventDefault();
|
||||
teszt(${qid}, ${correctAnswer});
|
||||
teszt(${id}, ${correct});
|
||||
});
|
||||
$("#cAns").click(function(event){
|
||||
event.preventDefault();
|
||||
showCorrect(${qid}, ${correctAnswer});
|
||||
showCorrect(${id}, ${correct});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
resultHtml +=
|
||||
|
|
@ -143,15 +126,34 @@ function shuffleArray(array) {
|
|||
// Initialize year dropdown with dynamic years from question data
|
||||
const initializeYearDropdown = async () => {
|
||||
try {
|
||||
await ensureQuestionsLoaded();
|
||||
|
||||
// Reflect the live question count on the info page.
|
||||
const countEl = document.getElementById("questionCount");
|
||||
if (countEl) countEl.textContent = questions.length;
|
||||
// Load questions if not already loaded
|
||||
if (questions === null) {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/fizika`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
questions = await response.json();
|
||||
console.log('Questions loaded for year dropdown initialization');
|
||||
} catch (error) {
|
||||
console.warn('Failed to load questions from API, falling back to local file:', error);
|
||||
try {
|
||||
const fallbackResponse = await fetch("fizika.json");
|
||||
if (!fallbackResponse.ok) {
|
||||
throw new Error(`Local file not available: ${fallbackResponse.status}`);
|
||||
}
|
||||
questions = await fallbackResponse.json();
|
||||
console.log('Questions loaded from local fallback file for year dropdown');
|
||||
} catch (fallbackError) {
|
||||
console.error('Both API and local file failed:', fallbackError);
|
||||
return; // Don't update dropdown if data unavailable
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract unique years from question sources
|
||||
const yearSet = new Set();
|
||||
questions.forEach((q) => {
|
||||
questions.forEach(q => {
|
||||
const yearMatch = q.source.match(/^(\d{4})\//);
|
||||
if (yearMatch) {
|
||||
yearSet.add(parseInt(yearMatch[1]));
|
||||
|
|
@ -162,18 +164,21 @@ const initializeYearDropdown = async () => {
|
|||
const uniqueYears = Array.from(yearSet).sort((a, b) => b - a);
|
||||
|
||||
// Get existing dropdown
|
||||
const yearDropdown = document.getElementById("evszam");
|
||||
const yearDropdown = document.getElementById('evszam');
|
||||
if (!yearDropdown) return;
|
||||
|
||||
// Preserve the "Összes év" option and add dynamic years
|
||||
const allYearsOption = '<option value="all/">Összes év</option>';
|
||||
const yearOptions = uniqueYears
|
||||
.map((year) => `<option value="${year}/">${year}</option>`)
|
||||
.join("");
|
||||
const yearOptions = uniqueYears.map(year =>
|
||||
`<option value="${year}/">${year}</option>`
|
||||
).join('');
|
||||
|
||||
yearDropdown.innerHTML = allYearsOption + yearOptions;
|
||||
|
||||
console.log('Year dropdown initialized with years:', uniqueYears);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize year dropdown:", error);
|
||||
console.error('Failed to initialize year dropdown:', error);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -181,16 +186,16 @@ const initializeYearDropdown = async () => {
|
|||
const initializeMonthDropdown = (selectedYear) => {
|
||||
if (!questions) return;
|
||||
|
||||
const monthDropdown = document.getElementById("honap");
|
||||
const monthDropdown = document.getElementById('honap');
|
||||
if (!monthDropdown) return;
|
||||
|
||||
// Always include "Összes feladatsora" option
|
||||
let monthOptions = '<option value="all">Összes feladatsora</option>';
|
||||
|
||||
if (selectedYear === "all/") {
|
||||
if (selectedYear === 'all/') {
|
||||
// Show all possible month patterns
|
||||
const monthSet = new Set();
|
||||
questions.forEach((q) => {
|
||||
questions.forEach(q => {
|
||||
const sourceMatch = q.source.match(/^(\d{4})\/(.+?)\//);
|
||||
if (sourceMatch) {
|
||||
monthSet.add(sourceMatch[2]);
|
||||
|
|
@ -199,16 +204,17 @@ const initializeMonthDropdown = (selectedYear) => {
|
|||
|
||||
// Convert to sorted array and create options
|
||||
const uniqueMonths = Array.from(monthSet).sort();
|
||||
uniqueMonths.forEach((month) => {
|
||||
uniqueMonths.forEach(month => {
|
||||
monthOptions += `<option value="${month}" class="fdynamic">${getMonthLabel(month)}</option>`;
|
||||
});
|
||||
|
||||
} else {
|
||||
// Extract year from selected value (e.g., "2024/" -> "2024")
|
||||
const year = selectedYear.replace("/", "");
|
||||
const year = selectedYear.replace('/', '');
|
||||
|
||||
// Get unique months for this specific year
|
||||
const monthSet = new Set();
|
||||
questions.forEach((q) => {
|
||||
questions.forEach(q => {
|
||||
const sourceMatch = q.source.match(`^${year}\/(.+?)\/`);
|
||||
if (sourceMatch) {
|
||||
monthSet.add(sourceMatch[1]);
|
||||
|
|
@ -218,52 +224,50 @@ const initializeMonthDropdown = (selectedYear) => {
|
|||
const uniqueMonths = Array.from(monthSet).sort();
|
||||
|
||||
// Special handling for known year patterns
|
||||
if (year === "2006") {
|
||||
if (year === '2006') {
|
||||
// Preserve existing 2006 logic but add any new months found
|
||||
monthOptions +=
|
||||
'<option value="1" class="f2006">Február-Március</option>';
|
||||
monthOptions += '<option value="1" class="f2006">Február-Március</option>';
|
||||
monthOptions += '<option value="2" class="f2006">Május-Június</option>';
|
||||
monthOptions +=
|
||||
'<option value="3" class="f2006">Október-November</option>';
|
||||
monthOptions += '<option value="3" class="f2006">Október-November</option>';
|
||||
|
||||
// Add any dynamic months not covered by the standard ones
|
||||
uniqueMonths.forEach((month) => {
|
||||
if (!["1", "2", "3"].includes(month)) {
|
||||
uniqueMonths.forEach(month => {
|
||||
if (!['1', '2', '3'].includes(month)) {
|
||||
monthOptions += `<option value="${month}" class="f2006">${getMonthLabel(month)}</option>`;
|
||||
}
|
||||
});
|
||||
} else if (year === "2016") {
|
||||
|
||||
} else if (year === '2016') {
|
||||
// Preserve existing 2016 logic but add any new months found
|
||||
monthOptions += '<option value="1" class="f">Május-Június</option>';
|
||||
monthOptions += '<option value="2" class="f">Október-November</option>';
|
||||
monthOptions +=
|
||||
'<option value="m1" class="f2016">1. Mintafeladatsor</option>';
|
||||
monthOptions +=
|
||||
'<option value="m2" class="f2016">2. Mintafeladatsor</option>';
|
||||
monthOptions +=
|
||||
'<option value="m3" class="f2016">3. Mintafeladatsor</option>';
|
||||
monthOptions += '<option value="m1" class="f2016">1. Mintafeladatsor</option>';
|
||||
monthOptions += '<option value="m2" class="f2016">2. Mintafeladatsor</option>';
|
||||
monthOptions += '<option value="m3" class="f2016">3. Mintafeladatsor</option>';
|
||||
|
||||
// Add any dynamic months not covered
|
||||
uniqueMonths.forEach((month) => {
|
||||
if (!["1", "2", "m1", "m2", "m3"].includes(month)) {
|
||||
uniqueMonths.forEach(month => {
|
||||
if (!['1', '2', 'm1', 'm2', 'm3'].includes(month)) {
|
||||
monthOptions += `<option value="${month}" class="f">${getMonthLabel(month)}</option>`;
|
||||
}
|
||||
});
|
||||
} else if (year === "2017") {
|
||||
|
||||
} else if (year === '2017') {
|
||||
// Preserve existing 2017 logic but add any new months found
|
||||
monthOptions += '<option value="1" class="f">Május-Június</option>';
|
||||
monthOptions += '<option value="2" class="f">Október-November</option>';
|
||||
|
||||
// Add any dynamic months
|
||||
uniqueMonths.forEach((month) => {
|
||||
if (!["1", "2"].includes(month)) {
|
||||
uniqueMonths.forEach(month => {
|
||||
if (!['1', '2'].includes(month)) {
|
||||
monthOptions += `<option value="${month}" class="f">${getMonthLabel(month)}</option>`;
|
||||
}
|
||||
});
|
||||
|
||||
} else {
|
||||
// For other years, use standard logic plus dynamic months
|
||||
const hasStandard1 = uniqueMonths.includes("1");
|
||||
const hasStandard2 = uniqueMonths.includes("2");
|
||||
const hasStandard1 = uniqueMonths.includes('1');
|
||||
const hasStandard2 = uniqueMonths.includes('2');
|
||||
|
||||
if (hasStandard1) {
|
||||
monthOptions += '<option value="1" class="f">Május-Június</option>';
|
||||
|
|
@ -273,8 +277,8 @@ const initializeMonthDropdown = (selectedYear) => {
|
|||
}
|
||||
|
||||
// Add any non-standard months
|
||||
uniqueMonths.forEach((month) => {
|
||||
if (!["1", "2"].includes(month)) {
|
||||
uniqueMonths.forEach(month => {
|
||||
if (!['1', '2'].includes(month)) {
|
||||
monthOptions += `<option value="${month}" class="f">${getMonthLabel(month)}</option>`;
|
||||
}
|
||||
});
|
||||
|
|
@ -282,18 +286,19 @@ const initializeMonthDropdown = (selectedYear) => {
|
|||
}
|
||||
|
||||
monthDropdown.innerHTML = monthOptions;
|
||||
console.log(`Month dropdown initialized for year: ${selectedYear}`);
|
||||
};
|
||||
|
||||
// Helper function to get readable month labels
|
||||
const getMonthLabel = (monthValue) => {
|
||||
// Handle known patterns
|
||||
const knownLabels = {
|
||||
1: "Május-Június",
|
||||
2: "Október-November",
|
||||
3: "Harmadik időszak",
|
||||
m1: "1. Mintafeladatsor",
|
||||
m2: "2. Mintafeladatsor",
|
||||
m3: "3. Mintafeladatsor",
|
||||
'1': 'Május-Június',
|
||||
'2': 'Október-November',
|
||||
'3': 'Harmadik időszak',
|
||||
'm1': '1. Mintafeladatsor',
|
||||
'm2': '2. Mintafeladatsor',
|
||||
'm3': '3. Mintafeladatsor'
|
||||
};
|
||||
|
||||
return knownLabels[monthValue] || monthValue;
|
||||
|
|
|
|||
31
package-lock.json
generated
31
package-lock.json
generated
|
|
@ -1,31 +0,0 @@
|
|||
{
|
||||
"name": "fizika",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "fizika",
|
||||
"version": "1.0.0",
|
||||
"devDependencies": {
|
||||
"prettier": "^3.4.2"
|
||||
}
|
||||
},
|
||||
"node_modules/prettier": {
|
||||
"version": "3.8.3",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.3.tgz",
|
||||
"integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
13
package.json
13
package.json
|
|
@ -1,13 +0,0 @@
|
|||
{
|
||||
"name": "fizika",
|
||||
"version": "1.0.0",
|
||||
"description": "Fizika emelt szintű érettségi gyakorló alkalmazás (repo tooling).",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"prettier": "^3.4.2"
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue