1
0

Compare commits

..

4 Commits

Author SHA1 Message Date
f34db1c6e8 chore: Started implementing 2026-02-02 08:36:43 +01:00
e78ee594a0 chore: Idk 2026-01-30 19:18:04 +01:00
16f6eef215 fix: Login await 2026-01-30 18:25:46 +01:00
4a3f1e9f4e feat: Load statis schedule 2026-01-30 18:19:44 +01:00
28 changed files with 1465 additions and 1611 deletions

View File

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

7
.gitignore vendored
View File

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

View File

@@ -1,19 +1,23 @@
FROM node:22
# Use official Node.js image as base
FROM node:18
# 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 . .
RUN npm ci
RUN npm run build-noweb
RUN npm prune --production
COPY dist dist
# Expose the port your app runs on (optional, depends on your app)
EXPOSE 3000
ENV SERVE_WEB=false
CMD ["npm", "run", "serve"]
# Start the app
CMD ["npm", "start"]

View File

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

View File

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

1638
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,14 +7,16 @@
"type": "module",
"main": "server.js",
"scripts": {
"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"
"test": "node tests/test.js",
"start": "concurrently \"node server.js\" \"node cron-runner.js\"",
"build": "cd web && hugo --gc --minify",
"dev-web": "cd web && hugo serve",
"setup-static": "node scripts/loadstaticschedule.js"
},
"dependencies": {
"@google/genai": "^1.38.0",
"axios": "^1.13.4",
"axios-cookiejar-support": "^6.0.5",
"body-parser": "^2.2.0",
"cheerio": "^1.1.2",
"concurrently": "^9.2.0",
@@ -22,20 +24,9 @@
"dotenv": "^17.2.3",
"exceljs": "^4.4.0",
"express": "^5.1.0",
"jszip": "^3.10.1",
"node-cron": "^4.2.1",
"node-fetch": "^3.3.2",
"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"
"tough-cookie": "^6.0.0"
}
}

View File

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

View File

