Files
X4Lo 1f1d28a34d Add B1 Meister: OeSD B1 exam trainer (German-Arabic)
Next.js app with Hoeren, Lesen, Schreiben, Sprechen, Grammatik and Wortschatz sections, flashcards with spaced repetition, speaking chat, XP/streaks/badges, daily reminders (PWA) and Docker Compose setup for Coolify.
2026-11-05 19:11:46 +00:00

134 lines
5.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { getProgress, syncReminderState, todayStr } from "./progress";
const messages = [
{ title: "Zeit für Deutsch! 🇦🇹", body: "Nur 10 Minuten heute – deine Serie wartet! • وقت الألمانية! عشر دقائق فقط اليوم" },
{ title: "Deine Flamme 🔥 geht aus!", body: "Lerne kurz, damit deine Serie weiterläuft. • تعلّم قليلاً حتى لا تنقطع سلسلتك" },
{ title: "Die B1-Prüfung kommt näher 📅", body: "Ein paar Karteikarten? Los geht's! • بعض البطاقات؟ هيا بنا!" },
{ title: "Hallo! Ich bin's, dein Deutschtrainer 👋", body: "Lass uns heute ein bisschen sprechen. • لنتحدث قليلاً اليوم" },
];
export function notificationsSupported() {
return typeof window !== "undefined" && "Notification" in window && "serviceWorker" in navigator;
}
export async function registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {
if (typeof navigator === "undefined" || !("serviceWorker" in navigator)) return null;
try {
const reg = await navigator.serviceWorker.register("/sw.js");
await navigator.serviceWorker.ready;
syncReminderState();
// Periodic Background Sync (Chrome/Android, installierte App)
const anyReg = reg as ServiceWorkerRegistration & {
periodicSync?: { register: (tag: string, o: { minInterval: number }) => Promise<void> };
};
if (anyReg.periodicSync) {
try {
const status = await navigator.permissions.query({ name: "periodic-background-sync" as PermissionName });
if (status.state === "granted") {
await anyReg.periodicSync.register("daily-reminder", { minInterval: 60 * 60 * 1000 });
}
} catch {
/* nicht unterstützt */
}
}
return reg;
} catch {
return null;
}
}
export async function requestNotificationPermission(): Promise<NotificationPermission | "unsupported"> {
if (!notificationsSupported()) return "unsupported";
if (Notification.permission === "granted") return "granted";
return Notification.requestPermission();
}
export async function showReminder(test = false) {
if (!notificationsSupported() || Notification.permission !== "granted") return false;
const reg = await navigator.serviceWorker.ready;
const m = messages[Math.floor(Math.random() * messages.length)];
const streak = getProgress().streak;
await reg.showNotification(test ? "Test: " + m.title : m.title, {
body: streak > 0 ? `${m.body}\n🔥 Serie: ${streak} Tage` : m.body,
icon: "/icon.svg",
badge: "/icon.svg",
tag: "daily-reminder",
});
return true;
}
const SHOWN_KEY = "b1meister:reminder-shown";
/** Prüft (solange die App offen ist) jede Minute, ob es Zeit für die Erinnerung ist. */
export function startInAppReminderLoop(): () => void {
const check = () => {
const p = getProgress();
if (!p.reminder.enabled) return;
const t = todayStr();
if (p.lastStudy === t) return;
let shown: string | null = null;
try {
shown = localStorage.getItem(SHOWN_KEY);
} catch {
/* ignorieren */
}
if (shown === t) return;
const [h, m] = p.reminder.time.split(":").map(Number);
const now = new Date();
if (now.getHours() * 60 + now.getMinutes() >= h * 60 + m) {
void showReminder().then((ok) => {
if (ok) {
try {
localStorage.setItem(SHOWN_KEY, t);
} catch {
/* ignorieren */
}
}
});
}
};
check();
const id = window.setInterval(check, 60 * 1000);
return () => window.clearInterval(id);
}
/** Erzeugt einen täglich wiederholten Kalendertermin mit Alarm (funktioniert auf jedem Handy). */
export function downloadCalendarReminder(time: string) {
const [h, m] = time.split(":");
const d = new Date();
const ymd = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}${String(d.getDate()).padStart(2, "0")}`;
const start = `${ymd}T${h.padStart(2, "0")}${m.padStart(2, "0")}00`;
const endDate = new Date(d);
endDate.setHours(Number(h), Number(m) + 15);
const end = `${ymd}T${String(endDate.getHours()).padStart(2, "0")}${String(endDate.getMinutes()).padStart(2, "0")}00`;
const url = typeof window !== "undefined" ? window.location.origin : "";
const ics = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//B1 Meister//DE",
"BEGIN:VEVENT",
`UID:b1meister-daily-${ymd}@b1meister`,
`DTSTAMP:${ymd}T000000`,
`DTSTART:${start}`,
`DTEND:${end}`,
"RRULE:FREQ=DAILY",
"SUMMARY:🇦🇹 Deutsch lernen – B1 Meister",
`DESCRIPTION:15 Minuten für die ÖSD B1 Prüfung! ${url}`,
"BEGIN:VALARM",
"TRIGGER:PT0M",
"ACTION:DISPLAY",
"DESCRIPTION:Zeit für Deutsch!",
"END:VALARM",
"END:VEVENT",
"END:VCALENDAR",
].join("\r\n");
const blob = new Blob([ics], { type: "text/calendar" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = "deutsch-erinnerung.ics";
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 2000);
}