1
0

Compare commits

...

35 Commits

Author SHA1 Message Date
4fccc793bb docs: Fix url
All checks were successful
Remote Deploy / deploy (push) Successful in 2m0s
2026-02-22 17:34:46 +01:00
7c75a8a485 chore: Remove
All checks were successful
Remote Deploy / deploy (push) Successful in 1m28s
2026-02-12 20:21:20 +01:00
df9fa7c605 chore: Some minor website modification changes
All checks were successful
Remote Deploy / deploy (push) Successful in 1m5s
2026-02-12 20:18:37 +01:00
793cce4ae7 chore: Idk
All checks were successful
Remote Deploy / deploy (push) Successful in 20s
2026-02-12 18:17:01 +01:00
e9ea35a064 feat: Integrate
All checks were successful
Remote Deploy / deploy (push) Successful in 36s
2026-02-12 18:08:15 +01:00
cea8cdf4ee feat: Added viewer 2026-02-12 17:45:47 +01:00
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
71 changed files with 18041 additions and 234 deletions

View File

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

View File

@@ -1,3 +1,6 @@
EMAIL=username@spsejecna.cz
PASSWORD=mojesupertajneheslo
SHAREPOINT_URL=https://spsejecnacz.sharepoint.com/:x:/s/nastenka/ESy19K245Y9BouR5ksciMvgBu3Pn_9EaT0fpP8R6MrkEmg
# For the viewer
API_URl=http://localhost:3000

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

@@ -2,12 +2,6 @@
Jednoduchý parser pro SPŠE Ječná tabulku suplování.
## Environmental variables
## Self-hosting
- `SHAREPOINT_URL` - URL adresa sharepointu dané tabulky (volitelné, využije hard-coded URL)
- `EMAIL` - SPŠE Ječná account email (povinné, username@spsejecna.cz)
- `PASSWORD` - Heslo k SPŠE Ječná účtu
## Spouštění serveru
Just `npm start` 💀
[Dokumentace zde](https://jecnarozvrh.jzitnik.dev/posts/self-hosting/)

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

2612
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,20 +7,45 @@
"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",
"dev-web": "cd web && hugo serve"
"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 && cd ../viewer && npm run build",
"build-noweb": "tsc",
"serve": "concurrently \"node dist/server.js\" \"node dist/cron-runner.js\"",
"dev-web": "cd web && hugo serve",
"parse-timetable": "node scripts/load_static_schedule.js",
"dev-preview": "tsx server.ts"
},
"dependencies": {
"axios": "^1.13.5",
"axios-cookiejar-support": "^6.0.5",
"body-parser": "^2.2.0",
"cheerio": "^1.1.2",
"cli-progress": "^3.12.0",
"concurrently": "^9.2.0",
"cors": "^2.8.6",
"dotenv": "^17.2.3",
"exceljs": "^4.4.0",
"express": "^5.1.0",
"inquirer": "^13.2.2",
"jszip": "^3.10.1",
"next": "^16.1.6",
"node-cron": "^4.2.1",
"puppeteer": "^24.10.0"
"password-prompt": "^1.1.3",
"puppeteer": "^24.10.0",
"tough-cookie": "^6.0.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/next": "^8.0.7",
"@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

@@ -15,8 +15,7 @@
import parseV1V2 from "./parse/v1_v2.js";
import parseV3 from "./parse/v3.js";
export default async function parseThisShit(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")

View File

@@ -15,21 +15,123 @@
import fs from "fs";
import parseAbsence from "../utils/parseAbsence.js"
import parseTeachers from "../utils/parseTeachers.js"
import ExcelJS from "exceljs"
import ExcelJS, { Worksheet, Cell, Row } from "exceljs"
import JSZip from "jszip";
import { parseStringPromise } from "xml2js";
export default async function parseV3(downloadedFilePath) {
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 = {};
const schedule: any = {};
for (const { dateKey, sheet } of resolvedDays) {
const { changes, absence, inWork, takesPlace, reservedRooms } = extractDaySchedule(sheet, teacherMap);
const { changes, absence, inWork, takesPlace, reservedRooms } = extractDaySchedule(sheet, teacherMap, themeColors);
schedule[dateKey] = {
info: { inWork },
@@ -45,7 +147,7 @@ export default async function parseV3(downloadedFilePath) {
schedule,
};
fs.writeFileSync("db/v3.json", JSON.stringify(data, null, 2));
fs.writeFileSync("volume/db/v3.json", JSON.stringify(data, null, 2));
}
//
@@ -54,21 +156,21 @@ export default async function parseV3(downloadedFilePath) {
// ────────────────────────────────────────────────────────────
//
function getUpcomingSheets(workbook) {
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;
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 = [];
const result: ResolvedDay[] = [];
for (const sheet of workbook.worksheets) {
const match = sheet.name.match(dateRegex);
const match = sheet.name.toLowerCase().match(dateRegex);
if (!match) continue;
const day = Number(match[2]);
const month = Number(match[3]) - 1;
const year = Number(match[4]);
const year = match[4].length === 2 ? Number('20' + match[4]) : Number(match[4]);
const sheetDate = new Date(year, month, day);
if (sheetDate < todayMidnight) continue;
@@ -80,8 +182,8 @@ function getUpcomingSheets(workbook) {
return result;
}
function groupSheetsByDate(items) {
const map = {};
function groupSheetsByDate(items: ResolvedDay[]) {
const map: Record<string, Worksheet[]> = {};
for (const item of items) {
map[item.dateKey] ??= [];
@@ -104,17 +206,17 @@ function groupSheetsByDate(items) {
// ────────────────────────────────────────────────────────────
//
function extractDaySchedule(sheet, teacherMap) {
function extractDaySchedule(sheet: Worksheet, teacherMap: Record<string, string>, themeColors: ThemeColors | null) {
return {
changes: extractClassChanges(sheet),
changes: extractClassChanges(sheet, themeColors),
absence: extractAbsence(sheet, teacherMap),
inWork: isPripravaSheet(sheet.name),
inWork: isPripravaSheet(sheet.name.toLowerCase()),
takesPlace: extractTakesPlace(sheet),
reservedRooms: extractReservedRooms(sheet)
};
}
function isPripravaSheet(name) {
function isPripravaSheet(name: string) {
return name
.toLowerCase()
.normalize("NFD")
@@ -128,12 +230,12 @@ function isPripravaSheet(name) {
// ────────────────────────────────────────────────────────────
//
function extractClassChanges(sheet) {
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 = [];
const classCells = [];
const classes: string[] = [];
const classCells: string[] = [];
sheet.eachRow((row) => {
row.eachCell((cell) => {
@@ -146,24 +248,24 @@ function extractClassChanges(sheet) {
});
});
const changes = {};
const changes: Record<string, (Lesson | null)[]> = {};
classCells.forEach((address, index) => {
const row = sheet.getRow(sheet.getCell(address).row);
changes[classes[index]] = buildLessonArray(row, address);
const row = sheet.getRow(Number(sheet.getCell(address).row));
changes[classes[index]] = buildLessonArray(row, address, themeColors);
});
return changes;
}
function buildLessonArray(row, ignoreAddress) {
const lessons = [];
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);
lessons[colIndex] = parseLessonCell(cell, themeColors);
});
const normalized = Array.from(lessons, (x) => (x === undefined ? null : x));
@@ -172,16 +274,24 @@ function buildLessonArray(row, ignoreAddress) {
return normalized.slice(1, 11);
}
function parseLessonCell(cell) {
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: cell.fill.fgColor.argb === undefined ? undefined : `#${cell.fill.fgColor.argb}`,
backgroundColor,
foregroundColor,
// @ts-ignore
willBeSpecified: cell.fill.fgColor.argb === "FFFFFF00" ? true : undefined,
};
} catch {
@@ -190,36 +300,46 @@ function parseLessonCell(cell) {
}
function extractTakesPlace(sheet) {
function extractTakesPlace(sheet: Worksheet) {
const cell = sheet.getCell("B4");
if (!cell.isMerged) {
return "";
}
let str = "";
let str = cell.master.value.trim();
let i = 5;
let i = 4;
while (true) {
const nextCell = sheet.getCell(`B${i}`);
const tryCells = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
const threshold = 20;
let con = false;
if (!nextCell.isMerged) {
break;
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;
}
}
const cell = nextCell.master
str += `\n${cell.value.trim()}`
i++;
if (con || i == 4) {
i++;
continue;
} else {
break;
}
}
return str;
return str.trim();
}
function extractReservedRooms(sheet) {
const result = [];
function extractReservedRooms(sheet: Worksheet) {
const result: (string | null)[] = [];
const cells = [];
const cells: string[] = [];
sheet.eachRow((row) => {
row.eachCell((cell) => {
@@ -231,15 +351,20 @@ function extractReservedRooms(sheet) {
});
cells.forEach((address) => {
const row = sheet.getRow(sheet.getCell(address).row);
const row = sheet.getRow(Number(sheet.getCell(address).row));
row.eachCell((cell) => {
if (cell.address === address) return;
result.push(cell.value.trim().length == 0 ? null : cell.value)
const val = cell.value?.toString().trim();
result.push(!val || val.length == 0 ? null : val)
});
});
while (result.length < 10) {
result.push(null);
}
return result;
}
@@ -249,8 +374,8 @@ function extractReservedRooms(sheet) {
// ────────────────────────────────────────────────────────────
//
function extractAbsence(sheet, teacherMap) {
let absenceAddress = null;
function extractAbsence(sheet: Worksheet, teacherMap: Record<string, string>) {
let absenceAddress: string | null = null;
sheet.eachRow((row) => {
row.eachCell((cell) => {
@@ -262,13 +387,14 @@ function extractAbsence(sheet, teacherMap) {
if (!absenceAddress) return [];
const row = sheet.getRow(sheet.getCell(absenceAddress).row);
const results = [];
let i = 0;
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 || i >= 10) return;
i++;
if (cell.address === absenceAddress || !absenceRange.has(cell.address.substring(0, 1))) {
return
};
const value = (cell.value || "").toString().trim();
if (!value) return;
@@ -285,7 +411,7 @@ function extractAbsence(sheet, teacherMap) {
// ────────────────────────────────────────────────────────────
//
function letterToNumber(letter) {
function letterToNumber(letter: string) {
return letter.toLowerCase().charCodeAt(0) - 97;
}
@@ -298,4 +424,4 @@ function formatNowTime() {
);
}
// parseV3("db/current.xlsx")
//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

@@ -0,0 +1,216 @@
/*
* 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";
import inquirer from "inquirer";
import cliProgress from "cli-progress";
const BASE = "https://www.spsejecna.cz";
const PATHS = {
SET_ROLE: "/user/role",
LOGIN: "/user/login",
TEACHERS: "/ucitel",
TEACHER: teacherCode => `/ucitel/${teacherCode}`
};
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"
}
}));
async function login(username, password) {
console.log("Logging in!");
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() {
console.log("Fetching teacher list");
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) {
console.log("Fetching teachers");
const progressBar = new cliProgress.SingleBar({
format: 'Progress |{bar}| {percentage}% || {value}/{total} steps',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true
});
progressBar.start(allTeachers.size, 0);
const classes = {};
function setupClass(className) {
function generateArray(width, height) {
return Array.from({ length: height }, () => Array.from({ length: width }, () => []));
}
classes[className.toLowerCase()] = 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().toLowerCase();
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++;
}
});
});
progressBar.update(idk);
}
progressBar.stop();
return classes;
}
const answers = await inquirer.prompt([
{
type: 'input',
name: 'username',
message: 'Enter your username:',
},
{
type: 'password',
name: 'password',
message: 'Enter your password:',
mask: '*',
},
{
type: 'input',
name: 'filePath',
message: 'Enter the file path to save:',
default: './output.json',
},
]);
await login(answers.username, answers.password);
const allTeachers = await getAllTeacherCodes();
const schedule = await constructSchedules(allTeachers)
const str = JSON.stringify(schedule);
fs.writeFileSync(answers.filePath, str, {
encoding: "utf8"
});
console.log("Done!");

View File

@@ -12,17 +12,24 @@
* 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";
import { getCurrentInterval } from "./scheduleRules.js";
import bodyParser from "body-parser";
import cors from "cors";
import next from "next";
import { fileURLToPath } from "url";
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 +40,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 +56,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 +73,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 +84,26 @@ app.get("/status", async (_, res) => {
}
})
app.post("/report", async (req, res) => {
app.get("/posts/viewer/redirect", (_: Request, res: Response) => {
res.redirect(302, "/viewer");
})
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 +113,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 +126,30 @@ 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) {
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const dev = process.env.NODE_ENV !== 'production'
// @ts-ignore
const nextApp = next({
dev,
dir: dev ? path.join(__dirname, 'viewer') : path.join(__dirname, '../viewer')
})
const handle = nextApp.getRequestHandler()
await nextApp.prepare()
app.all(/^\/viewer(?:$|\/.*)/, (req, res) => {
return handle(req, res)
})
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");
}

21
tsconfig.json Normal file
View File

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

41
viewer/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

8
viewer/app/all/page.tsx Normal file
View File

@@ -0,0 +1,8 @@
import { getData } from '@/lib/api';
import SubstitutionViewer from './substitution-viewer';
export default async function Page() {
const data = await getData();
return <SubstitutionViewer initialData={data} />;
}

View File

@@ -0,0 +1,202 @@
'use client';
import { useState, useEffect, useMemo } from 'react';
import { format, parseISO } from 'date-fns';
import { SubstitutionData, ChangeEntry } from '@/lib/types';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import TakesPlace from '@/components/own/takes-place';
import { TeacherAbsenceItem } from '@/components/own/teacher-absence';
import UpdateStatus from '@/components/own/update-status';
interface SubstitutionViewerProps {
initialData: SubstitutionData | null;
}
export default function SubstitutionViewer({ initialData }: SubstitutionViewerProps) {
const data = initialData;
const [selectedDate, setSelectedDate] = useState<string>('');
useEffect(() => {
if (data?.schedule) {
const dates = Object.keys(data.schedule).sort();
if (dates.length > 0) {
if (!selectedDate || !data.schedule[selectedDate]) {
setSelectedDate(dates[0]);
}
}
}
}, [data, selectedDate]);
const currentDayData = data?.schedule?.[selectedDate];
const dates = data ? Object.keys(data.schedule).sort() : [];
if (!data) {
return (
<div className="flex flex-col items-center justify-center min-h-screen text-muted-foreground space-y-4">
<p>Nepodařilo se načíst data.</p>
<Button onClick={() => window.location.reload()}>Zkusit znovu</Button>
</div>
);
}
return (
<main className="flex-1 w-full max-w-[1920px] mx-auto p-4 md:p-6 space-y-6">
<UpdateStatus data={data} />
<div className="max-w-md">
<Label htmlFor="date-select" className="mb-2 block">Datum</Label>
<Select value={selectedDate} onValueChange={setSelectedDate}>
<SelectTrigger id="date-select" className="w-full">
<SelectValue placeholder="Vyberte datum" />
</SelectTrigger>
<SelectContent>
{dates.map((date) => {
const info = data.schedule[date];
const label = format(parseISO(date), 'd.M.yyyy');
const suffix = info.info.inWork ? ' (příprava)' : '';
return (
<SelectItem key={date} value={date}>
{label}{suffix}
</SelectItem>
);
})}
</SelectContent>
</Select>
</div>
{currentDayData ? (
<div className="grid grid-cols-1 xl:grid-cols-4 gap-6">
<div className="xl:col-span-3 space-y-6">
<div>
<h2 className="text-xl font-semibold mb-3">Změny v rozvrhu</h2>
<SubstitutionsTable changes={currentDayData.changes} />
</div>
<TakesPlace string={currentDayData.takesPlace} />
</div>
<div className="xl:col-span-1 space-y-6">
<div>
<h2 className="text-xl font-semibold mb-3 text-slate-900 dark:text-slate-100">Absence učitelů</h2>
{currentDayData.absence.length > 0 ? (
<div className="space-y-3">
{currentDayData.absence.map((entry, idx) => (
<TeacherAbsenceItem key={idx} entry={entry} />
))}
</div>
) : (
<div className="p-4 rounded-lg border border-dashed text-muted-foreground text-center bg-slate-50 dark:bg-slate-900/50">
Žádní učitelé nemají absenci
</div>
)}
</div>
</div>
</div>
) : (
<div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
<p className="text-lg">Pro vybrané datum nejsou k dispozici žádná data.</p>
</div>
)}
</main>
);
}
function SubstitutionsTable({ changes }: { changes: Record<string, (ChangeEntry | null)[]> }) {
const sortedClasses = useMemo(() => {
return Object.keys(changes).sort((a, b) => {
const regex = /^([A-Z]+)(\d+)([a-z]*)$/;
const ma = a.match(regex);
const mb = b.match(regex);
if (ma && mb) {
const [, pa, na, sa] = ma;
const [, pb, nb, sb] = mb;
const numDiff = parseInt(na) - parseInt(nb);
if (numDiff !== 0) return numDiff;
const prefixDiff = pa.localeCompare(pb);
if (prefixDiff !== 0) return prefixDiff;
return sa.localeCompare(sb);
}
return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
});
}, [changes]);
const maxHours = useMemo(() => {
let max = 0;
Object.values(changes).forEach(list => {
if (list.length > max) max = list.length;
});
return max;
}, [changes]);
const hours = Array.from({ length: maxHours }, (_, i) => i + 1);
return (
<Card className="overflow-hidden border p-0">
<div className="overflow-x-auto">
<table className="w-full text-sm text-left border-collapse">
<thead>
<tr>
<th className="p-3 font-semibold border-b border-r min-w-[80px] text-center sticky left-0 z-10">
</th>
{hours.map(h => (
<th key={h} className="p-3 font-semibold border-b border-r min-w-[60px] text-center w-[60px]">
{h}
</th>
))}
</tr>
</thead>
<tbody>
{sortedClasses.map((className) => (
<tr key={className} className="border-b last:border-0">
<td className="p-2 font-bold border-r sticky left-0 z-10 bg-card text-center">
{className}
</td>
{hours.map((_, idx) => {
const change = changes[className][idx];
return (
<td key={idx} className="p-[2px] border-r w-[70px] h-[70px] align-middle">
{change ? (
<div
className="w-full h-full min-h-[46px] flex items-center justify-center p-1 rounded-sm text-xs text-center truncate"
style={{
backgroundColor: change.backgroundColor || '#eee',
color: change.foregroundColor ? "#" +change.foregroundColor.substring(3, 6) : '#000'
}}
title={change.text}
>
{change.text}
</div>
) : (
<div className="w-full h-full min-h-[46px]"></div>
)}
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
</Card>
);
}

127
viewer/app/globals.css Normal file
View File

@@ -0,0 +1,127 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--radius-3xl: calc(var(--radius) + 12px);
--radius-4xl: calc(var(--radius) + 16px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
@apply bg-background text-foreground;
}
}

64
viewer/app/layout.tsx Normal file
View File

@@ -0,0 +1,64 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@/components/ui/sonner";
import { SiteHeader } from "@/components/site-header";
import { InfoIcon } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Mimořádný rozvrh SPŠE Ječná",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<div className="flex flex-col min-h-screen">
<SiteHeader />
{children}
<div className="w-full flex justify-center pt-4 pb-8">
<Alert className="max-w-100 mx-auto">
<InfoIcon />
<AlertTitle>Pozor!</AlertTitle>
<AlertDescription>
Tento web není oficiální a není jakkoliv spojen se SPŠE Ječná.
</AlertDescription>
</Alert>
</div>
<footer className="text-center text-xs text-foreground/70 pb-4">
&copy; 2026{" "}
<a href="https://jzitnik.dev" target="_blank" className="underline hover:text-foreground/90">Jakub Žitník</a>{" "}
{" "}
<a href="https://www.gnu.org/licenses/gpl-3.0.html" target="_blank" className="underline hover:text-foreground/90">Licencováno pod GNU GPL v3.0</a>
</footer>
</div>
<Toaster />
</ThemeProvider>
</body>
</html>
);
}

8
viewer/app/page.tsx Normal file
View File

@@ -0,0 +1,8 @@
import { getData } from "@/lib/api";
import View from "./view";
export default async function Page() {
const data = await getData();
return <View data={data} />
}

167
viewer/app/view.tsx Normal file
View File

@@ -0,0 +1,167 @@
"use client";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { SubstitutionData, LocalData } from "@/lib/types";
import { Card, CardContent } from "@/components/ui/card";
import ScheduleViewer from "@/components/own/schedule-viewer";
import { capitalizeFirstLetter } from "@/lib/utils";
import UpdateStatus from '@/components/own/update-status';
interface ViewProps {
data: SubstitutionData | null;
}
interface FormValues {
className: string;
jsonFile: FileList | null;
}
export default function View({ data }: ViewProps) {
const [loading, setLoading] = useState(true);
const [localData, setLocalData] = useState<LocalData | null>(null);
const [hideSubstitutions, setHideSubstitutions] = useState(false);
const form = useForm<FormValues>({
defaultValues: {
className: "",
jsonFile: null,
},
});
const onSubmit = async (values: FormValues) => {
const classNameProcessed = values.className.toLowerCase();
const file = values.jsonFile?.[0];
if (!file) {
alert("No file uploaded!");
return;
}
try {
const text = await file.text();
const jsonData = JSON.parse(text);
console.log(jsonData)
const foundKey = Object.keys(jsonData).find(k => k.toLowerCase() === classNameProcessed);
if (!foundKey) {
alert("Class not found in file!");
return;
}
const data = {
class: foundKey,
timetable: jsonData[foundKey]
};
setLocalData(data);
localStorage.setItem("data", JSON.stringify(data));
} catch (err) {
console.log(err)
alert("Invalid JSON file.");
}
};
useEffect(() => {
const saved = localStorage.getItem("data");
if (saved) {
setLocalData(JSON.parse(saved));
}
setLoading(false);
}, [data]);
if (loading) return <p>Loading...</p>;
if (!localData) {
return (
<div className="flex justify-center w-full">
<Card className="my-8 max-w-200">
<CardContent>
<Form {...form} >
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="className"
rules={{
required: "Třída je povinná",
pattern: {
value: /^[AEC][1-4][a-c]?$/i,
message: "Neplatný název třídy"
},
}}
render={({ field }) => (
<FormItem>
<FormLabel>Třída</FormLabel>
<FormControl>
<Input {...field} placeholder="C2c" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="jsonFile"
rules={{ required: "Soubor je povinný" }}
render={({ field }) => (
<FormItem>
<FormLabel>Soubor</FormLabel>
<FormControl>
<input
type="file"
accept=".json"
onChange={(e) => field.onChange(e.target.files)}
className="cursor-pointer"
/>
</FormControl>
<FormDescription>
<a href="/posts/viewer/getting_file" target="_blank" className="hover:underline">
Jak získat soubor?
</a>
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="cursor-pointer">Odeslat</Button>
</form>
</Form>
</CardContent>
</Card>
</div>
);
}
return (
<div className="w-full max-w-[1920px] mx-auto p-4 space-y-6">
<div className="flex justify-between items-center">
<h1 className="text-2xl font-bold">Rozvrh třídy {capitalizeFirstLetter(localData.class)}</h1>
<div className="flex gap-2">
<Button variant="outline" onClick={() => setHideSubstitutions(!hideSubstitutions)}>
{hideSubstitutions ? "Zobrazit suplování" : "Skrýt suplování"}
</Button>
<Button variant="outline" onClick={() => setLocalData(null)}>Změnit třídu/soubor</Button>
</div>
</div>
<UpdateStatus data={data} />
<ScheduleViewer localData={localData} substitutionData={data} hideSubstitutions={hideSubstitutions} />
</div>
);
}

23
viewer/components.json Normal file
View File

@@ -0,0 +1,23 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}

View File

@@ -0,0 +1,244 @@
'use client';
import { useMemo } from 'react';
import { format, startOfWeek, addDays, parseISO } from 'date-fns';
import { cs } from 'date-fns/locale';
import { LocalData, SubstitutionData, ChangeEntry, Hour } from '@/lib/types';
import { Card } from '@/components/ui/card';
import { capitalizeFirstLetter } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
interface ScheduleViewerProps {
localData: LocalData;
substitutionData: SubstitutionData | null;
hideSubstitutions?: boolean;
}
function getChangesForClass(changes: Record<string, (ChangeEntry | null)[]> | undefined, className: string): (ChangeEntry | null)[] {
if (!changes) return [];
if (changes[className]) return changes[className];
const key = Object.keys(changes).find(k => k.toLowerCase() === className.toLowerCase());
if (key) return changes[key];
return [];
}
export default function ScheduleViewer({ localData, substitutionData, hideSubstitutions = false }: ScheduleViewerProps) {
const referenceDate = useMemo(() => {
if (substitutionData?.schedule) {
const dates = Object.keys(substitutionData.schedule).sort();
if (dates.length > 0) {
return parseISO(dates[0]);
}
}
return new Date();
}, [substitutionData]);
const mondayDate = useMemo(() => {
return startOfWeek(referenceDate, { weekStartsOn: 1 });
}, [referenceDate]);
const weekDays = useMemo(() => {
return Array.from({ length: 5 }, (_, i) => addDays(mondayDate, i));
}, [mondayDate]);
const maxHours = useMemo(() => {
let max = 0;
localData.timetable.forEach(day => {
if (day.length > max) max = day.length;
});
return max;
}, [localData]);
const currentWeekMaxHours = useMemo(() => {
let max = maxHours;
if (!hideSubstitutions && substitutionData?.schedule) {
weekDays.forEach(date => {
const dateStr = format(date, 'yyyy-MM-dd');
const dayData = substitutionData.schedule[dateStr];
if (dayData && dayData.changes) {
const changes = getChangesForClass(dayData.changes, localData.class);
if (changes.length > max) max = changes.length;
}
});
}
return max;
}, [maxHours, substitutionData, weekDays, localData.class, hideSubstitutions]);
const hours = Array.from({ length: currentWeekMaxHours }, (_, i) => i + 1);
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="text-sm text-muted-foreground">
Zobrazen týden od {format(mondayDate, 'd. M.', { locale: cs })} do {format(weekDays[4], 'd. M. yyyy', { locale: cs })}
</div>
</div>
<Card className="overflow-hidden border p-0">
<div className="overflow-x-auto">
<table className="w-full text-sm text-left border-collapse">
<thead>
<tr>
<th className="p-3 font-semibold border-b border-r min-w-[100px] text-center">
Den
</th>
{hours.map(h => (
<th key={h} className="p-3 font-semibold border-b border-r min-w-[120px] text-center">
{h}
</th>
))}
</tr>
</thead>
<tbody>
{weekDays.map((date, dayIndex) => {
const dateStr = format(date, 'yyyy-MM-dd');
const dayName = format(date, 'EEEE', { locale: cs });
const staticDay = localData.timetable[dayIndex] || [];
const dynamicDay = substitutionData?.schedule?.[dateStr];
const changes = getChangesForClass(dynamicDay?.changes, localData.class);
const has3 = hours.some((_, hourIndex) => staticDay[hourIndex].length == 3);
return (
<tr key={dateStr} className="border-b last:border-0 group hover:bg-muted/5" style={{height: has3 ? "120px" : "80px"}}>
<td className="p-3 font-medium border-r text-center">
<div className="capitalize">{dayName}</div>
<div className="text-xs text-muted-foreground">{format(date, 'd. M.')}</div>
</td>
{hours.map((_, hourIndex) => {
const change = changes[hourIndex];
const staticLessons = staticDay[hourIndex] || [];
return (
<td key={hourIndex} className="border-r min-w-[120px] h-full align-top relative p-0">
<CellContent
staticLessons={staticLessons}
change={hideSubstitutions ? null : change}
/>
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
</Card>
</div>
);
}
function LessonDialog({ lesson, children }: { lesson: Hour, children: React.ReactNode }) {
return (
<Dialog>
<DialogTrigger asChild className="cursor-pointer hover:bg-accent hover:text-accent-foreground transition-colors">
{children}
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>{lesson.title || lesson.subject}</DialogTitle>
<DialogDescription>
Detailní informace o hodině
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<span className="font-bold text-right col-span-1">Předmět:</span>
<span className="col-span-3">{lesson.title} ({lesson.subject})</span>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<span className="font-bold text-right col-span-1">Učitel:</span>
<a
href={`https://spsejecna.cz/ucitel/${lesson.teacher.code}`}
target="_blank"
rel="noopener noreferrer"
className="col-span-3 text-primary underline-offset-4 hover:underline"
>
{lesson.teacher.name}
</a>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<span className="font-bold text-right col-span-1">Místnost:</span>
<a
href={`https://spsejecna.cz/ucebna/${lesson.room}`}
target="_blank"
rel="noopener noreferrer"
className="col-span-3 text-primary underline-offset-4 hover:underline"
>
{lesson.room}
</a>
</div>
</div>
</DialogContent>
</Dialog>
)
}
function CellContent({ staticLessons, change }: { staticLessons: Hour[], change: ChangeEntry | null | undefined }) {
if (change) {
return (
<div
className="w-full h-full p-2 text-xs flex items-center justify-center text-center font-medium"
style={{
backgroundColor: change.backgroundColor || '#f0f0f0',
color: change.foregroundColor ? "#" + change.foregroundColor.substring(3, 6) : '#000',
}}
>
{change.text}
</div>
);
}
if (!staticLessons || staticLessons.length === 0) {
return null;
}
if (staticLessons.length > 1) {
return (
<div className="flex flex-col min-h-[80px] h-full">
{staticLessons.map((lesson, idx) => (
<LessonDialog key={idx} lesson={lesson}>
<div role="button" tabIndex={0} className="flex-1 flex flex-col justify-between p-1 text-[10px] border-b min-h-[40px] text-left">
<div className='flex justify-between'>
<div className="font-bold truncate">{lesson.subject}</div>
<span className="truncate opacity-70">{capitalizeFirstLetter(lesson.teacher.code)}</span>
</div>
<div className="flex justify-between">
<span className="truncate max-w-[40px]">{lesson.room}</span>
<span className="truncate opacity-70">{lesson.group}</span>
</div>
</div>
</LessonDialog>
))}
</div>
);
}
const lesson = staticLessons[0];
return (
<LessonDialog lesson={lesson}>
<div role="button" tabIndex={0} className="w-full min-h-[80px] h-full p-2 border-b flex flex-col justify-between text-xs text-left">
<div className="font-bold text-lg text-primary">{lesson.subject}</div>
<div className="flex justify-between items-end mt-1">
<div className="font-mono font-medium">{lesson.room}</div>
<div className="text-[10px] opacity-80" title={lesson.teacher.name}>{capitalizeFirstLetter(lesson.teacher.code)}</div>
</div>
</div>
</LessonDialog>
);
}

View File

@@ -0,0 +1,16 @@
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
export default function TakesPlace({string}: {string: string}) {
return (
<Card>
<CardHeader>
<CardTitle>Koná se</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-slate-700 dark:text-slate-300">
{string}
</p>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,34 @@
import { AbsenceEntry } from "@/lib/types";
import { Card, CardContent } from "../ui/card";
export function TeacherAbsenceItem({ entry }: { entry: AbsenceEntry }) {
const getTeacherName = (e: AbsenceEntry) => {
if (e.type === 'invalid') return null;
return e.teacher;
};
const teacherName = getTeacherName(entry) || 'Neznámý';
const getTypeDescription = (e: AbsenceEntry) => {
switch (e.type) {
case 'wholeDay': return 'Celý den';
case 'single': return `${e.hours}. hodinu`;
case 'range': return `${e.hours.from}-${e.hours.to} hodinu`;
case 'exkurze': return 'Na exkurzi';
case 'zastoupen': return `Zastoupen (${e.zastupuje.teacher || 'Neznámý'})`;
case 'invalid': return `Neplatný záznam: ${e.original}`;
default: return 'Neznámý';
}
};
return (
<Card>
<CardContent>
<div className="font-bold text-base text-slate-800 dark:text-slate-200">{teacherName}</div>
<div className="text-sm text-slate-500 dark:text-slate-400">
{getTypeDescription(entry)}
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,52 @@
"use client";
import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { RefreshCw } from "lucide-react";
import { SubstitutionData } from "@/lib/types";
import { Button } from "@/components/ui/button";
interface UpdateStatusProps {
data: SubstitutionData | null;
}
export default function UpdateStatus({ data }: UpdateStatusProps) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
if (!data) return null;
const handleRefresh = () => {
startTransition(() => {
router.refresh();
});
};
return (
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 text-sm text-muted-foreground p-4 rounded-lg border">
<div>
<span className="font-medium">Poslední aktualizace:</span> {data.status.lastUpdated}
<span className="mx-2 hidden sm:inline"></span>
<br className="sm:hidden" />
<span>
Aktualizace každých{" "}
{data.status.currentUpdateSchedule < 60
? `${data.status.currentUpdateSchedule} min`
: `${data.status.currentUpdateSchedule / 60} hod`}
</span>
</div>
<Button
variant="outline"
size="sm"
onClick={handleRefresh}
disabled={isPending}
className="w-full sm:w-auto"
>
<RefreshCw
className={`h-4 w-4 mr-2 ${isPending ? "animate-spin" : ""}`}
/>
Aktualizovat
</Button>
</div>
);
}

View File

@@ -0,0 +1,103 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { Menu, X, AlertTriangle, Home, List } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export function SiteHeader() {
const [isOpen, setIsOpen] = useState(false);
const pathname = usePathname();
const routes = [
{
href: "/",
label: "Třída",
active: pathname === "/",
icon: Home
},
{
href: "/all",
label: "Vše",
active: pathname === "/all",
icon: List
}
];
return (
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="flex h-14 items-center px-4 md:px-8">
<Button
variant="ghost"
className="mr-2 px-0 text-base hover:bg-transparent focus-visible:bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 md:hidden"
onClick={() => setIsOpen(!isOpen)}
>
{isOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
<span className="sr-only">Toggle Menu</span>
</Button>
<div className="mr-4 hidden md:flex items-center">
<Link href="/" className="mr-6 flex items-center space-x-2">
<span className="hidden font-bold sm:inline-block">
Mimořádný rozvrh
</span>
</Link>
<nav className="flex items-center space-x-6 text-sm font-medium">
{routes.map((route) => (
<Link
key={route.href}
href={route.href}
className={cn(
"transition-colors hover:text-foreground/80 flex items-center gap-2",
route.active ? "text-foreground" : "text-foreground/60"
)}
>
<route.icon className="h-4 w-4" />
{route.label}
</Link>
))}
</nav>
</div>
<div className="flex flex-1 items-center justify-between space-x-2 md:justify-end hidden">
<div className="w-full flex-1 md:w-auto md:flex-none">
<span className="font-bold md:hidden">Mimořádný rozvrh</span>
</div>
<nav className="flex items-center">
<Button variant="ghost" size="icon" title="Nahlásit chybu" asChild>
<Link href="https://github.com/jzitnik/tablescraper/issues/new" target="_blank" rel="noreferrer">
<AlertTriangle className="h-5 w-5 text-amber-500" />
<span className="sr-only">Nahlásit chybu</span>
</Link>
</Button>
</nav>
</div>
</div>
{isOpen && (
<div className="md:hidden border-t p-4 space-y-4 bg-background animate-in slide-in-from-top-5">
<nav className="flex flex-col space-y-4">
{routes.map((route) => (
<Link
key={route.href}
href={route.href}
onClick={() => setIsOpen(false)}
className={cn(
"text-sm font-medium transition-colors hover:text-primary p-2 rounded-md hover:bg-muted",
route.active ? "bg-muted text-foreground" : "text-muted-foreground"
)}
>
<div className="flex items-center gap-3">
<route.icon className="h-5 w-5" />
{route.label}
</div>
</Link>
))}
</nav>
</div>
)}
</header>
);
}

View File

@@ -0,0 +1,11 @@
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

View File

@@ -0,0 +1,66 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }

View File

@@ -0,0 +1,64 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@@ -0,0 +1,158 @@
"use client"
import * as React from "react"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,167 @@
"use client"
import * as React from "react"
import type { Label as LabelPrimitive } from "radix-ui"
import { Slot } from "radix-ui"
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState } = useFormContext()
const formState = useFormState({ name: fieldContext.name })
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider>
)
}
function FormLabel({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField()
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn("data-[error=true]:text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
}
function FormControl({ ...props }: React.ComponentProps<typeof Slot.Root>) {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot.Root
data-slot="form-control"
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId } = useFormField()
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : props.children
if (!body) {
return null
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn("text-destructive text-sm", className)}
{...props}
>
{body}
</p>
)
}
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View File

@@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import { Label as LabelPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@@ -0,0 +1,45 @@
"use client"
import * as React from "react"
import { CircleIcon } from "lucide-react"
import { RadioGroup as RadioGroupPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function RadioGroup({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
return (
<RadioGroupPrimitive.Root
data-slot="radio-group"
className={cn("grid gap-3", className)}
{...props}
/>
)
}
function RadioGroupItem({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
return (
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator
data-slot="radio-group-indicator"
className="relative flex items-center justify-center"
>
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
}
export { RadioGroup, RadioGroupItem }

View File

@@ -0,0 +1,190 @@
"use client"
import * as React from "react"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { Select as SelectPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span
data-slot="select-item-indicator"
className="absolute right-2 flex size-3.5 items-center justify-center"
>
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@@ -0,0 +1,40 @@
"use client"
import {
CircleCheckIcon,
InfoIcon,
Loader2Icon,
OctagonXIcon,
TriangleAlertIcon,
} from "lucide-react"
import { useTheme } from "next-themes"
import { Toaster as Sonner, type ToasterProps } from "sonner"
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
icons={{
success: <CircleCheckIcon className="size-4" />,
info: <InfoIcon className="size-4" />,
warning: <TriangleAlertIcon className="size-4" />,
error: <OctagonXIcon className="size-4" />,
loading: <Loader2Icon className="size-4 animate-spin" />,
}}
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
"--border-radius": "var(--radius)",
} as React.CSSProperties
}
{...props}
/>
)
}
export { Toaster }

View File

@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
{...props}
/>
)
}
export { Textarea }

18
viewer/eslint.config.mjs Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

18
viewer/lib/api.ts Normal file
View File

@@ -0,0 +1,18 @@
import { SubstitutionData } from "./types";
export async function getData(): Promise<SubstitutionData | null> {
const apiUrl = process.env.API_URL || 'http://localhost:3000';
try {
const res = await fetch(`${apiUrl}/versioned/v3`, {
next: { revalidate: 60 },
});
if (!res.ok) {
return null;
}
return res.json();
} catch {
return null;
}
}

49
viewer/lib/types.ts Normal file
View File

@@ -0,0 +1,49 @@
export interface TeacherReference {
name: string;
code: string;
}
export type AbsenceEntry =
| { type: 'wholeDay'; teacher: string; teacherCode: string }
| { type: 'single'; teacher: string; teacherCode: string; hours: string }
| { type: 'range'; teacher: string; teacherCode: string; hours: { from: string; to: string } }
| { type: 'exkurze'; teacher: string; teacherCode: string }
| { type: 'zastoupen'; teacher: string; teacherCode: string; zastupuje: { teacher: string | null } }
| { type: 'invalid'; original: string; teacher?: null; teacherCode?: null };
export interface ChangeEntry {
text: string;
backgroundColor?: string | null;
foregroundColor?: string | null;
}
export interface SubstitutionDayData {
info: { inWork: boolean };
takesPlace: string;
changes: Record<string, (ChangeEntry | null)[]>;
absence: AbsenceEntry[];
}
export interface SubstitutionData {
status: {
currentUpdateSchedule: number;
lastUpdated: string;
}
schedule: Record<string, SubstitutionDayData>;
}
export interface Hour {
subject: string;
title: string;
teacher: {
code: string;
name: string;
}
group?: string;
room: string;
}
export interface LocalData {
class: string;
timetable: Hour[][][];
}

11
viewer/lib/utils.ts Normal file
View File

@@ -0,0 +1,11 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function capitalizeFirstLetter(string: string) {
if (!string) return string;
return string.charAt(0).toUpperCase() + string.slice(1);
}

12
viewer/next.config.ts Normal file
View File

@@ -0,0 +1,12 @@
import type { NextConfig } from "next";
import path from "path";
const nextConfig: NextConfig = {
reactCompiler: true,
basePath: '/viewer',
turbopack: {
root: process.env.NODE_ENV == "development" ? path.resolve(__dirname) : path.resolve(__dirname, '..'),
},
};
export default nextConfig;

11843
viewer/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
viewer/package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "viewer",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@hookform/resolvers": "^5.2.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"lucide-react": "^0.563.0",
"next": "16.1.6",
"next-themes": "^0.4.6",
"radix-ui": "^1.4.3",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-hook-form": "^7.71.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"shadcn": "^3.8.4",
"tailwindcss": "^4",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
}
}

View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

1
viewer/public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
viewer/public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
viewer/public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
viewer/public/vercel.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
viewer/public/window.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

34
viewer/tsconfig.json Normal file
View File

@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}

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,22 +22,30 @@ 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/v1`
**Endpoint:** `/versioned/v3`
Toto je aktuální a doporučená verze API. Klikněte na odkaz pro zobrazení kompletní dokumentace pro v2.
Toto je aktuální a doporučená verze API. Obsahuje velké změny oproti V2 a obsahuje nové data.
- ### [Verze 1 (v1)](../api-usage-v1)
- ### [Verze 2 (v2)](../v2)
**Status:** Stabilní
**Endpoint:** `/versioned/v2`
- ### [~Verze 1 (v1)~](../v1)
**Status:** Deprecated
**Endpoint:** `/versioned/v1`
Verze 1 bude v budoucnu odstaněna. Migrujte na novější verze
---
## Nezařazené Endpointy
@@ -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://gitea.local.jzitnik.dev/jzitnik/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

@@ -0,0 +1,33 @@
---
title: "Získání statického souboru"
date: 2026-02-12
hiddenInHomelist: true
---
Pokud si chcete zobrazit stálý rozvrh zároveň s mimořádným rozvrhem ve webovém rozhraní musíte si získat statický rozvrh. Ten získáte pomocí Node.js scriptu.
## Požadavky
Před začátkem se ujistěte, že máte připravené následující:
- **Účet SPŠE Ječná**: Script vyžaduje platný školní účet a heslo.
- **Node.js 22+**
- **Git**
## Stažení projektu
```bash
git clone https://gitea.jzitnik.dev/jzitnik/jecnarozvrh
```
## Stažení knihoven a spuštění scriptu
```bash
npm i
npm run parse-timetable
```
Script se vás zeptá na username, password a output cestu k souboru.
Script projde všechny učitele a sestaví rozvrh všech tříd podle toho.

View File

@@ -0,0 +1,4 @@
---
title: "Online verze"
date: 2026-02-12
---

View File

@@ -13,7 +13,7 @@ mainsections: ["posts", "papermod"]
minify:
disableXML: true
# minifyOutput: true
minifyOutput: true
pagination:
disableAliases: false
@@ -22,15 +22,18 @@ pagination:
menu:
main:
- name: Online client
url: /viewer
weight: 10
- name: Status
url: https://status.jzitnik.dev
weight: 10
weight: 20
- name: Autor
url: https://jzitnik.dev
weight: 20
weight: 30
- name: Zdrojový kód
url: https://gitea.jzitnik.dev/jzitnik/jecnarozvrh
weight: 30
weight: 40
outputs:
home:
@@ -59,8 +62,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>