@@ -13,9 +13,9 @@
*/
import parseV1V2 from "./parse/v1_v2.js";
import parseV3 from "./parse/v3.js";
import parseV3 from "./parse/v3/v3.js";
export default async function parseThisShit(downloadedFilePath: string) {
export default async function parseThisShit(downloadedFilePath) {
await parseV1V2(downloadedFilePath);
await parseV3(downloadedFilePath);
await parseV3("db/v2.json"); // NEEDS TO BE RAN AFTER V2 (uses its format)
}

View File

@@ -12,27 +12,17 @@
* GNU General Public License for more details.
*/
import ExcelJS, { Worksheet, Cell } from "exceljs"
import ExcelJS from "exceljs"
import fs from "fs"
import parseAbsence, { AbsenceResult } from "../utils/parseAbsence.js"
import parseAbsence from "../utils/parseAbsence.js"
import parseTeachers from "../utils/parseTeachers.js"
interface DatedSheet {
sheet: Worksheet;
dateKey: string;
}
interface ScheduleDay {
[key: string]: any;
ABSENCE?: AbsenceResult[];
}
export default async function parseV1V2(downloadedFilePath: string) {
export default async function parseV1V2(downloadedFilePath) {
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*(\d{4}|\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*(20\d{2})/i;
// Get today's date for comparison
function getCurrentDateObject() {
@@ -42,15 +32,15 @@ export default async function parseV1V2(downloadedFilePath: string) {
const today = getCurrentDateObject();
const datedSheets: DatedSheet[] = [];
const datedSheets = [];
for (const sheet of workbook.worksheets) {
const match = sheet.name.toLowerCase().match(dateRegex);
const match = sheet.name.match(dateRegex);
if (!match) continue;
const day = parseInt(match[2], 10);
const month = parseInt(match[3], 10) - 1;
const year = match[4].length === 2 ? Number('20' + match[4]) : Number(match[4]);
const year = parseInt(match[4], 10);
const sheetDate = new Date(year, month, day);
if (sheetDate < today) continue;
@@ -63,7 +53,7 @@ export default async function parseV1V2(downloadedFilePath: string) {
});
}
const sheetsByDate: Record<string, Worksheet[]> = {};
const sheetsByDate = {};
for (const item of datedSheets) {
sheetsByDate[item.dateKey] ??= [];
sheetsByDate[item.dateKey].push(item.sheet);
@@ -71,23 +61,20 @@ export default async function parseV1V2(downloadedFilePath: string) {
const upcomingSheets = Object.values(sheetsByDate).map((sheets) => {
if (sheets.length === 1) return sheets[0].name;
const found = sheets.find((s) => s.state !== "hidden");
return (found ?? sheets[0]).name;
return (sheets.find((s) => s.state !== "hidden") ?? sheets[0]).name;
});
const final: ScheduleDay[] = [];
const final = [];
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: string[] = [];
const matchingKeys: string[] = [];
const classes = [];
const matchingKeys = [];
currentSheet.eachRow((row) => {
row.eachCell((cell) => {
@@ -108,7 +95,7 @@ export default async function parseV1V2(downloadedFilePath: string) {
})
})
function letterToNumber(letter: string) {
function letterToNumber(letter) {
return letter.toLowerCase().charCodeAt(0) - "a".charCodeAt(0);
}
@@ -117,20 +104,17 @@ export default async function parseV1V2(downloadedFilePath: string) {
for (const matchingKey of matchingKeys) {
const matchingCell = currentSheet.getCell(matchingKey);
const rowNumber = matchingCell.row;
const allKeys: string[] = [];
const allKeys = [];
// Get all cells in the same row
const row = currentSheet.getRow(Number(rowNumber));
const row = currentSheet.getRow(rowNumber);
row.eachCell((cell) => {
if (cell.address !== matchingKey) {
allKeys.push(cell.address);
}
})
// 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)[] = [];
let final2 = [];
for (const key of allKeys) {
const cell = currentSheet.getCell(key);
@@ -140,16 +124,13 @@ export default async function parseV1V2(downloadedFilePath: string) {
try {
const regex = /^úklid\s+(?:\d+\s+)?[A-Za-z]{2}$/;
const cellText = cell.text || "";
// @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) {
if (regex.test(cellText.trim()) || cellText.trim().length == 0 || cell.fill?.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)";
}
@@ -159,19 +140,19 @@ export default async function parseV1V2(downloadedFilePath: string) {
}
}
const final2Array = Array.from(final2, (item) => (item === undefined ? null : item));
while (final2Array.length < 10) {
final2Array.push(null);
final2 = Array.from(final2, (item) => (item === undefined ? null : item));
while (final2.length < 10) {
final2.push(null);
}
final[finalIndex][classes[classI]] = final2Array.slice(1, 11);
final[finalIndex][classes[classI]] = final2.slice(1, 11);
classI++;
}
// ABSENCE
final[finalIndex]["ABSENCE"] = [];
let absenceKey: string | null = null;
let absenceKey = null;
currentSheet.eachRow((row) => {
row.eachCell((cell) => {
@@ -185,21 +166,22 @@ export default async function parseV1V2(downloadedFilePath: string) {
if (absenceKey) {
const absenceCell = currentSheet.getCell(absenceKey);
const rowNumber = absenceCell.row;
const allAbsenceKeys: string[] = [];
const allAbsenceKeys = [];
// Get all cells in the same row as absence
const row = currentSheet.getRow(Number(rowNumber));
const row = currentSheet.getRow(rowNumber);
row.eachCell((cell) => {
if (cell.address !== absenceKey) { // absenceKey is checked above to be non-null
if (cell.address !== absenceKey) {
allAbsenceKeys.push(cell.address);
}
})
const absenceRange = new Set(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L"])
let i = 0;
for (const absenceKeyCur of allAbsenceKeys) {
if (!absenceRange.has(absenceKeyCur.substring(0, 1))) {
break;
};
if (i >= 10) {
break; // stop once 10 items are added
}
i++;
const cell = currentSheet.getCell(absenceKeyCur);
const value = (cell.value || "").toString().trim();
@@ -208,9 +190,7 @@ export default async function parseV1V2(downloadedFilePath: string) {
}
const data = parseAbsence(value, teacherMap);
if (final[finalIndex]["ABSENCE"]) {
final[finalIndex]["ABSENCE"]!.push(...data);
}
final[finalIndex]["ABSENCE"].push(...data);
}
}
@@ -223,14 +203,14 @@ export default async function parseV1V2(downloadedFilePath: string) {
const data = {
schedule: final,
props: upcomingSheets.map((str) => {
const dateMatch = str.match(/(\d{1,2})\.\s*(\d{1,2})\.\s*(\d{4}|\d{2})/);
const dateMatch = str.match(/(\d{1,2})\.\s*(\d{1,2})\.\s*(\d{4})/);
let date = null;
if (dateMatch) {
const day = Number.parseInt(dateMatch[1], 10);
const month = Number.parseInt(dateMatch[2], 10);
const year = dateMatch[3].length === 2 ? Number('20' + dateMatch[3]) : Number(dateMatch[3]);
const year = Number.parseInt(dateMatch[3], 10);
date = new Date(year, month - 1, day);
}
@@ -253,15 +233,15 @@ export default async function parseV1V2(downloadedFilePath: string) {
}
}
fs.writeFileSync("volume/db/v2.json", JSON.stringify(data, null, 2));
fs.writeFileSync("db/v2.json", JSON.stringify(data, null, 2));
// Modify the data for v1
const copy = JSON.parse(JSON.stringify(data));
copy.schedule.forEach((day: ScheduleDay) => {
copy.schedule.forEach(day => {
if (!Array.isArray(day.ABSENCE)) return;
day.ABSENCE = day.ABSENCE.map((old: any) => {
day.ABSENCE = day.ABSENCE.map(old => {
if (old.type === "zastoupen") {
return {
type: "invalid",
@@ -275,7 +255,7 @@ export default async function parseV1V2(downloadedFilePath: string) {
});
});
fs.writeFileSync("volume/db/v1.json", JSON.stringify(copy, null, 2))
fs.writeFileSync("db/v1.json", JSON.stringify(copy, null, 2))
}
//parseV1V2("db/current.xlsx")

View File

@@ -1,427 +0,0 @@
/*
* 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")

73
scrape/parse/v3/call.js Normal file
View File

@@ -0,0 +1,73 @@
/*
* 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 { GoogleGenAI } from "@google/genai";
import fs from "fs/promises";
const TIMETABLE_PATH = "db/persistent/timetables.json";
export async function setup() {
const timetable = JSON.parse(
await fs.readFile(TIMETABLE_PATH, { encoding: "utf8" })
);
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY
});
const systemPrompt = await fs.readFile("./prompt.txt", "utf-8");
/**
* @param {Object} changesByClass
* {
* "1A": [ ...changes... ],
* "2B": [ ...changes... ]
* }
* @param {number} dayIndex
*/
return async (changesByClass, dayIndex) => {
const input = {};
for (const cls of Object.keys(changesByClass)) {
input[cls] = {
stableSchedule: timetable[cls][dayIndex],
changes: changesByClass[cls]
};
}
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
config: {
systemInstruction: {
parts: [{ text: systemPrompt }]
},
temperature: 0
},
contents: [
{
role: "user",
parts: [{ text: JSON.stringify(input) }]
}
]
});
const aiOutput = response.text ?? "";
try {
return JSON.parse(aiOutput);
} catch {
return { invalid: true, reason: "AI output could not be parsed" };
}
};
}

130
scrape/parse/v3/v3.js Normal file
View File

@@ -0,0 +1,130 @@
/*
* 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/promises";
import { setup } from "./call.js";
const PREVIOUS = "db/v3/_previous.json";
const FINAL = "db/v3/v3.json";
const EXCLUDE_CLASSES = new Set(["ABSENCE"]);
async function checkFileExists(filePath) {
try {
await fs.access(filePath);
return true;
} catch (err) {
return false;
}
}
function arraysAreEqual(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
}
function getTime() {
const currentDate = new Date();
return currentDate.getHours().toString().padStart(2, "0") + ":" + currentDate.getMinutes().toString().padStart(2, "0");
}
function setupFinal() {
return {
schedule: [],
status: {
lastUpdated: getTime(),
}
}
}
export default async function parseV3(fileV2Path) {
const call = await setup();
let clearRun = false;
let previousStr = "{}";
if (await checkFileExists(PREVIOUS)) {
previousStr = await fs.readFile(PREVIOUS, "utf8");
} else {
clearRun = true;
}
const now = JSON.parse(await fs.readFile(fileV2Path, "utf8"));
const previous = JSON.parse(previousStr);
const previousDays = previous.props?.map(p => p.date) || [];
let final;
if (await checkFileExists(FINAL)) {
final = JSON.parse(await fs.readFile(FINAL, "utf8"));
} else {
final = setupFinal();
clearRun = true;
}
let i = 0;
for (const prop of now.props) {
const date = new Date(prop.date);
const dayIndex = (date.getDay() + 6) % 7;
if (!final.schedule[i]) {
final.schedule[i] = {};
}
const day = now.schedule[i];
const batch = {};
for (const cls of Object.keys(day)) {
if (EXCLUDE_CLASSES.has(cls)) continue;
const newClass = day[cls];
if (clearRun || !previousDays.includes(prop.date)) {
batch[cls] = newClass;
continue;
}
const oldPropIndex = previous.props.findIndex(
p => p.date === prop.date
);
const oldClass = previous.schedule[oldPropIndex]?.[cls] || [];
if (!arraysAreEqual(oldClass, newClass)) {
batch[cls] = newClass;
}
}
if (Object.keys(batch).length > 0) {
const results = await call(batch, dayIndex);
for (const cls of Object.keys(results)) {
final.schedule[i][cls] = results[cls];
}
}
i++;
}
if (!clearRun) {
final.status.lastUpdated = getTime();
}
final.props = now.props;
await fs.writeFile(FINAL, JSON.stringify(final), "utf8");
await fs.copyFile(fileV2Path, PREVIOUS);
}
parseV3("db/v2.json");

View File

@@ -12,7 +12,7 @@
* GNU General Public License for more details.
*/
import puppeteer, { Page, Browser } from 'puppeteer';
import puppeteer from 'puppeteer';
import path from 'path';
import fs from 'fs';
import parseThisShit from './parse.js';
@@ -21,44 +21,40 @@ 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 DOWNLOAD_FOLDER = path.resolve("./volume/downloads");
const ERROR_FOLDER = path.resolve("./volume/errors")
const DB_FOLDER = path.resolve("./volume/db");
const VOLUME_PATH = path.resolve('./volume/browser');
async function clearDownloadsFolder() {
try {
await fs.promises.rm(DOWNLOAD_FOLDER, { recursive: true, force: true });
await fs.promises.mkdir(DOWNLOAD_FOLDER);
await fs.promises.rm('./downloads', { recursive: true, force: true });
await fs.promises.mkdir('./downloads');
} catch (err) {
console.error('Error:', err);
}
}
async function handleError(page: Page, err: any) {
async function handleError(page, err) {
try {
if (!fs.existsSync(ERROR_FOLDER)) fs.mkdirSync(ERROR_FOLDER);
const errorsDir = path.resolve('./errors');
if (!fs.existsSync(errorsDir)) fs.mkdirSync(errorsDir);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filePath = path.join(ERROR_FOLDER, `error-${timestamp}.png`);
const filePath = path.join(errorsDir, `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(ERROR_FOLDER)
const files = fs.readdirSync(errorsDir)
.map(f => ({
name: f,
time: fs.statSync(path.join(ERROR_FOLDER, f)).mtime.getTime()
time: fs.statSync(path.join(errorsDir, 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(ERROR_FOLDER, f.name));
fs.unlinkSync(path.join(errorsDir, f.name));
}
}
} catch (screenshotErr) {
@@ -68,22 +64,22 @@ async function handleError(page: Page, err: any) {
}
(async () => {
let browser: Browser | undefined, page: Page | undefined;
let browser, page;
try {
browser = await puppeteer.launch({
headless: true,
headless: 'new',
userDataDir: VOLUME_PATH,
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const pages = await browser.pages();
page = pages[0];
[page] = await browser.pages();
if (!fs.existsSync(DOWNLOAD_FOLDER)) fs.mkdirSync(DOWNLOAD_FOLDER);
const downloadPath = path.resolve('./downloads');
if (!fs.existsSync(downloadPath)) fs.mkdirSync(downloadPath);
const client = await page.createCDPSession();
await client.send('Page.setDownloadBehavior', {
behavior: 'allow',
downloadPath: DOWNLOAD_FOLDER,
downloadPath: downloadPath,
});
await page.goto(SHAREPOINT_URL, { waitUntil: 'networkidle2' });
@@ -95,7 +91,7 @@ async function handleError(page: Page, err: any) {
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 {
@@ -121,7 +117,7 @@ async function handleError(page: Page, err: any) {
}
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 {
@@ -137,9 +133,7 @@ async function handleError(page: Page, err: any) {
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"]');
@@ -159,7 +153,7 @@ async function handleError(page: Page, err: any) {
await new Promise(r => setTimeout(r, 10000));
function waitForFile(filename: string, timeout = 30000): Promise<void> {
function waitForFile(filename, timeout = 30000) {
return new Promise((resolve, reject) => {
const start = Date.now();
const interval = setInterval(() => {
@@ -174,7 +168,7 @@ async function handleError(page: Page, err: any) {
});
}
function getNewestFile(dir: string) {
function getNewestFile(dir) {
const files = fs.readdirSync(dir)
.map(f => ({
name: f,
@@ -184,16 +178,14 @@ async function handleError(page: Page, err: any) {
return files.length ? path.join(dir, files[0].name) : null;
}
const downloadedFilePath = getNewestFile(DOWNLOAD_FOLDER);
const downloadedFilePath = getNewestFile(downloadPath);
if (!downloadedFilePath) {
throw new Error('No XLSX file found in download folder');
}
console.log('Waiting for file:', downloadedFilePath);
await waitForFile(downloadedFilePath);
if (!fs.existsSync(DB_FOLDER)) fs.mkdirSync(DB_FOLDER);
await fs.promises.cp(downloadedFilePath, path.join(DB_FOLDER, "current.xlsx"));
await fs.promises.cp(downloadedFilePath, "db/current.xlsx");
await parseThisShit(downloadedFilePath);
await clearDownloadsFolder();

View File

@@ -17,28 +17,10 @@ const LAST_HOUR = 10;
// -------------------------------
// Helpers
// -------------------------------
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 cleanInput = (input) => (input ?? "").trim().replace(/\s+/g, " ");
export const isTeacherToken = (t) => /^[A-Za-z]+$/.test(t);
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 => {
export const parseSpec = (spec) => {
if (!spec) return null;
let m;
@@ -73,12 +55,12 @@ export const parseSpec = (spec: string | null): Spec | null => {
return null;
};
export const resolveTeacher = (teacherCode: string, teacherMap: TeacherMap = {}): { code: string; name: string | null } => ({
export const resolveTeacher = (teacherCode, teacherMap = {}) => ({
code: teacherCode,
name: teacherMap?.[teacherCode.toLowerCase()] ?? null,
});
const makeResult = (teacherCode: string, spec: Spec | null, teacherMap: TeacherMap): AbsenceResult => {
const makeResult = (teacherCode, spec, teacherMap) => {
const { name } = resolveTeacher(teacherCode, teacherMap);
const type = spec ? (spec.kind === "range" ? "range" : "single") : "wholeDay";
const hours = spec ? spec.value : null;
@@ -88,8 +70,8 @@ const makeResult = (teacherCode: string, spec: Spec | null, teacherMap: TeacherM
// -------------------------------
// Teacher list processing (modular)
// -------------------------------
const processTeacherList = (teacherListStr: string, spec: Spec | null, teacherMap: TeacherMap): AbsenceResult[] => {
let results: AbsenceResult[] = [];
const processTeacherList = (teacherListStr, spec, teacherMap) => {
let results = [];
const teachers = teacherListStr.split(/[,;]\s*/).filter(Boolean);
if (teacherListStr.includes(";")) {
@@ -107,14 +89,14 @@ const processTeacherList = (teacherListStr: string, spec: Spec | null, teacherMa
// -------------------------------
// Main parser
// -------------------------------
export default function parseAbsence(input: string, teacherMap: TeacherMap = {}): AbsenceResult[] {
export default function parseAbsence(input, teacherMap = {}) {
const s = cleanInput(input);
if (!s) return [];
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);
const results = [];
const consumed = [];
const markConsumed = (start, end) => consumed.push([start, end]);
const isConsumed = (i) => consumed.some(([a, b]) => i >= a && i < b);
// 1. Teachers with specific hours (e.g. "Ab 1-4")
const teacherListThenSpecRe =
@@ -134,51 +116,6 @@ export default function parseAbsence(input: string, teacherMap: 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) {
@@ -216,7 +153,6 @@ export default function parseAbsence(input: string, teacherMap: TeacherMap = {})
teacher: missingResolved.name,
teacherCode: missingResolved.code.toLowerCase(),
type: "zastoupen",
hours: null,
zastupuje: {
teacher: subResolved.name,
teacherCode: subResolved.code.toLowerCase()

View File

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

View File

@@ -0,0 +1,182 @@
/*
* 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 axios from "axios";
import { CookieJar } from "tough-cookie";
import { wrapper } from "axios-cookiejar-support";
import * as cheerio from "cheerio";
import { URLSearchParams } from "url";
import fs from "fs";
const BASE = "https://www.spsejecna.cz";
const PATHS = {
SET_ROLE: "/user/role",
LOGIN: "/user/login",
TEACHERS: "/ucitel",
TEACHER: teacherCode => `/ucitel/${teacherCode}`
};
const DB_PATH = "db/persistent/timetables.json";
const jar = new CookieJar();
const client = wrapper(axios.create({
baseURL: BASE,
jar,
withCredentials: true,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
}));
globalThis.File = class File {};
async function login(username, password) {
await client.get("/");
await client.get(PATHS.SET_ROLE, {
params: { role: "student" }
});
const token3Res = await client.get("/");
const token3 = token3Res.data.match(/"token3"\s+value="(\d+)"/)[1];
const form = new URLSearchParams();
form.append('user', username);
form.append('pass', password);
form.append('token3', token3);
form.append('submit', 'Přihlásit+se');
try {
const response = await client.post(PATHS.LOGIN, form.toString(), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
maxRedirects: 0
});
if (response.status == 200) {
console.log("INVALID CREDENTIALS!");
process.exit(1);
}
} catch {}
}
async function getAllTeacherCodes() {
const list = new Set();
const response = await client.get(PATHS.TEACHERS);
const $ = cheerio.load(response.data);
$("main .contentLeftColumn li, main .contentRightColumn li").each((_, el) => {
const link = $(el).find("a");
const href = link.attr("href");
if (href) {
const key = href.split("/").pop().toLowerCase();
list.add(key);
}
});
return list;
}
async function constructSchedules(allTeachers) {
const classes = {};
function setupClass(className) {
function generateArray(width, height) {
return Array.from({ length: height }, () => Array.from({ length: width }, () => []));
}
classes[className] = generateArray(10, 5);
}
let idk = 0;
for (const key of allTeachers) {
idk++;
const response = await client.get(PATHS.TEACHER(key));
const $ = cheerio.load(response.data);
const tbody = $('table.timetable > tbody');
if (!tbody.length) {
console.log(`ERROR: ${key}`)
continue;
}
tbody.find('tr').slice(1).each((dayIndex, tr) => {
const $tr = $(tr);
let currentHour = 0;
$tr.find('td').each((_, td) => {
const $td = $(td);
const colspan = parseInt($td.attr('colspan') || '1', 10);
const $subject = $td.find('span.subject');
const $class = $td.find('span.class');
const $group = $td.find('span.group');
const $room = $td.find('a.room');
const $employee = $td.find('a.employee');
const hasData = $subject.length && $class.length && $room.length && $employee.length;
let cellData = null;
let classText = '';
if (hasData) {
classText = $class.text().trim();
cellData = {
subject: $subject.text().trim(),
title: $subject.attr('title')?.trim() || '',
group: $group.length ? $group.text().trim() : null,
room: $room.text().trim(),
teacher: {
code: $employee.text().trim().toLowerCase(),
name: $employee.attr('title')?.trim() || ''
}
};
}
for (let i = 0; i < colspan; i++) {
if (currentHour >= 10) {
break;
}
if (hasData && cellData) {
if (classes[classText] === undefined) {
setupClass(classText);
}
classes[classText][dayIndex][currentHour].push(cellData);
}
currentHour++;
}
});
});
console.log(`DONE: ${idk}/${allTeachers.size}`)
}
return classes;
}
await login(process.env.USERNAME, process.env.PASSWORD);
const allTeachers = await getAllTeacherCodes();
const schedule = await constructSchedules(allTeachers)
const str = JSON.stringify(schedule);
fs.writeFileSync(DB_PATH, str, {
encoding: "utf8"
});

28
scripts/setup.js Normal file
View File

@@ -0,0 +1,28 @@
/*
* 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";
const DIRS = [
"db/persistent",
"db/v3",
];
for (const dir of DIRS) {
try {
fs.mkdirSync(dir);
} catch {}
}
// LEAVE ME ALONE I KNOW THIS CODE IS SHIT

View File

@@ -12,7 +12,7 @@
* GNU General Public License for more details.
*/
import express, { Request, Response } from "express";
import express from "express";
import path from "path";
const app = express();
import fs from "fs/promises";
@@ -20,14 +20,9 @@ import { getCurrentInterval } from "./scheduleRules.js";
import bodyParser from "body-parser";
import cors from "cors";
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 VERSIONS = ["v1", "v2"];
const PORT = process.env.PORT || 3000;
// @ts-ignore
globalThis.File = class File {};
app.use(bodyParser.json());
@@ -38,14 +33,14 @@ app.use(cors({
allowedHeaders: ["Content-Type"],
}));
app.get('/', async (req: Request, res: Response) => {
app.get('/', async (req, res) => {
const userAgent = req.headers['user-agent'] || '';
const isBrowser = /Mozilla|Chrome|Firefox|Safari|Edg/.test(userAgent);
if (isBrowser && SERVE_WEB) {
res.sendFile(path.join(WEB_FOLDER, "index.html"));
if (isBrowser) {
res.sendFile(path.join(process.cwd(), "web", "public", "index.html"));
} else {
const dataStr = await fs.readFile(path.join(DB_FOLDER, "v1.json"), "utf8");
const dataStr = await fs.readFile(path.join(process.cwd(), "db", "v1.json"), "utf8");
const data = JSON.parse(dataStr);
data["status"]["currentUpdateSchedule"] = getCurrentInterval();
@@ -55,9 +50,9 @@ app.get('/', async (req: Request, res: Response) => {
});
VERSIONS.forEach((version) => {
app.get(`/versioned/${version}`, async (_: Request, res: Response) => {
app.get(`/versioned/${version}`, async (_, res) => {
try {
const filePath = path.join(DB_FOLDER, `${version}.json`);
const filePath = path.join(process.cwd(), "db", `${version}.json`);
const dataStr = await fs.readFile(filePath, "utf8");
const data = JSON.parse(dataStr);
@@ -71,7 +66,7 @@ VERSIONS.forEach((version) => {
});
});
app.get("/status", async (_: Request, res: Response) => {
app.get("/status", async (_, res) => {
const dataStr = await fs.readFile(path.resolve("./volume/customState.json"), {encoding: "utf8"});
const data = JSON.parse(dataStr);
@@ -82,22 +77,17 @@ app.get("/status", async (_: Request, res: Response) => {
}
})
app.post("/report", async (req: Request, res: Response): Promise<any> => {
app.post("/report", async (req, res) => {
const { class: className, location, content } = req.body;
if (!className || !location || !content) {
return res.status(400).json({ error: "Missing required fields." });
}
if (!["TIMETABLE", "ABSENCES", "ABSENCE", "TAKES_PLACE", "OTHER"].includes(location)) {
if (!["TIMETABLE", "ABSENCES", "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, {
@@ -107,7 +97,7 @@ app.post("/report", async (req: Request, res: Response): Promise<any> => {
},
body: `${content}\n\nClass: ${className}\nLocation: ${location}`,
});
} catch (err: any) {
} catch (err) {
console.error('Fetch failed:', err.message);
console.error(err);
throw err;
@@ -120,12 +110,10 @@ app.post("/report", async (req: Request, res: Response): Promise<any> => {
res.status(200).json({ message: "Report received successfully." });
});
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,8 +15,7 @@
import fs from "fs";
import parseAbsence from "../scrape/utils/parseAbsence.js";
const teachermap: Record<string, string> = JSON.parse(fs.readFileSync("./tests/teachermap.json", "utf8"));
let passedAll = true;
const teachermap = JSON.parse(fs.readFileSync("./teachermap.json"));
test("Me", [
{
@@ -233,7 +232,6 @@ test("za Vn zastupuje Jk", [
teacher: "Ing. Zdeněk Vondra",
teacherCode: "vn",
type: "zastoupen",
hours: null,
zastupuje: {
teacher: "David Janoušek",
teacherCode: "jk",
@@ -250,55 +248,18 @@ test("Vc 1. h", [
},
]);
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[]) {
function test(input, expectedOutput) {
const res = parseAbsence(input, teachermap);
if (!deepEqual(res, expectedOutput)) {
passedAll = false;
console.error("ERROR for input: " + input);
console.log(JSON.stringify(res, null, 2));
console.log(JSON.stringify(expectedOutput, null, 2));
console.log(res);
console.log(expectedOutput);
console.log();
}
}
function deepEqual(a: any, b: any): boolean {
function deepEqual(a, b) {
if (a === b) return true;
if (
@@ -337,7 +298,3 @@ function deepEqual(a: any, b: any): boolean {
return keysA.every((key) => keysB.includes(key) && deepEqual(a[key], b[key]));
}
if (passedAll) {
console.log("All tests passed");
}

View File

@@ -1,20 +0,0 @@
{
"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

@@ -18,21 +18,19 @@ 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)](../v2)
- ### [Verze 2 (v2)](../api-usage-v2)
**Status:** Stabilní
**Endpoint:** `/versioned/v2`
**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)](../v1)
- ### [Verze 1 (v1)](../api-usage-v1)
**Status:** Stabilní
**Endpoint:** `/versioned/v1`
@@ -76,7 +74,6 @@ 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

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

View File

@@ -1,90 +0,0 @@
---
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Š 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,13 +59,8 @@ 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: