1
0

Compare commits

...

33 Commits

Author SHA1 Message Date
5ac84e3690 docs: Some docs modifications
All checks were successful
Remote Deploy / deploy (push) Successful in 9s
2026-02-11 22:29:05 +01:00
c37a114a78 docs: Add official lib 2026-02-11 22:09:32 +01:00
af4eb5bb88 fix: Another fucking teacher absence
All checks were successful
Remote Deploy / deploy (push) Successful in 9s
2026-02-11 20:21:27 +01:00
bb70b8bc9d docs: Some website modifications
All checks were successful
Remote Deploy / deploy (push) Successful in 9s
2026-02-11 11:51:53 +01:00
7938d2cb9f feat: Serve web
All checks were successful
Remote Deploy / deploy (push) Successful in 10s
2026-02-11 11:25:03 +01:00
16b8b9ae10 chore: Fix docker build
All checks were successful
Remote Deploy / deploy (push) Successful in 11s
2026-02-11 11:09:54 +01:00
faeb0323ba refactor: Some path refactoring 2026-02-11 10:51:02 +01:00
9117044f88 chore: Some website url changes 2026-02-11 10:35:46 +01:00
ae17dc241a refactor: Rewrite to typescript
All checks were successful
Remote Deploy / deploy (push) Successful in 14s
2026-02-11 08:20:56 +01:00
138fa17e54 fix: Absence keys
All checks were successful
Remote Deploy / deploy (push) Successful in 5s
2026-02-10 21:53:55 +01:00
d4815d39ca fix: Background color when not specified
All checks were successful
Remote Deploy / deploy (push) Successful in 5s
2026-02-10 21:44:42 +01:00
de7ac3a48d feat: Background color fetching
All checks were successful
Remote Deploy / deploy (push) Successful in 6s
2026-02-10 21:36:53 +01:00
cfdd97c935 fix: Exkurze shit
All checks were successful
Remote Deploy / deploy (push) Successful in 5s
2026-02-09 19:26:55 +01:00
75d8ba745f fix: Fix
All checks were successful
Remote Deploy / deploy (push) Successful in 5s
2026-02-09 16:06:19 +01:00
7937ac4d65 fix: Some minor changes
All checks were successful
Remote Deploy / deploy (push) Successful in 5s
2026-02-09 16:04:13 +01:00
0c4ca11d7f chore: Some minor fixes
All checks were successful
Remote Deploy / deploy (push) Successful in 5s
2026-02-09 15:55:40 +01:00
5e5e01e9cb Fix v3
All checks were successful
Remote Deploy / deploy (push) Successful in 5s
2026-02-09 09:50:57 +00:00
64a01bf98d Idk
All checks were successful
Remote Deploy / deploy (push) Successful in 6s
2026-02-09 09:46:56 +00:00
de5cd4e911 Emergency debugging
All checks were successful
Remote Deploy / deploy (push) Successful in 5s
2026-02-09 08:12:07 +00:00
166b53bb1a Emergency debugging
Some checks failed
Remote Deploy / deploy (push) Has been cancelled
2026-02-09 08:12:06 +00:00
f5166e5231 Fix parser from phone
All checks were successful
Remote Deploy / deploy (push) Successful in 6s
2026-02-09 07:52:08 +00:00
1d743c5553 fix: Takes place
All checks were successful
Remote Deploy / deploy (push) Successful in 6s
2026-02-08 19:38:22 +01:00
dc845edef0 fix: This 2026-02-08 19:29:17 +01:00
0beb0411d6 fix: Another
All checks were successful
Remote Deploy / deploy (push) Successful in 4s
2026-02-08 19:27:19 +01:00
768913aacc fix: Maybe fix
All checks were successful
Remote Deploy / deploy (push) Successful in 6s
2026-02-08 19:25:27 +01:00
3e1b912cf8 fix: New date format
All checks were successful
Remote Deploy / deploy (push) Successful in 4s
2026-02-08 19:23:00 +01:00
d2a702f9f3 fix: Parser
All checks were successful
Remote Deploy / deploy (push) Successful in 6s
2026-02-08 19:19:21 +01:00
53ecce1eca chore: Minor API changes
All checks were successful
Remote Deploy / deploy (push) Successful in 6s
2026-02-07 16:36:34 +01:00
3430b1c2b1 feat: Include text color in colored stuff 2026-02-07 16:35:29 +01:00
c8d18cf248 fix: V3 parser and minor changes
All checks were successful
Remote Deploy / deploy (push) Successful in 7s
2026-02-07 12:20:22 +01:00
0f4bde1b63 fix: Make it always 10 nulls long instead of 9
All checks were successful
Remote Deploy / deploy (push) Successful in 5s
2026-02-06 20:37:14 +01:00
cdd1d7c078 fix: Add v3 version to the server
All checks were successful
Remote Deploy / deploy (push) Successful in 4s
2026-02-06 20:28:16 +01:00
e3020a278f feat: New v3 API
All checks were successful
Remote Deploy / deploy (push) Successful in 6s
2026-02-06 20:27:21 +01:00
27 changed files with 2115 additions and 163 deletions

View File

@@ -1 +1,7 @@
volume/
node_modules
volume/browser
volume/db
volume/downloads
volume/errors
.env

7
.gitignore vendored
View File

@@ -1,8 +1,9 @@
node_modules
volume/browser
db
downloads
errors
volume/db
volume/downloads
volume/errors
dist
# Web
web/public

View File

@@ -1,23 +1,19 @@
# Use official Node.js image as base
FROM node:18
FROM node:22
# Create app directory
WORKDIR /usr/src/app
# Copy package.json and package-lock.json (if available)
COPY package*.json ./
# Install dependencies
RUN npm install
# Build
RUN npm run build
# Copy app source code
COPY . .
# Expose the port your app runs on (optional, depends on your app)
RUN npm ci
RUN npm run build-noweb
RUN npm prune --production
COPY dist dist
EXPOSE 3000
# Start the app
CMD ["npm", "start"]
ENV SERVE_WEB=false
CMD ["npm", "run", "serve"]

View File

@@ -13,11 +13,25 @@
*/
import cron from 'node-cron';
import { exec } from 'child_process';
import { scheduleRules, toMinutes } from './scheduleRules.js';
import { scheduleRules, toMinutes, ScheduleRule } from './scheduleRules.js';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
function runScraper() {
console.log(`Running scraper at ${new Date().toLocaleString()}...`);
exec('node scrape/scraper.js', (error, stdout, stderr) => {
let command;
if (process.env.NODE_ENV === 'development') {
const scriptPath = path.resolve(__dirname, 'scrape/scraper.ts');
command = `npx tsx "${scriptPath}"`;
} else {
const scriptPath = path.resolve(__dirname, 'scrape/scraper.js');
command = `node "${scriptPath}"`;
}
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Scraper error: ${error.message}`);
return;
@@ -27,11 +41,11 @@ function runScraper() {
});
}
function createSchedules(rules) {
function createSchedules(rules: ScheduleRule[]) {
rules.forEach(rule => {
const startMin = toMinutes(rule.start);
const endMin = toMinutes(rule.end === "0:00" ? "24:00" : rule.end);
const times = [];
const times: { h: number; m: number }[] = [];
const adjustedEnd = endMin <= startMin ? endMin + 1440 : endMin;
for (let t = startMin; t < adjustedEnd; t += rule.interval) {

View File

@@ -6,7 +6,8 @@ services:
ports:
- "3000:3000"
environment:
NODE_ENV: development
NODE_ENV: production
EMAIL: username@spsejecna.cz
PASSWORD: mojesupertajneheslo
volumes:
- ./volume:./usr/src/app/volume
command: npm start
- ./volume:/usr/src/app/volume

749
package-lock.json generated
View File

@@ -16,8 +16,21 @@
"dotenv": "^17.2.3",
"exceljs": "^4.4.0",
"express": "^5.1.0",
"jszip": "^3.10.1",
"node-cron": "^4.2.1",
"puppeteer": "^24.10.0"
"puppeteer": "^24.10.0",
"xml2js": "^0.6.2"
},
"devDependencies": {
"@types/body-parser": "^1.19.6",
"@types/cors": "^2.8.19",
"@types/express": "^5.0.6",
"@types/jszip": "^3.4.0",
"@types/node": "^25.2.3",
"@types/node-cron": "^3.0.11",
"@types/xml2js": "^0.4.14",
"tsx": "^4.21.0",
"typescript": "^5.9.3"
}
},
"node_modules/@babel/code-frame": {
@@ -43,6 +56,448 @@
"node": ">=6.9.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",
"integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz",
"integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz",
"integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz",
"integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz",
"integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz",
"integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz",
"integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz",
"integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz",
"integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz",
"integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz",
"integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz",
"integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz",
"integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz",
"integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz",
"integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz",
"integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz",
"integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz",
"integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz",
"integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz",
"integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz",
"integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz",
"integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz",
"integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz",
"integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz",
"integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz",
"integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@fast-csv/format": {
"version": "4.3.5",
"resolved": "https://registry.npmjs.org/@fast-csv/format/-/format-4.3.5.tgz",
@@ -111,14 +566,139 @@
"integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==",
"license": "MIT"
},
"node_modules/@types/node": {
"version": "22.15.29",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.29.tgz",
"integrity": "sha512-LNdjOkUDlU1RZb8e1kOIUpN1qQUlzGkEtbVNo53vbrwDg5om6oduhm4SiUaPW5ASTXhAiP0jInWG8Qx9fVlOeQ==",
"node_modules/@types/body-parser": {
"version": "1.19.6",
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
"integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"undici-types": "~6.21.0"
"@types/connect": "*",
"@types/node": "*"
}
},
"node_modules/@types/connect": {
"version": "3.4.38",
"resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
"integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/cors": {
"version": "2.8.19",
"resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz",
"integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/express": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
"integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/body-parser": "*",
"@types/express-serve-static-core": "^5.0.0",
"@types/serve-static": "^2"
}
},
"node_modules/@types/express-serve-static-core": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz",
"integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/qs": "*",
"@types/range-parser": "*",
"@types/send": "*"
}
},
"node_modules/@types/http-errors": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",
"integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/jszip": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/@types/jszip/-/jszip-3.4.0.tgz",
"integrity": "sha512-GFHqtQQP3R4NNuvZH3hNCYD0NbyBZ42bkN7kO3NDrU/SnvIZWMS8Bp38XCsRKBT5BXvgm0y1zqpZWp/ZkRzBzg==",
"dev": true,
"license": "MIT",
"dependencies": {
"jszip": "*"
}
},
"node_modules/@types/node": {
"version": "25.2.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.2.3.tgz",
"integrity": "sha512-m0jEgYlYz+mDJZ2+F4v8D1AyQb+QzsNqRuI7xg1VQX/KlKS0qT9r1Mo16yo5F/MtifXFgaofIFsdFMox2SxIbQ==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.16.0"
}
},
"node_modules/@types/node-cron": {
"version": "3.0.11",
"resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.11.tgz",
"integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/qs": {
"version": "6.14.0",
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz",
"integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/range-parser": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",
"integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/send": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
"integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/serve-static": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",
"integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/http-errors": "*",
"@types/node": "*"
}
},
"node_modules/@types/xml2js": {
"version": "0.4.14",
"resolved": "https://registry.npmjs.org/@types/xml2js/-/xml2js-0.4.14.tgz",
"integrity": "sha512-4YnrRemBShWRO2QjvUin8ESA41rH+9nQGLUGZV/1IDhi3SL9OhdpNC/MrulTWuptXKwhx/aDxE7toV0f/ypIXQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/yauzl": {
@@ -1190,6 +1770,48 @@
"node": ">= 0.4"
}
},
"node_modules/esbuild": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz",
"integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.27.3",
"@esbuild/android-arm": "0.27.3",
"@esbuild/android-arm64": "0.27.3",
"@esbuild/android-x64": "0.27.3",
"@esbuild/darwin-arm64": "0.27.3",
"@esbuild/darwin-x64": "0.27.3",
"@esbuild/freebsd-arm64": "0.27.3",
"@esbuild/freebsd-x64": "0.27.3",
"@esbuild/linux-arm": "0.27.3",
"@esbuild/linux-arm64": "0.27.3",
"@esbuild/linux-ia32": "0.27.3",
"@esbuild/linux-loong64": "0.27.3",
"@esbuild/linux-mips64el": "0.27.3",
"@esbuild/linux-ppc64": "0.27.3",
"@esbuild/linux-riscv64": "0.27.3",
"@esbuild/linux-s390x": "0.27.3",
"@esbuild/linux-x64": "0.27.3",
"@esbuild/netbsd-arm64": "0.27.3",
"@esbuild/netbsd-x64": "0.27.3",
"@esbuild/openbsd-arm64": "0.27.3",
"@esbuild/openbsd-x64": "0.27.3",
"@esbuild/openharmony-arm64": "0.27.3",
"@esbuild/sunos-x64": "0.27.3",
"@esbuild/win32-arm64": "0.27.3",
"@esbuild/win32-ia32": "0.27.3",
"@esbuild/win32-x64": "0.27.3"
}
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@@ -1444,6 +2066,21 @@
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
"license": "ISC"
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/fstream": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz",
@@ -1530,6 +2167,19 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/get-tsconfig": {
"version": "4.13.6",
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz",
"integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==",
"dev": true,
"license": "MIT",
"dependencies": {
"resolve-pkg-maps": "^1.0.0"
},
"funding": {
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
"node_modules/get-uri": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.4.tgz",
@@ -2570,6 +3220,16 @@
"node": ">=4"
}
},
"node_modules/resolve-pkg-maps": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
"integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
}
},
"node_modules/rimraf": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
@@ -2634,6 +3294,15 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/sax": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.4.4.tgz",
"integrity": "sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/saxes": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz",
@@ -3014,6 +3683,26 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tsx": {
"version": "4.21.0",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.27.0",
"get-tsconfig": "^4.7.5"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/type-is": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",
@@ -3055,6 +3744,20 @@
"integrity": "sha512-SbklCd1F0EiZOyPiW192rrHZzZ5sBijB6xM+cpmrwDqObvdtunOHHIk9fCGsoK5JVIYXoyEp4iEdE3upFH3PAg==",
"license": "MIT"
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici": {
"version": "7.15.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.15.0.tgz",
@@ -3065,11 +3768,11 @@
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"license": "MIT",
"optional": true
"version": "7.16.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
"devOptional": true,
"license": "MIT"
},
"node_modules/unpipe": {
"version": "1.0.0",
@@ -3217,6 +3920,28 @@
}
}
},
"node_modules/xml2js": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
"integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==",
"license": "MIT",
"dependencies": {
"sax": ">=0.6.0",
"xmlbuilder": "~11.0.0"
},
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/xmlbuilder": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
"integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
"license": "MIT",
"engines": {
"node": ">=4.0"
}
},
"node_modules/xmlchars": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",

View File

@@ -7,9 +7,11 @@
"type": "module",
"main": "server.js",
"scripts": {
"test": "node tests/test.js",
"start": "concurrently \"node server.js\" \"node cron-runner.js\"",
"build": "cd web && hugo --gc --minify",
"test": "tsx tests/test.ts",
"start": "concurrently \"NODE_ENV=development tsx server.ts\" \"NODE_ENV=development tsx cron-runner.ts\"",
"build": "tsc && cd web && hugo --gc --minify",
"build-noweb": "tsc",
"serve": "concurrently \"node dist/server.js\" \"node dist/cron-runner.js\"",
"dev-web": "cd web && hugo serve"
},
"dependencies": {
@@ -20,7 +22,20 @@
"dotenv": "^17.2.3",
"exceljs": "^4.4.0",
"express": "^5.1.0",
"jszip": "^3.10.1",
"node-cron": "^4.2.1",
"puppeteer": "^24.10.0"
"puppeteer": "^24.10.0",
"xml2js": "^0.6.2"
},
"devDependencies": {
"@types/body-parser": "^1.19.6",
"@types/cors": "^2.8.19",
"@types/express": "^5.0.6",
"@types/jszip": "^3.4.0",
"@types/node": "^25.2.3",
"@types/node-cron": "^3.0.11",
"@types/xml2js": "^0.4.14",
"tsx": "^4.21.0",
"typescript": "^5.9.3"
}
}

View File

@@ -13,7 +13,13 @@
*/
// Rules: start and end in 24h format, interval in minutes
export const scheduleRules = [
export interface ScheduleRule {
start: string;
end: string;
interval: number;
}
export const scheduleRules: ScheduleRule[] = [
{ start: "0:00", end: "3:00", interval: 180 },
{ start: "3:00", end: "4:00", interval: 60 },
{ start: "5:00", end: "6:00", interval: 30 },
@@ -23,12 +29,12 @@ export const scheduleRules = [
{ start: "19:00", end: "0:00", interval: 180 }
];
export function toMinutes(timeStr) {
export function toMinutes(timeStr: string): number {
const [h, m] = timeStr.split(":").map(Number);
return h * 60 + (m || 0);
}
export function getCurrentInterval(date = new Date()) {
export function getCurrentInterval(date: Date = new Date()): number | null {
const nowMinutes = date.getHours() * 60 + date.getMinutes();
for (const rule of scheduleRules) {

View File

@@ -13,7 +13,9 @@
*/
import parseV1V2 from "./parse/v1_v2.js";
import parseV3 from "./parse/v3.js";
export default async function parseThisShit(downloadedFilePath) {
await parseV1V2(downloadedFilePath)
export default async function parseThisShit(downloadedFilePath: string) {
await parseV1V2(downloadedFilePath);
await parseV3(downloadedFilePath);
}

View File

@@ -12,17 +12,27 @@
* GNU General Public License for more details.
*/
import ExcelJS from "exceljs"
import ExcelJS, { Worksheet, Cell } from "exceljs"
import fs from "fs"
import parseAbsence from "../utils/parseAbsence.js"
import parseAbsence, { AbsenceResult } from "../utils/parseAbsence.js"
import parseTeachers from "../utils/parseTeachers.js"
export default async function parseV1V2(downloadedFilePath) {
interface DatedSheet {
sheet: Worksheet;
dateKey: string;
}
interface ScheduleDay {
[key: string]: any;
ABSENCE?: AbsenceResult[];
}
export default async function parseV1V2(downloadedFilePath: string) {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(downloadedFilePath);
const teacherMap = await parseTeachers();
const dateRegex = /^(pondělí|úterý|středa|čtvrtek|pátek|po|út|ut|st|čt|ct|pa|pá)\s+(\d{1,2})\.\s*(\d{1,2})\.\s*(20\d{2})/i;
const dateRegex = /^(pondělí|úterý|středa|čtvrtek|pátek|po|út|ut|st|čt|ct|pa|pá)\s+(\d{1,2})\.\s*(\d{1,2})\.\s*(\d{4}|\d{2})/i;
// Get today's date for comparison
function getCurrentDateObject() {
@@ -32,15 +42,15 @@ export default async function parseV1V2(downloadedFilePath) {
const today = getCurrentDateObject();
const datedSheets = [];
const datedSheets: DatedSheet[] = [];
for (const sheet of workbook.worksheets) {
const match = sheet.name.match(dateRegex);
const match = sheet.name.toLowerCase().match(dateRegex);
if (!match) continue;
const day = parseInt(match[2], 10);
const month = parseInt(match[3], 10) - 1;
const year = parseInt(match[4], 10);
const year = match[4].length === 2 ? Number('20' + match[4]) : Number(match[4]);
const sheetDate = new Date(year, month, day);
if (sheetDate < today) continue;
@@ -53,7 +63,7 @@ export default async function parseV1V2(downloadedFilePath) {
});
}
const sheetsByDate = {};
const sheetsByDate: Record<string, Worksheet[]> = {};
for (const item of datedSheets) {
sheetsByDate[item.dateKey] ??= [];
sheetsByDate[item.dateKey].push(item.sheet);
@@ -61,20 +71,23 @@ export default async function parseV1V2(downloadedFilePath) {
const upcomingSheets = Object.values(sheetsByDate).map((sheets) => {
if (sheets.length === 1) return sheets[0].name;
return (sheets.find((s) => s.state !== "hidden") ?? sheets[0]).name;
const found = sheets.find((s) => s.state !== "hidden");
return (found ?? sheets[0]).name;
});
const final = [];
const final: ScheduleDay[] = [];
let finalIndex = 0
for (const key of upcomingSheets) {
const currentSheet = workbook.getWorksheet(key);
if (!currentSheet) continue;
final.push({});
const regex = /[AEC][0-4][a-c]?\s*\/.*/s;
const prefixRegex = /[AEC][0-4][a-c]?/;
const classes = [];
const matchingKeys = [];
const classes: string[] = [];
const matchingKeys: string[] = [];
currentSheet.eachRow((row) => {
row.eachCell((cell) => {
@@ -95,7 +108,7 @@ export default async function parseV1V2(downloadedFilePath) {
})
})
function letterToNumber(letter) {
function letterToNumber(letter: string) {
return letter.toLowerCase().charCodeAt(0) - "a".charCodeAt(0);
}
@@ -104,17 +117,20 @@ export default async function parseV1V2(downloadedFilePath) {
for (const matchingKey of matchingKeys) {
const matchingCell = currentSheet.getCell(matchingKey);
const rowNumber = matchingCell.row;
const allKeys = [];
const allKeys: string[] = [];
// Get all cells in the same row
const row = currentSheet.getRow(rowNumber);
const row = currentSheet.getRow(Number(rowNumber));
row.eachCell((cell) => {
if (cell.address !== matchingKey) {
allKeys.push(cell.address);
}
})
let final2 = [];
// Use an array directly, initialized with nulls or sparse array logic
// The original code used `let final2 = []` but treated it as object `final2[parsedKey] = ...`
// Then `Array.from(final2)` converts it to array.
let final2: (string | null)[] = [];
for (const key of allKeys) {
const cell = currentSheet.getCell(key);
@@ -124,13 +140,16 @@ export default async function parseV1V2(downloadedFilePath) {
try {
const regex = /^úklid\s+(?:\d+\s+)?[A-Za-z]{2}$/;
const cellText = cell.text || "";
if (regex.test(cellText.trim()) || cellText.trim().length == 0 || cell.fill?.fgColor === undefined) {
// @ts-ignore - fgColor is missing in type definition for some versions or intricate structure
const fgColor = cell.fill?.fgColor;
if (regex.test(cellText.trim()) || cellText.trim().length == 0 || fgColor === undefined) {
d = false;
}
} catch {}
if (d) {
let text = cell.text;
// @ts-ignore
if (cell.fill?.fgColor?.argb == "FFFFFF00") {
text += "\n(bude upřesněno)";
}
@@ -140,19 +159,19 @@ export default async function parseV1V2(downloadedFilePath) {
}
}
final2 = Array.from(final2, (item) => (item === undefined ? null : item));
while (final2.length < 10) {
final2.push(null);
const final2Array = Array.from(final2, (item) => (item === undefined ? null : item));
while (final2Array.length < 10) {
final2Array.push(null);
}
final[finalIndex][classes[classI]] = final2.slice(1, 11);
final[finalIndex][classes[classI]] = final2Array.slice(1, 11);
classI++;
}
// ABSENCE
final[finalIndex]["ABSENCE"] = [];
let absenceKey = null;
let absenceKey: string | null = null;
currentSheet.eachRow((row) => {
row.eachCell((cell) => {
@@ -166,22 +185,21 @@ export default async function parseV1V2(downloadedFilePath) {
if (absenceKey) {
const absenceCell = currentSheet.getCell(absenceKey);
const rowNumber = absenceCell.row;
const allAbsenceKeys = [];
const allAbsenceKeys: string[] = [];
// Get all cells in the same row as absence
const row = currentSheet.getRow(rowNumber);
const row = currentSheet.getRow(Number(rowNumber));
row.eachCell((cell) => {
if (cell.address !== absenceKey) {
allAbsenceKeys.push(cell.address);
if (cell.address !== absenceKey) { // absenceKey is checked above to be non-null
allAbsenceKeys.push(cell.address);
}
})
let i = 0;
const absenceRange = new Set(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L"])
for (const absenceKeyCur of allAbsenceKeys) {
if (i >= 10) {
break; // stop once 10 items are added
}
i++;
if (!absenceRange.has(absenceKeyCur.substring(0, 1))) {
break;
};
const cell = currentSheet.getCell(absenceKeyCur);
const value = (cell.value || "").toString().trim();
@@ -190,7 +208,9 @@ export default async function parseV1V2(downloadedFilePath) {
}
const data = parseAbsence(value, teacherMap);
final[finalIndex]["ABSENCE"].push(...data);
if (final[finalIndex]["ABSENCE"]) {
final[finalIndex]["ABSENCE"]!.push(...data);
}
}
}
@@ -203,14 +223,14 @@ export default async function parseV1V2(downloadedFilePath) {
const data = {
schedule: final,
props: upcomingSheets.map((str) => {
const dateMatch = str.match(/(\d{1,2})\.\s*(\d{1,2})\.\s*(\d{4})/);
const dateMatch = str.match(/(\d{1,2})\.\s*(\d{1,2})\.\s*(\d{4}|\d{2})/);
let date = null;
if (dateMatch) {
const day = Number.parseInt(dateMatch[1], 10);
const month = Number.parseInt(dateMatch[2], 10);
const year = Number.parseInt(dateMatch[3], 10);
const year = dateMatch[3].length === 2 ? Number('20' + dateMatch[3]) : Number(dateMatch[3]);
date = new Date(year, month - 1, day);
}
@@ -233,15 +253,15 @@ export default async function parseV1V2(downloadedFilePath) {
}
}
fs.writeFileSync("db/v2.json", JSON.stringify(data, null, 2));
fs.writeFileSync("volume/db/v2.json", JSON.stringify(data, null, 2));
// Modify the data for v1
const copy = JSON.parse(JSON.stringify(data));
copy.schedule.forEach(day => {
copy.schedule.forEach((day: ScheduleDay) => {
if (!Array.isArray(day.ABSENCE)) return;
day.ABSENCE = day.ABSENCE.map(old => {
day.ABSENCE = day.ABSENCE.map((old: any) => {
if (old.type === "zastoupen") {
return {
type: "invalid",
@@ -255,7 +275,7 @@ export default async function parseV1V2(downloadedFilePath) {
});
});
fs.writeFileSync("db/v1.json", JSON.stringify(copy, null, 2))
fs.writeFileSync("volume/db/v1.json", JSON.stringify(copy, null, 2))
}
//parseV1V2("db/current.xlsx")

427
scrape/parse/v3.ts Normal file
View File

@@ -0,0 +1,427 @@
/*
* Copyright (C) 2025 Jakub Žitník
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
import fs from "fs";
import parseAbsence from "../utils/parseAbsence.js"
import parseTeachers from "../utils/parseTeachers.js"
import ExcelJS, { Worksheet, Cell, Row } from "exceljs"
import JSZip from "jszip";
import { parseStringPromise } from "xml2js";
interface ThemeColors {
[key: number]: string | null;
}
interface Lesson {
text: string;
backgroundColor: string | null;
foregroundColor?: string;
willBeSpecified?: boolean;
}
interface ResolvedDay {
dateKey: string;
sheet: Worksheet;
}
/**
* Read theme colors from the workbook
*/
async function getThemeColors(filePath: string): Promise<ThemeColors | null> {
const data = fs.readFileSync(filePath);
const zip = await JSZip.loadAsync(data);
// list all files for debug
const themeFile = zip.file("xl/theme/theme1.xml");
if (!themeFile) {
return null;
}
const themeXml = await themeFile.async("text");
const theme = await parseStringPromise(themeXml);
const scheme = theme["a:theme"]?.["a:themeElements"]?.[0]?.["a:clrScheme"]?.[0];
if (!scheme) return null;
function getColor(node: any) {
if (node["a:srgbClr"]) return node["a:srgbClr"][0].$.val;
if (node["a:sysClr"]) return node["a:sysClr"][0].$.lastClr;
return null;
}
const colors: ThemeColors = {
0: getColor(scheme["a:dk1"]?.[0]),
1: getColor(scheme["a:lt1"]?.[0]),
2: getColor(scheme["a:dk2"]?.[0]),
3: getColor(scheme["a:lt2"]?.[0]),
4: getColor(scheme["a:accent1"]?.[0]),
5: getColor(scheme["a:accent2"]?.[0]),
6: getColor(scheme["a:accent3"]?.[0]),
7: getColor(scheme["a:accent4"]?.[0]),
8: getColor(scheme["a:accent5"]?.[0]),
9: getColor(scheme["a:accent6"]?.[0]),
};
return colors;
}
/**
* Apply Excel tint to a base hex color
*/
function applyTintToHex(hex: string, tint: number = 0) {
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
const tintChannel = (c: number) =>
tint > 0 ? Math.round(c + (255 - c) * tint) : Math.round(c * (1 + tint));
const nr = tintChannel(r);
const ng = tintChannel(g);
const nb = tintChannel(b);
return [nr, ng, nb]
.map((v) => v.toString(16).padStart(2, "0"))
.join("")
.toUpperCase();
}
/**
* Resolve final hex for a cell fill
*/
function resolveCellColor(cell: Cell, themeColors: ThemeColors | null) {
// @ts-ignore
if (!cell.fill?.fgColor) return null;
// @ts-ignore
const fg = cell.fill.fgColor;
if (fg.argb) return `#${fg.argb}`;
if (fg.theme !== undefined && themeColors) {
const base = themeColors[fg.theme];
if (!base) return null;
return `#${applyTintToHex(base, fg.tint ?? 0)}`;
}
return null;
}
export default async function parseV3(downloadedFilePath: string) {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(downloadedFilePath);
const themeColors = await getThemeColors(downloadedFilePath);
const teacherMap = await parseTeachers();
const upcoming = getUpcomingSheets(workbook);
const resolvedDays = groupSheetsByDate(upcoming);
const schedule: any = {};
for (const { dateKey, sheet } of resolvedDays) {
const { changes, absence, inWork, takesPlace, reservedRooms } = extractDaySchedule(sheet, teacherMap, themeColors);
schedule[dateKey] = {
info: { inWork },
changes,
absence,
takesPlace,
reservedRooms,
};
}
const data = {
status: { lastUpdated: formatNowTime() },
schedule,
};
fs.writeFileSync("volume/db/v3.json", JSON.stringify(data, null, 2));
}
//
// ────────────────────────────────────────────────────────────
// SHEET FILTERING
// ────────────────────────────────────────────────────────────
//
function getUpcomingSheets(workbook: ExcelJS.Workbook): ResolvedDay[] {
const dateRegex = /^(pondělí|úterý|středa|čtvrtek|pátek|po|út|ut|st|čt|ct|pa|pá)\s+(\d{1,2})\.\s*(\d{1,2})\.\s*(\d{4}|\d{2})/i;
const today = new Date();
const todayMidnight = new Date(today.getFullYear(), today.getMonth(), today.getDate());
const result: ResolvedDay[] = [];
for (const sheet of workbook.worksheets) {
const match = sheet.name.toLowerCase().match(dateRegex);
if (!match) continue;
const day = Number(match[2]);
const month = Number(match[3]) - 1;
const year = match[4].length === 2 ? Number('20' + match[4]) : Number(match[4]);
const sheetDate = new Date(year, month, day);
if (sheetDate < todayMidnight) continue;
const dateKey = `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
result.push({ dateKey, sheet });
}
return result;
}
function groupSheetsByDate(items: ResolvedDay[]) {
const map: Record<string, Worksheet[]> = {};
for (const item of items) {
map[item.dateKey] ??= [];
map[item.dateKey].push(item.sheet);
}
return Object.entries(map).map(([dateKey, sheets]) => {
const chosen =
sheets.length === 1
? sheets[0]
: sheets.find((s) => s.state !== "hidden") ?? sheets[0];
return { dateKey, sheet: chosen };
});
}
//
// ────────────────────────────────────────────────────────────
// DAY PARSING
// ────────────────────────────────────────────────────────────
//
function extractDaySchedule(sheet: Worksheet, teacherMap: Record<string, string>, themeColors: ThemeColors | null) {
return {
changes: extractClassChanges(sheet, themeColors),
absence: extractAbsence(sheet, teacherMap),
inWork: isPripravaSheet(sheet.name.toLowerCase()),
takesPlace: extractTakesPlace(sheet),
reservedRooms: extractReservedRooms(sheet)
};
}
function isPripravaSheet(name: string) {
return name
.toLowerCase()
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.includes("priprava");
}
//
// ────────────────────────────────────────────────────────────
// CLASS CHANGES
// ────────────────────────────────────────────────────────────
//
function extractClassChanges(sheet: Worksheet, themeColors: ThemeColors | null) {
const classRegex = /[AEC][0-4][a-c]?\s*\/.*/s;
const prefixRegex = /[AEC][0-4][a-c]?/;
const classes: string[] = [];
const classCells: string[] = [];
sheet.eachRow((row) => {
row.eachCell((cell) => {
const value = cell.value;
if (typeof value === "string" && classRegex.test(value) && cell.address.startsWith("A")) {
const prefixMatch = value.match(prefixRegex);
if (prefixMatch) classes.push(prefixMatch[0]);
classCells.push(cell.address);
}
});
});
const changes: Record<string, (Lesson | null)[]> = {};
classCells.forEach((address, index) => {
const row = sheet.getRow(Number(sheet.getCell(address).row));
changes[classes[index]] = buildLessonArray(row, address, themeColors);
});
return changes;
}
function buildLessonArray(row: Row, ignoreAddress: string, themeColors: ThemeColors | null) {
const lessons: (Lesson | null)[] = [];
row.eachCell((cell) => {
if (cell.address === ignoreAddress) return;
const colIndex = letterToNumber(cell.address.replace(/[0-9]/g, ""));
lessons[colIndex] = parseLessonCell(cell, themeColors);
});
const normalized = Array.from(lessons, (x) => (x === undefined ? null : x));
while (normalized.length < 11) normalized.push(null);
return normalized.slice(1, 11);
}
function parseLessonCell(cell: Cell, themeColors: ThemeColors | null): Lesson | null {
try {
const text = (cell.text || "").trim();
const cleanupRegex = /^úklid\s+(?:\d+\s+)?[A-Za-z]{2}$/;
// @ts-ignore
if (!text || cleanupRegex.test(text) || !cell.fill?.fgColor) return null;
const backgroundColor = resolveCellColor(cell, themeColors);
const foregroundColor = !backgroundColor ? undefined : (
cell.font?.color?.argb === undefined ? "#FF000000" : `#${cell.font.color.argb}`
);
return {
text,
backgroundColor,
foregroundColor,
// @ts-ignore
willBeSpecified: cell.fill.fgColor.argb === "FFFFFF00" ? true : undefined,
};
} catch {
return null;
}
}
function extractTakesPlace(sheet: Worksheet) {
const cell = sheet.getCell("B4");
if (!cell.isMerged) {
return "";
}
let str = "";
let i = 4;
while (true) {
const tryCells = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
const threshold = 20;
let con = false;
for (const cellTest of tryCells) {
const cellTry = sheet.getCell(`${cellTest}${i}`)
const cellValue = (typeof cellTry?.value === 'string' ? cellTry.value.trim() : "") || "";
if (cellValue.length >= threshold) {
str += `\n${cellValue}`;
con = true;
break;
}
}
if (con || i == 4) {
i++;
continue;
} else {
break;
}
}
return str.trim();
}
function extractReservedRooms(sheet: Worksheet) {
const result: (string | null)[] = [];
const cells: string[] = [];
sheet.eachRow((row) => {
row.eachCell((cell) => {
const value = cell.value;
if (typeof value === "string" && value.trim() === "rezervace" && cell.address.startsWith("A")) {
cells.push(cell.address);
}
});
});
cells.forEach((address) => {
const row = sheet.getRow(Number(sheet.getCell(address).row));
row.eachCell((cell) => {
if (cell.address === address) return;
const val = cell.value?.toString().trim();
result.push(!val || val.length == 0 ? null : val)
});
});
while (result.length < 10) {
result.push(null);
}
return result;
}
//
// ────────────────────────────────────────────────────────────
// ABSENCE
// ────────────────────────────────────────────────────────────
//
function extractAbsence(sheet: Worksheet, teacherMap: Record<string, string>) {
let absenceAddress: string | null = null;
sheet.eachRow((row) => {
row.eachCell((cell) => {
if ((cell.value || "").toString().trim().toLowerCase() === "absence") {
absenceAddress = cell.address;
}
});
});
if (!absenceAddress) return [];
const row = sheet.getRow(Number(sheet.getCell(absenceAddress).row));
const results: any[] = [];
const absenceRange = new Set(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L"])
row.eachCell((cell) => {
if (cell.address === absenceAddress || !absenceRange.has(cell.address.substring(0, 1))) {
return
};
const value = (cell.value || "").toString().trim();
if (!value) return;
results.push(...parseAbsence(value, teacherMap));
});
return results;
}
//
// ────────────────────────────────────────────────────────────
// UTILS
// ────────────────────────────────────────────────────────────
//
function letterToNumber(letter: string) {
return letter.toLowerCase().charCodeAt(0) - 97;
}
function formatNowTime() {
const now = new Date();
return (
now.getHours().toString().padStart(2, "0") +
":" +
now.getMinutes().toString().padStart(2, "0")
);
}
//parseV3("db/current.xlsx")

View File

@@ -12,7 +12,7 @@
* GNU General Public License for more details.
*/
import puppeteer from 'puppeteer';
import puppeteer, { Page, Browser } from 'puppeteer';
import path from 'path';
import fs from 'fs';
import parseThisShit from './parse.js';
@@ -21,40 +21,44 @@ import 'dotenv/config';
const EMAIL = process.env.EMAIL;
const PASSWORD = process.env.PASSWORD;
const SHAREPOINT_URL = process.env.SHAREPOINT_URL || 'https://spsejecnacz.sharepoint.com/:x:/s/nastenka/ESy19K245Y9BouR5ksciMvgBu3Pn_9EaT0fpP8R6MrkEmg';
const VOLUME_PATH = path.resolve('./volume/browser');
const VOLUME_PATH = path.resolve("./volume/browser");
const DOWNLOAD_FOLDER = path.resolve("./volume/downloads");
const ERROR_FOLDER = path.resolve("./volume/errors")
const DB_FOLDER = path.resolve("./volume/db");
async function clearDownloadsFolder() {
try {
await fs.promises.rm('./downloads', { recursive: true, force: true });
await fs.promises.mkdir('./downloads');
await fs.promises.rm(DOWNLOAD_FOLDER, { recursive: true, force: true });
await fs.promises.mkdir(DOWNLOAD_FOLDER);
} catch (err) {
console.error('Error:', err);
}
}
async function handleError(page, err) {
async function handleError(page: Page, err: any) {
try {
const errorsDir = path.resolve('./errors');
if (!fs.existsSync(errorsDir)) fs.mkdirSync(errorsDir);
if (!fs.existsSync(ERROR_FOLDER)) fs.mkdirSync(ERROR_FOLDER);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filePath = path.join(errorsDir, `error-${timestamp}.png`);
const filePath = path.join(ERROR_FOLDER, `error-${timestamp}.png`);
// @ts-ignore
await page.screenshot({ path: filePath, fullPage: true });
console.error(`❌ Error occurred. Screenshot saved: ${filePath}`);
// Keep only last 10 screenshots
const files = fs.readdirSync(errorsDir)
const files = fs.readdirSync(ERROR_FOLDER)
.map(f => ({
name: f,
time: fs.statSync(path.join(errorsDir, f)).mtime.getTime()
time: fs.statSync(path.join(ERROR_FOLDER, f)).mtime.getTime()
}))
.sort((a, b) => b.time - a.time);
if (files.length > 10) {
const oldFiles = files.slice(10);
for (const f of oldFiles) {
fs.unlinkSync(path.join(errorsDir, f.name));
fs.unlinkSync(path.join(ERROR_FOLDER, f.name));
}
}
} catch (screenshotErr) {
@@ -64,22 +68,22 @@ async function handleError(page, err) {
}
(async () => {
let browser, page;
let browser: Browser | undefined, page: Page | undefined;
try {
browser = await puppeteer.launch({
headless: 'new',
headless: true,
userDataDir: VOLUME_PATH,
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
[page] = await browser.pages();
const pages = await browser.pages();
page = pages[0];
const downloadPath = path.resolve('./downloads');
if (!fs.existsSync(downloadPath)) fs.mkdirSync(downloadPath);
if (!fs.existsSync(DOWNLOAD_FOLDER)) fs.mkdirSync(DOWNLOAD_FOLDER);
const client = await page.createCDPSession();
await client.send('Page.setDownloadBehavior', {
behavior: 'allow',
downloadPath: downloadPath,
downloadPath: DOWNLOAD_FOLDER,
});
await page.goto(SHAREPOINT_URL, { waitUntil: 'networkidle2' });
@@ -91,7 +95,7 @@ async function handleError(page, err) {
try {
await page.waitForSelector('input[type="email"]', { timeout: 3000 });
await page.type('input[type="email"]', EMAIL, { delay: 50 });
await page.type('input[type="email"]', EMAIL || "", { delay: 50 });
await page.keyboard.press('Enter');
} catch {
try {
@@ -117,7 +121,7 @@ async function handleError(page, err) {
}
await page.waitForSelector('input[type="password"]', { timeout: 100000 });
await page.type('input[type="password"]', PASSWORD, { delay: 50 });
await page.type('input[type="password"]', PASSWORD || "", { delay: 50 });
await page.keyboard.press('Enter');
try {
@@ -133,7 +137,9 @@ async function handleError(page, err) {
await new Promise(r => setTimeout(r, 5000));
const frameHandle = await page.waitForSelector('iframe');
if (!frameHandle) throw new Error("Frame not found");
const frame = await frameHandle.contentFrame();
if (!frame) throw new Error("Frame content not found");
await frame.waitForSelector('button[title="File"]', { timeout: 60000 });
await frame.click('button[title="File"]');
@@ -153,7 +159,7 @@ async function handleError(page, err) {
await new Promise(r => setTimeout(r, 10000));
function waitForFile(filename, timeout = 30000) {
function waitForFile(filename: string, timeout = 30000): Promise<void> {
return new Promise((resolve, reject) => {
const start = Date.now();
const interval = setInterval(() => {
@@ -168,7 +174,7 @@ async function handleError(page, err) {
});
}
function getNewestFile(dir) {
function getNewestFile(dir: string) {
const files = fs.readdirSync(dir)
.map(f => ({
name: f,
@@ -178,14 +184,16 @@ async function handleError(page, err) {
return files.length ? path.join(dir, files[0].name) : null;
}
const downloadedFilePath = getNewestFile(downloadPath);
const downloadedFilePath = getNewestFile(DOWNLOAD_FOLDER);
if (!downloadedFilePath) {
throw new Error('No XLSX file found in download folder');
}
console.log('Waiting for file:', downloadedFilePath);
await waitForFile(downloadedFilePath);
await fs.promises.cp(downloadedFilePath, "db/current.xlsx");
if (!fs.existsSync(DB_FOLDER)) fs.mkdirSync(DB_FOLDER);
await fs.promises.cp(downloadedFilePath, path.join(DB_FOLDER, "current.xlsx"));
await parseThisShit(downloadedFilePath);
await clearDownloadsFolder();

View File

@@ -17,10 +17,28 @@ const LAST_HOUR = 10;
// -------------------------------
// Helpers
// -------------------------------
export const cleanInput = (input) => (input ?? "").trim().replace(/\s+/g, " ");
export const isTeacherToken = (t) => /^[A-Za-z]+$/.test(t);
export const cleanInput = (input: string | null | undefined): string => (input ?? "").trim().replace(/\s+/g, " ");
export const isTeacherToken = (t: string): boolean => /^[A-Za-z]+$/.test(t);
export const parseSpec = (spec) => {
interface Spec {
kind: "range" | "single";
value: { from: number; to: number } | number;
}
interface TeacherMap {
[key: string]: string;
}
export interface AbsenceResult {
teacher: string | null;
teacherCode: string | null;
type: string;
hours: { from: number; to: number } | number | null;
zastupuje?: { teacher: string | null; teacherCode: string | null };
original?: string;
}
export const parseSpec = (spec: string | null): Spec | null => {
if (!spec) return null;
let m;
@@ -55,12 +73,12 @@ export const parseSpec = (spec) => {
return null;
};
export const resolveTeacher = (teacherCode, teacherMap = {}) => ({
export const resolveTeacher = (teacherCode: string, teacherMap: TeacherMap = {}): { code: string; name: string | null } => ({
code: teacherCode,
name: teacherMap?.[teacherCode.toLowerCase()] ?? null,
});
const makeResult = (teacherCode, spec, teacherMap) => {
const makeResult = (teacherCode: string, spec: Spec | null, teacherMap: TeacherMap): AbsenceResult => {
const { name } = resolveTeacher(teacherCode, teacherMap);
const type = spec ? (spec.kind === "range" ? "range" : "single") : "wholeDay";
const hours = spec ? spec.value : null;
@@ -70,8 +88,8 @@ const makeResult = (teacherCode, spec, teacherMap) => {
// -------------------------------
// Teacher list processing (modular)
// -------------------------------
const processTeacherList = (teacherListStr, spec, teacherMap) => {
let results = [];
const processTeacherList = (teacherListStr: string, spec: Spec | null, teacherMap: TeacherMap): AbsenceResult[] => {
let results: AbsenceResult[] = [];
const teachers = teacherListStr.split(/[,;]\s*/).filter(Boolean);
if (teacherListStr.includes(";")) {
@@ -89,14 +107,14 @@ const processTeacherList = (teacherListStr, spec, teacherMap) => {
// -------------------------------
// Main parser
// -------------------------------
export default function parseAbsence(input, teacherMap = {}) {
export default function parseAbsence(input: string, teacherMap: TeacherMap = {}): AbsenceResult[] {
const s = cleanInput(input);
if (!s) return [];
const results = [];
const consumed = [];
const markConsumed = (start, end) => consumed.push([start, end]);
const isConsumed = (i) => consumed.some(([a, b]) => i >= a && i < b);
const results: AbsenceResult[] = [];
const consumed: [number, number][] = [];
const markConsumed = (start: number, end: number) => consumed.push([start, end]);
const isConsumed = (i: number) => consumed.some(([a, b]) => i >= a && i < b);
// 1. Teachers with specific hours (e.g. "Ab 1-4")
const teacherListThenSpecRe =
@@ -116,6 +134,51 @@ export default function parseAbsence(input, teacherMap = {}) {
markConsumed(matchStart, matchEnd);
}
// 1a. Teachers with "-startHour-exk" suffix (e.g. "Sv-5-exk")
const teacherStartExkRe = /([A-Za-z]+)-(\d+)-exk/gi;
while ((m = teacherStartExkRe.exec(s)) !== null) {
const matchStart = m.index;
const matchEnd = teacherStartExkRe.lastIndex;
if (isConsumed(matchStart)) continue;
const teacherCode = m[1];
const from = Number(m[2]);
const { name } = resolveTeacher(teacherCode, teacherMap);
if (from >= 1 && from <= LAST_HOUR) {
results.push({
teacher: name,
teacherCode: teacherCode.toLowerCase(),
type: "exkurze",
hours: { from, to: LAST_HOUR },
});
markConsumed(matchStart, matchEnd);
}
}
// 1b. Teachers with "-exk" followed by spec (e.g. "Ex-exk. 3+")
const teacherExkWithSpecRe = /([A-Za-z]+)-exk(?:\.)?\s*(\d+(?:\+|-\d+|,\d+)?)/gi;
while ((m = teacherExkWithSpecRe.exec(s)) !== null) {
const matchStart = m.index;
const matchEnd = teacherExkWithSpecRe.lastIndex;
if (isConsumed(matchStart)) continue;
const teacherCode = m[1];
const specStr = m[2];
const spec = parseSpec(specStr);
if (spec) {
const { name } = resolveTeacher(teacherCode, teacherMap);
results.push({
teacher: name,
teacherCode: teacherCode.toLowerCase(),
type: "exkurze",
hours: spec.value,
});
markConsumed(matchStart, matchEnd);
}
}
// 2. Teachers with "-exk" suffix
const teacherExkRe = /([A-Za-z]+)-exk/gi;
while ((m = teacherExkRe.exec(s)) !== null) {
@@ -153,6 +216,7 @@ export default function parseAbsence(input, teacherMap = {}) {
teacher: missingResolved.name,
teacherCode: missingResolved.code.toLowerCase(),
type: "zastoupen",
hours: null,
zastupuje: {
teacher: subResolved.name,
teacherCode: subResolved.code.toLowerCase()

View File

@@ -14,15 +14,16 @@
import * as cheerio from "cheerio";
// @ts-ignore
globalThis.File = class File {};
export default async function parseTeachers() {
export default async function parseTeachers(): Promise<Record<string, string>> {
const url = "https://spsejecna.cz/ucitel";
const response = await fetch(url);
const data = await response.text();
const $ = cheerio.load(data);
const map = {};
const map: Record<string, string> = {};
$("main .contentLeftColumn li, main .contentRightColumn li").each((_, el) => {
const link = $(el).find("a");
@@ -30,8 +31,10 @@ export default async function parseTeachers() {
const text = link.text().trim(); // e.g. "Ing. Bc. Šárka Páltiková"
if (href) {
const key = href.split("/").pop().toLowerCase(); // get "pa"
map[key] = text;
const key = href.split("/").pop()?.toLowerCase(); // get "pa"
if (key) {
map[key] = text;
}
}
});

View File

@@ -12,7 +12,7 @@
* GNU General Public License for more details.
*/
import express from "express";
import express, { Request, Response } from "express";
import path from "path";
const app = express();
import fs from "fs/promises";
@@ -20,9 +20,14 @@ import { getCurrentInterval } from "./scheduleRules.js";
import bodyParser from "body-parser";
import cors from "cors";
const VERSIONS = ["v1", "v2"];
const DB_FOLDER = path.join(process.cwd(), "volume", "db");
const WEB_FOLDER = path.join(process.cwd(), "web", "public");
const SERVE_WEB = process.env.SERVE_WEB != "false";
const VERSIONS = ["v1", "v2", "v3"];
const PORT = process.env.PORT || 3000;
// @ts-ignore
globalThis.File = class File {};
app.use(bodyParser.json());
@@ -33,14 +38,14 @@ app.use(cors({
allowedHeaders: ["Content-Type"],
}));
app.get('/', async (req, res) => {
app.get('/', async (req: Request, res: Response) => {
const userAgent = req.headers['user-agent'] || '';
const isBrowser = /Mozilla|Chrome|Firefox|Safari|Edg/.test(userAgent);
if (isBrowser) {
res.sendFile(path.join(process.cwd(), "web", "public", "index.html"));
if (isBrowser && SERVE_WEB) {
res.sendFile(path.join(WEB_FOLDER, "index.html"));
} else {
const dataStr = await fs.readFile(path.join(process.cwd(), "db", "v1.json"), "utf8");
const dataStr = await fs.readFile(path.join(DB_FOLDER, "v1.json"), "utf8");
const data = JSON.parse(dataStr);
data["status"]["currentUpdateSchedule"] = getCurrentInterval();
@@ -49,19 +54,10 @@ app.get('/', async (req, res) => {
}
});
app.get('/versioned/v1', async (_, res) => {
const dataStr = await fs.readFile(path.join(process.cwd(), "db", "v1.json"), "utf8");
const data = JSON.parse(dataStr);
data["status"]["currentUpdateSchedule"] = getCurrentInterval();
res.json(data);
});
VERSIONS.forEach((version) => {
app.get(`/versioned/${version}`, async (_, res) => {
app.get(`/versioned/${version}`, async (_: Request, res: Response) => {
try {
const filePath = path.join(process.cwd(), "db", `${version}.json`);
const filePath = path.join(DB_FOLDER, `${version}.json`);
const dataStr = await fs.readFile(filePath, "utf8");
const data = JSON.parse(dataStr);
@@ -75,7 +71,7 @@ VERSIONS.forEach((version) => {
});
});
app.get("/status", async (_, res) => {
app.get("/status", async (_: Request, res: Response) => {
const dataStr = await fs.readFile(path.resolve("./volume/customState.json"), {encoding: "utf8"});
const data = JSON.parse(dataStr);
@@ -86,17 +82,22 @@ app.get("/status", async (_, res) => {
}
})
app.post("/report", async (req, res) => {
app.post("/report", async (req: Request, res: Response): Promise<any> => {
const { class: className, location, content } = req.body;
if (!className || !location || !content) {
return res.status(400).json({ error: "Missing required fields." });
}
if (!["TIMETABLE", "ABSENCES", "OTHER"].includes(location)) {
if (!["TIMETABLE", "ABSENCES", "ABSENCE", "TAKES_PLACE", "OTHER"].includes(location)) {
return res.status(400).json({ error: "Invalid location value." });
}
const url = process.env.REPORT_WEBHOOK_URL;
if (!url) {
console.error("REPORT_WEBHOOK_URL is not set.");
return res.status(500).json({ error: "Server configuration error." });
}
let resp;
try {
resp = await fetch(url, {
@@ -106,7 +107,7 @@ app.post("/report", async (req, res) => {
},
body: `${content}\n\nClass: ${className}\nLocation: ${location}`,
});
} catch (err) {
} catch (err: any) {
console.error('Fetch failed:', err.message);
console.error(err);
throw err;
@@ -119,10 +120,12 @@ app.post("/report", async (req, res) => {
res.status(200).json({ message: "Report received successfully." });
});
app.use(express.static(path.join(process.cwd(), 'web/public'), {
index: 'index.html',
extensions: ['html'],
}));
if (SERVE_WEB) {
app.use(express.static(path.join(process.cwd(), 'web/public'), {
index: 'index.html',
extensions: ['html'],
}));
}
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);

View File

@@ -15,7 +15,8 @@
import fs from "fs";
import parseAbsence from "../scrape/utils/parseAbsence.js";
const teachermap = JSON.parse(fs.readFileSync("./teachermap.json"));
const teachermap: Record<string, string> = JSON.parse(fs.readFileSync("./tests/teachermap.json", "utf8"));
let passedAll = true;
test("Me", [
{
@@ -232,6 +233,7 @@ test("za Vn zastupuje Jk", [
teacher: "Ing. Zdeněk Vondra",
teacherCode: "vn",
type: "zastoupen",
hours: null,
zastupuje: {
teacher: "David Janoušek",
teacherCode: "jk",
@@ -248,18 +250,55 @@ test("Vc 1. h", [
},
]);
function test(input, expectedOutput) {
test("Sv-5-exk", [
{
teacher: "Ing. Jan Šváb",
teacherCode: "sv",
type: "exkurze",
hours: { from: 5, to: 10 },
},
]);
test("Ex-exk. 3+", [
{
teacher: "Ing. Jana Exnerová",
teacherCode: "ex",
type: "exkurze",
hours: { from: 3, to: 10 },
},
]);
test("Ex-exk.3+", [
{
teacher: "Ing. Jana Exnerová",
teacherCode: "ex",
type: "exkurze",
hours: { from: 3, to: 10 },
},
]);
test("Ex-exk. 3", [
{
teacher: "Ing. Jana Exnerová",
teacherCode: "ex",
type: "exkurze",
hours: 3,
},
]);
function test(input: string, expectedOutput: any[]) {
const res = parseAbsence(input, teachermap);
if (!deepEqual(res, expectedOutput)) {
passedAll = false;
console.error("ERROR for input: " + input);
console.log(res);
console.log(expectedOutput);
console.log(JSON.stringify(res, null, 2));
console.log(JSON.stringify(expectedOutput, null, 2));
console.log();
}
}
function deepEqual(a, b) {
function deepEqual(a: any, b: any): boolean {
if (a === b) return true;
if (
@@ -298,3 +337,7 @@ function deepEqual(a, b) {
return keysA.every((key) => keysB.includes(key) && deepEqual(a[key], b[key]));
}
if (passedAll) {
console.log("All tests passed");
}

20
tsconfig.json Normal file
View File

@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./"
},
"include": [
"./**/*.ts"
],
"exclude": [
"node_modules",
"web"
]
}

View File

@@ -0,0 +1,5 @@
---
title: API
summary: Jak využívat API
description: Jak využívat API
---

View File

@@ -0,0 +1,210 @@
---
title: "Oficiální knihovna"
date: 2026-02-11
tags: ["api", "docs"]
hiddenInHomelist: true
TocOpen: true
---
Ječná Rozvrh API má svoji Rust knihovnu pro komunikaci s API. Obsahuje mappings pro Kotlin. Pro další jazyky budou mappingy v budoucnu.
## Usage
### `JecnaSuplClient` struct
Knihovna používá `JecnaSuplClient` struct. Vytvoříte instanci pomocí `new`.
```rust
fn main() {
let client = JecnaSuplClient::new();
}
```
### `set_provider(url: String)`
Pokud nenastavíte vlastní provider path API použije hosted `https://jecnarozvrh.jzitnik.dev`
Example usage:
```rust
client.set_provider("https://jecnarozvrh.example.com");
```
### `get_schedule(class_name: String) -> Result<SuplResult, SuplError>`
Example usage:
```rust
let class = String::from("C2c");
match client.get_schedule(class) {
Ok(result) => {
println!("Last update: {}", result.status.last_updated);
}
Err(error) => {
panic!("Error: {}", error)
}
}
```
### `get_teacher_absence() -> Result<TeacherAbsenceResult, SuplError>`
Example usage:
```rust
match client.get_teacher_absence() {
Ok(result) => {
/* Code */
}
Err(error) => {
panic!("Error: {}", error)
}
}
```
### `get_all() -> Result<ApiResponse, SuplError>`
Example usage:
```rust
match client.get_all() {
Ok(result) => {
/* Code */
}
Err(error) => {
panic!("Error: {}", error)
}
}
```
### `report(content: String, class: String, report_location: ReportLocation) -> Result<(), SuplError>`
Report function for reporting errors of the parser to the provider.
Example usage:
```rust
let content = String::from("Detailni popis chyby");
let class = String::from("C2c");
let report_location = ReportLocation::Timetable;
match client.report(content, class, report_location) {
Ok(result) => {
println!("Success");
}
Err(error) => {
panic!("Error: {}", error)
}
}
```
## Datové struktury
```rust
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum SuplError {
#[error("Network error: {reason}")]
NetworkError { reason: String },
#[error("Parse error: {reason}")]
ParseError { reason: String },
#[error("Invalid date format: {reason}")]
DateFormatError { reason: String },
#[error("Internal runtime error: {reason}")]
RuntimeError { reason: String },
}
pub enum AbsenceEntry {
WholeDay {
teacher: Option<String>,
teacher_code: String,
},
Single {
teacher: Option<String>,
teacher_code: String,
hours: u16,
},
Range {
teacher: Option<String>,
teacher_code: String,
hours: AbsenceRange,
},
Exkurze {
teacher: Option<String>,
teacher_code: String,
},
Zastoupen {
teacher: Option<String>,
teacher_code: String,
zastupuje: SubstituteInfo,
},
Invalid { original: String },
}
pub struct AbsenceRange {
pub from: u16,
pub to: u16,
}
pub struct SubstituteInfo {
pub teacher: Option<String>,
pub teacher_code: String,
}
pub struct ChangeEntry {
pub text: String,
pub background_color: Option<String>,
pub foreground_color: Option<String>,
pub will_be_specified: Option<bool>,
}
pub struct ApiResponse {
pub status: Status,
pub schedule: HashMap<String, DailyData>,
}
pub struct DailyData {
pub info: DayInfo,
pub changes: HashMap<String, Vec<Option<ChangeEntry>>>,
pub absence: Vec<AbsenceEntry>,
pub takes_place: String,
pub reserved_rooms: Vec<Option<String>>,
}
pub struct DayInfo {
pub in_work: bool,
}
pub struct Status {
pub last_updated: String,
pub current_update_schedule: u16,
}
pub struct SuplResult {
pub status: Status,
pub schedule: HashMap<String, DailySchedule>,
}
pub struct DailySchedule {
pub info: DayInfo,
pub changes: Vec<Option<ChangeEntry>>,
pub absence: Vec<AbsenceEntry>,
pub takes_place: String,
}
pub struct TeacherAbsenceResult {
pub absences: HashMap<String, Vec<AbsenceEntry>>,
}
```
## Mappings do jiných jazyků
### Kotlin
- [Mappings (required)](https://mvnrepository.com/artifact/cz.jzitnik/jecna-supl-client)
Jednotlivé buildy:
- [Android](https://mvnrepository.com/artifact/cz.jzitnik/jecna-supl-client-android)
- [Linux X64](https://mvnrepository.com/artifact/cz.jzitnik/jecna-supl-client-linux-x64)
- [Windows X64](https://mvnrepository.com/artifact/cz.jzitnik/jecna-supl-client-windows-x64)
Všechny funkce jsou mappovány do `camelCase`. **Nejedná se o suspend funkce!**

View File

@@ -6,6 +6,10 @@ tags: ["api", "docs"]
Vítejte v dokumentaci pro API systému Ječná Rozvrh. Toto API poskytuje programový přístup k rozvrhům, suplování a dalším informacím.
## Oficiální knihovna
[Oficiální knihovna pro komunikaci s Ječná Rozvrh API](../lib)
## Základní Informace
### URL
@@ -18,21 +22,29 @@ Kořenový endpoint (`/`) je **zastaralý (deprecated)**.
Ačkoliv v současnosti vrací stejná data jako `/versioned/v1`, jeho podpora může být v budoucnu ukončena. **Prosím, nepoužívejte tento endpoint pro nové projekty a existující projekty aktualizujte na verzované endpointy.**
**Tento endpoint vrací V1 pouze pokud se nejedná o UserAgent prohlížeče. Pokud se detekuje prohlížeč, vrátí se webová stránka.**
---
## Dostupné Verze API
API je verzované, aby byla zajištěna zpětná kompatibilita. Zde je seznam dostupných verzí:
- ### [Verze 2 (v2)](../api-usage-v2)
- ### [Verze 3 (v2)](../v3)
**Status:** Stabilní
**Endpoint:** `/versioned/v3`
Toto je aktuální a doporučená verze API. Obsahuje velké změny oproti V2 a obsahuje nové data.
- ### [Verze 2 (v2)](../v2)
**Status:** Stabilní
**Endpoint:** `/versioned/v2`
- ### [~Verze 1 (v1)~](../v1)
**Status:** Deprecated
**Endpoint:** `/versioned/v1`
Toto je aktuální a doporučená verze API. Klikněte na odkaz pro zobrazení kompletní dokumentace pro v2.
- ### [Verze 1 (v1)](../api-usage-v1)
**Status:** Stabilní
**Endpoint:** `/versioned/v1`
Verze 1 bude v budoucnu odstaněna. Migrujte na novější verze
---
@@ -74,6 +86,7 @@ Požadavek musí obsahovat JSON objekt s následujícími poli:
- `class` (string, povinné): Název třídy, které se hlášení týká.
- `location` (string, povinné): Místo, kde se chyba vyskytla. Povolené hodnoty jsou:
- `"TIMETABLE"`
- `"TAKES_PLACE"`
- `"ABSENCES"`
- `"OTHER"`
- `content` (string, povinné): Popis problému.

View File

@@ -5,6 +5,10 @@ tags: ["api", "docs", "v1"]
hiddenInHomelist: true
---
{{< admonition type="warning" title="Deprecated" >}}
Tato verze je **deprecated**. Prosím nepoužívejte ji, bude brzy odstraněna.
{{< /admonition >}}
Tato stránka detailně popisuje **Verzi 1 (v1)** API Ječná Rozvrh.
## Endpoint: `GET /versioned/v1`
@@ -39,7 +43,7 @@ Tato sekce je pole, kde každý prvek představuje jeden den. Každý den je obj
- **Klíč:** Název třídy (např. `"A1"`)
- **Hodnota:** Pole s 10 prvky, které reprezentují 10 vyučovacích hodin.
- `string`: Pokud je hodina normálně vyučována, obsahuje název předmětu nebo informaci o změně.
- `null`: Pokud hodina odpadá nebo pro ni není záznam.
- `null`: Pokud pro ni není záznam.
- Text `(bude upřesněno)` může být připojen k předmětu, pokud je změna nejistá.
<details>

View File

@@ -39,7 +39,7 @@ Tato sekce je pole, kde každý prvek představuje jeden den. Každý den je obj
- **Klíč:** Název třídy (např. `"A1"`)
- **Hodnota:** Pole s 10 prvky, které reprezentují 10 vyučovacích hodin.
- `string`: Pokud je hodina normálně vyučována, obsahuje název předmětu nebo informaci o změně.
- `null`: Pokud hodina odpadá nebo pro ni není záznam.
- `null`: Pokud pro ni není záznam.
- Text `(bude upřesněno)` může být připojen k předmětu, pokud je změna nejistá.
<details>

View File

@@ -0,0 +1,193 @@
---
title: "API Dokumentace - Verze 2"
date: 2026-01-28
tags: ["api", "docs", "v2"]
hiddenInHomelist: true
---
Tato stránka detailně popisuje **Verzi 2 (v2)** API Ječná Rozvrh.
## Endpoint: `GET /versioned/v3`
Toto je hlavní endpoint, který poskytuje veškerá data o rozvrhu pro v2.
### Struktura Odpovědi
Odpověď je JSON objekt, který obsahuje dva hlavní klíče: `schedule` a `status`.
<details>
<summary>Zobrazit příklad struktury odpovědi</summary>
```json
{
"schedule": { /* objekt denních rozvrhů */ },
"status": { /* objekt stavu */ }
}
```
</details>
---
### Datové Struktury
#### Sekce: `schedule`
Tato sekce je objekt, kde každý klíč představuje datum ve formátu `YYYY-MM-DD` a prvek představuje jeden den. Každý den je objekt, jehož klíče jsou `info`, `changes`, `absence`, `takesPlace` a `reservedRooms`
##### `changes`
- Objekt
- **Klíč:** Název třídy (např. `"A1"`)
- **Hodnota:** Pole s 10 prvky, které reprezentují 10 vyučovacích hodin.
- Objekt: Pokud je hodina normálně vyučována, obsahuje název předmětu nebo informaci o změně.
- `null`: Pokud pro ni není záznam.
Hodnota je následující objekt
```ts
{
text: string,
backgroundColor?: string,
foregroundColor?: string,
willBeSpecified?: boolean
}
```
<details>
<summary>Zobrazit příklad rozvrhu pro třídu A1</summary>
```json
"A1": [
{
"text": "M 5 Kp(Ng)"
},
null,
null,
{
"text": "M 5 odpadá",
"backgroundColor": "#DCEDD5",
"foregroundColor": "#FF000000"
},
null,
null,
null,
null,
null,
null
]
```
</details>
##### `absence`
- Pole objektů, kde každý objekt specifikuje jednu absenci. Struktura objektu je následující:
- `teacher` (string | null): Celé jméno učitele, pokud je známé.
- `teacherCode` (string | null): Zkratka jména učitele (např. "me", "ad").
- `type` (string): Typ absence. Může nabývat následujících hodnot:
- `"wholeDay"`: Učitel chybí celý den.
- `"single"`: Učitel chybí jednu vyučovací hodinu.
- `"range"`: Učitel chybí v rozmezí několika hodin.
- `"exkurze"`: Učitel je na exkurzi.
- `"invalid"`: Záznam o absenci se nepodařilo zpracovat.
- `hours` (object | number | null): Specifikuje hodiny absence.
- `null`: Pro typy `wholeDay`, `exkurze`, a `invalid`.
- `number` (např. `3`): Pro typ `single`.
- `object` (např. `{ "from": 2, "to": 4 }`): Pro typ `range`.
- `original` (string | null): Pouze pro typ `invalid`, obsahuje původní nezpracovaný text.
<details>
<summary>Zobrazit příklady absencí</summary>
**Celý den:**
```json
{
"teacher": "Jan Novák",
"teacherCode": "no",
"type": "wholeDay",
"hours": null
}
```
**Jedna hodina:**
```json
{
"teacher": "Jan Novák",
"teacherCode": "no",
"type": "single",
"hours": 1
}
```
**Rozsah hodin:**
```json
{
"teacher": "Jan Novák",
"teacherCode": "no",
"type": "range",
"hours": { "from": 2, "to": 4 }
}
```
**Exkurze:**
```json
{
"teacher": "Jan Novák",
"teacherCode": "no",
"type": "exkurze",
"hours": null
}
```
**Zastupuje:**
```json
{
"teacher": "Ing. Zdeněk Vondra",
"teacherCode": "vn",
"type": "zastoupen",
"hours": null,
"zastupuje": {
"teacher": "David Janoušek",
"teacherCode": "jk",
},
},
```
**Neplatný záznam:**
```json
{
"type": "invalid",
"teacher": null,
"teacherCode": null,
"hours": null,
"original": "Nezpracovatelný text"
}
```
</details>
##### `takesPlace`
String obsahující aktuálně probíhající akce ten den.
#### `reservedRooms`
Pole 10 prvků (string | null) pro jakou hodinu jsou rezervované jaké místnosti.
#### `info.inWork`
Boolean jestli je daná tabulka in work (příprava).
#### Sekce: `status` - Stav a Metadata
Objekt poskytující informace o aktuálnosti dat.
- `lastUpdated` (string): Čas poslední úspěšné aktualizace dat ve formátu `HH:MM`.
- `currentUpdateSchedule` (number): Interval v **minutách**, ve kterém scraper interně kontroluje a stahuje novou verzi rozvrhu. Tento interval se dynamicky mění v závislosti na denní době (kratší během vyučování, delší v noci).
<details>
<summary>Zobrazit příklad status</summary>
```json
"status": {
"lastUpdated": "08:30",
"currentUpdateSchedule": 5
}
```
</details>

View File

@@ -0,0 +1,90 @@
---
title: "Self-hosting"
date: 2026-02-11
tags: ["hosting", "setup"]
---
Tento projekt je možné hostovat vlastním způsobem, ať už pomocí Dockeru nebo nativně.
## Požadavky
Před začátkem se ujistěte, že máte připravené následující:
- **Účet SPŠE Ječná**: Projekt vyžaduje platný školní e-mail a heslo pro přístup k tabulce na SharePointu.
- **Node.js 22+**: Pokud hostujete nativně.
- **Hugo**: Pro sestavení a provoz webového rozhraní.
- **Chromium/Puppeteer**: Pro automatizované stahování dat.
## Způsoby hostování
### Docker (Doporučeno)
Použití Dockeru je nejjednodušší způsob, jak projekt spustit, protože automaticky řeší všechny závislosti včetně prohlížeče pro Puppeteer.
1. **Klonování repozitáře**:
```bash
git clone https://github.com/zitnik/jecnarozvrh.git
cd jecnarozvrh
```
2. **Konfigurace**:
Upravte soubor `docker-compose.yml` a doplňte své přihlašovací údaje:
```yaml
services:
app:
environment:
- EMAIL=vas-email@spsejecna.cz
- PASSWORD=vase-heslo
```
3. **Spuštění**:
```bash
docker-compose up -d --build
```
Aplikace bude dostupná na portu `3000`.
> **Poznámka k webu v Dockeru**: Výchozí Docker image má `SERVE_WEB` nastaveno na `false`, protože neobsahuje Hugo pro sestavení webové části. Docker verze primárně slouží jako API server.
### Nativní instalace
Pokud nechcete používat Docker, můžete projekt spustit přímo na svém systému.
1. **Instalace závislostí**:
```bash
npm install
```
2. **Sestavení projektu**:
Tento krok zkompiluje TypeScript a sestaví Hugo web.
```bash
npm run build
```
3. **Nastavení proměnných prostředí**:
Vytvořte soubor `.env` v kořenovém adresáři:
```env
EMAIL=vas-email@spsejecna.cz
PASSWORD=vase-heslo
PORT=3000
```
4. **Spuštění**:
```bash
npm run serve
```
## Environmental variables
| Proměnná | Popis | Výchozí hodnota |
|----------|-------|-----------------|
| `EMAIL` | Školní e-mail pro přihlášení. | - |
| `PASSWORD` | Heslo k e-mailu. | - |
| `SHAREPOINT_URL` | Odkaz na Excel tabulku na SharePointu. | *Předdefinovaný odkaz na nástěnku* |
| `PORT` | Port, na kterém server poběží. | `3000` |
| `REPORT_WEBHOOK_URL` | URL pro webhook hlášení chyb (Discord/Slack). | - |
| `SERVE_WEB` | Určuje, zda se má serveovat Hugo web. | `true` |
## Persitence dat
Veškerá stažená data a stav prohlížeče (včetně cookies) se ukládají do složky `volume/`. Při použití Dockeru je důležité tuto složku mapovat jako volume, aby nedocházelo k opakovanému přihlašování a stahování dat při každém restartu.

View File

@@ -13,7 +13,7 @@ mainsections: ["posts", "papermod"]
minify:
disableXML: true
# minifyOutput: true
minifyOutput: true
pagination:
disableAliases: false
@@ -59,8 +59,13 @@ params:
Content: >
Webová stránka SPŠE Ječná Rozvrh API pro získávání mimořádného rozvrhu v rozumném formátu.
- **Toto API je NEOFICIÁLNǏ a nemá nic společného s oficiálním softwarem školy**.
- **Toto API je NEOFICIÁLNÍ a nemá nic společného s oficiálním softwarem školy**.
footer:
text: >
Licencováno pod [GNU GPL v3.0](https://www.gnu.org/licenses/gpl-3.0.html)
copyright: "© 2026 [Jakub Žitník](https://jzitnik.dev)"
markup:
goldmark:

View File

View File

@@ -0,0 +1,78 @@
{{ $type := .Get "type" | default "note" }}
{{ $title := .Get "title" | default (print (title $type)) }}
<div class="alert alert-{{ $type }}">
<div class="alert-title">
{{ $title }}
</div>
<div class="alert-content">
{{ .Inner | markdownify }}
</div>
</div>
<style>
.alert {
margin: 1.5rem 0;
padding: 1rem;
border-left: 4px solid;
border-radius: 0.5rem;
background-color: #2e2e33;
color: #ebebeb;
}
/* Title */
.alert-title {
font-weight: 600;
margin-bottom: 0.5rem;
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 2rem;
}
.alert-content {
font-size: 1.1rem;
line-height: 1.6;
max-width: 100%;
}
.alert-content p {
margin: 0.5em 0;
}
.alert-content a {
color: #7dd3fc;
text-decoration: underline;
}
.alert-content code {
background: #2a2a2a;
padding: 0.15em 0.35em;
border-radius: 4px;
font-size: 0.85em;
}
.alert-content pre {
background: #111;
padding: 0.75rem;
border-radius: 6px;
overflow-x: auto;
}
.alert-note {
border-color: #31929A;
}
.alert-warning {
border-color: #eab308;
}
.alert-danger {
border-color: #ef4444;
}
.alert-success {
border-color: #22c55e;
}
</style>