Upload via GUI (23 Dateien)

This commit is contained in:
2026-11-01 11:15:09 +00:00
parent c57918c86f
commit ba32f72275
19 changed files with 1073 additions and 73 deletions
+77 -16
View File
@@ -1,5 +1,6 @@
// Gemeinsamer Kern von Popup und Hintergrunddienst: Serveradresse, Anmeldung, API-Aufrufe, Hilfsfunktionen.
// Gemeinsamer Kern von Oberfläche und Hintergrunddienst: Serveradresse, Anmeldung, API-Aufrufe, Hilfsfunktionen.
// Das Anmelde-Token liegt nur in chrome.storage.local dieser Erweiterung (nie in sync, nie im Seitencode).
// Der Zugriff auf den Server ist im Manifest erlaubt (host_permissions): Es gibt keine Rückfrage beim Anmelden.
export class ApiError extends Error {
constructor(status, code, message) { super(message); this.status = status; this.code = code; }
@@ -25,11 +26,15 @@ export async function getSession() {
return session && session.token && session.serverUrl ? session : null;
}
export const setSession = (session) => chrome.storage.local.set({ session });
export async function clearSession() { await chrome.storage.local.remove(['session', 'lastSeen', 'badgeCount', 'meta']); }
export async function clearSession() {
const drafts = Object.keys(await chrome.storage.local.get(null)).filter((k) => k.startsWith('draft:')); // nicht gesendete Entwürfe gehören zur Anmeldung
await chrome.storage.local.remove(['session', 'lastSeen', 'badgeCount', 'meta', ...drafts]);
}
export const DEFAULT_SETTINGS = { notifications: true, notifyUnassigned: true, notifyMine: true, theme: 'auto', compact: false };
export async function getSettings() {
const { settings } = await chrome.storage.local.get('settings');
return { notifications: true, ...(settings || {}) };
return { ...DEFAULT_SETTINGS, ...(settings || {}) };
}
export const setSettings = (settings) => chrome.storage.local.set({ settings });
@@ -40,13 +45,13 @@ export async function apiCall(path, { method = 'GET', query, body, auth = true,
if (!base) throw new ApiError(401, 'UNAUTHENTICATED', 'Nicht angemeldet.');
const url = new URL(`${base}/api/staff/v1/${path}`);
for (const [k, v] of Object.entries(query || {})) if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, String(v));
const headers = { Accept: 'application/json', 'Cache-Control': 'no-cache' };
const headers = { Accept: 'application/json' };
if (auth) {
if (!session?.token) throw new ApiError(401, 'UNAUTHENTICATED', 'Nicht angemeldet.');
headers.Authorization = `Bearer ${session.token}`;
headers['X-DeskHub-Authorization'] = `Bearer ${session.token}`;
}
const init = { method, headers, redirect: 'error', credentials: 'omit', signal: signal || AbortSignal.timeout(30000) };
const init = { method, headers, redirect: 'error', credentials: 'omit', cache: 'no-store', signal: signal || AbortSignal.timeout(30000) };
if (body !== undefined && method !== 'GET') { headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(body); }
let res;
try { res = await fetch(url, init); } catch { throw new ApiError(0, 'NETWORK', 'Server nicht erreichbar.'); }
@@ -60,17 +65,24 @@ export async function apiCall(path, { method = 'GET', query, body, auth = true,
return { status: res.status, data };
}
/** Fragt bei Bedarf die Berechtigung für genau diesen Server ab (nur diese eine Adresse, nicht „alle Webseiten“). Muss aus einem Klick heraus aufgerufen werden. */
export async function ensureHostPermission(serverUrl) {
const pattern = new URL(serverUrl).origin + '/*';
if (await chrome.permissions.contains({ origins: [pattern] })) return true;
return chrome.permissions.request({ origins: [pattern] });
/**
* Schickt eine POST-Anfrage los, ohne auf etwas zu warten (für „beim Verlassen aufräumen“). Läuft synchron mit keepalive und überlebt deshalb
* das Schließen des Popups, das sich bei jedem Klick daneben schließt. Die Sitzung wird übergeben, weil ein Speicherzugriff dafür zu spät käme.
*/
export function apiBeacon(session, path, body) {
if (!session?.token || !session?.serverUrl) return;
try {
fetch(`${session.serverUrl}/api/staff/v1/${path}`, {
method: 'POST', keepalive: true, redirect: 'error', credentials: 'omit', cache: 'no-store',
headers: { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: `Bearer ${session.token}`, 'X-DeskHub-Authorization': `Bearer ${session.token}` },
body: JSON.stringify(body),
}).catch(() => {});
} catch { /* egal */ }
}
/** Meldet an. @returns {{requiresTotp:true}|{session:object}} */
export async function login(serverUrlInput, email, password, totpCode) {
const serverUrl = normalizeServerUrl(serverUrlInput);
if (!(await ensureHostPermission(serverUrl))) throw new Error('Ohne Erlaubnis für diesen Server kann sich die Erweiterung nicht anmelden.');
const { status, data } = await apiCall('login.php', {
method: 'POST', auth: false, serverUrl,
body: { email, password, totpCode: totpCode || null, deviceName: 'Chrome-Erweiterung' },
@@ -81,16 +93,27 @@ export async function login(serverUrlInput, email, password, totpCode) {
return { session };
}
/** Meldet ab (Token auf dem Server sperren) und entfernt Daten und Berechtigung dieses Servers. */
/** Meldet ab: Token auf dem Server sperren und lokale Daten entfernen. */
export async function logout() {
const session = await getSession();
if (session) {
try { await apiCall('logout.php', { method: 'POST', body: {} }); } catch { /* Token läuft ohnehin ab */ }
try { await chrome.permissions.remove({ origins: [new URL(session.serverUrl).origin + '/*'] }); } catch { /* ignorieren */ }
}
if (session) { try { await apiCall('logout.php', { method: 'POST', body: {} }); } catch { /* Token läuft ohnehin ab */ } }
await clearSession();
}
/** Stammdaten (Abteilungen, Prioritäten, Mitarbeiter, Status, Tags) – 10 Minuten zwischengespeichert. */
export async function getMeta(force = false) {
const { meta } = await chrome.storage.local.get('meta');
if (!force && meta && Date.now() - meta.at < 10 * 60 * 1000) return meta;
const { data } = await apiCall('metadata.php');
const fresh = {
at: Date.now(),
departments: (data.departments || []).filter((d) => !/\(deaktiviert\)$/.test(d.name)),
priorities: data.priorities || [], agents: data.agents || [], statuses: data.statuses || [], tags: data.tags || [],
};
await chrome.storage.local.set({ meta: fresh });
return fresh;
}
/** Pfad eines Tickets in der Weboberfläche. Nur Ticketnummern im bekannten Format. */
export function ticketPath(number) {
const n = String(number || '');
@@ -117,3 +140,41 @@ export function plainToHtml(text) {
}
export const truncate = (s, n) => (String(s).length > n ? String(s).slice(0, n - 1) + '…' : String(s));
/** „2026-10-31 04:03:00“ (Serverzeit) → Date. Der Server liefert Zeiten ohne Zeitzone; sie werden wie lokale Zeit behandelt. */
export function parseServerTime(s) {
const m = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/.exec(String(s || ''));
return m ? new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] || 0)) : null;
}
/** Kurzform wie „vor 5 Min“, „gestern 14:02“, „31.10. 04:03“. */
export function timeAgo(s, now = new Date()) {
const d = parseServerTime(s);
if (!d) return '';
const diff = Math.round((now - d) / 1000);
const hm = d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
if (diff < 0) { // Zukunft (z. B. Wiedervorlage)
const tomorrow = new Date(now); tomorrow.setDate(now.getDate() + 1);
if (d.toDateString() === now.toDateString()) return `heute ${hm}`;
if (d.toDateString() === tomorrow.toDateString()) return `morgen ${hm}`;
return `${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}. ${hm}`;
}
if (diff < 60) return 'gerade eben';
if (diff < 3600) return `vor ${Math.floor(diff / 60)} Min`;
const sameDay = d.toDateString() === now.toDateString();
if (sameDay) return `heute ${hm}`;
const yesterday = new Date(now); yesterday.setDate(now.getDate() - 1);
if (d.toDateString() === yesterday.toDateString()) return `gestern ${hm}`;
return `${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}. ${hm}`;
}
export const fmtBytes = (n) => (n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n >= 1024 ? Math.round(n / 1024) + ' KB' : n + ' B');
export const initials = (name) => String(name || '?').trim().split(/\s+/).slice(0, 2).map((p) => p[0]?.toUpperCase() || '').join('') || '?';
export const safeColor = (c) => (typeof c === 'string' && /^#[0-9a-fA-F]{3,8}$/.test(c) ? c : null);
export const RESOLUTION_REASONS = {
fixed: 'Fehler behoben', guidance: 'Anleitung oder Beratung', duplicate: 'Doppelt / zusammengeführt', not_reproducible: 'Nicht reproduzierbar',
no_action: 'Keine Maßnahme erforderlich', spam: 'Spam oder Sperre', other: 'Sonstiges',
};
export const STATUS_LABELS = { open: 'Offen', pending: 'Wartet auf Kunde', answered: 'Beantwortet', on_hold: 'Pausiert', resolved: 'Gelöst', closed: 'Geschlossen' };
export const AVAILABILITY = { available: 'Verfügbar', busy: 'Beschäftigt', break: 'Pause', offline: 'Offline' };