generated from Dicken/dickendock
Lesezeichen, Import/Export, Favoriten-Sortierung im Frontend, Favicon-Fix, sortierbare Spalten, Kategorie-Dropdown
This commit is contained in:
@@ -76,6 +76,22 @@ export function ensureSchema(): void {
|
||||
message TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bookmarks (
|
||||
id TEXT PRIMARY KEY,
|
||||
url TEXT NOT NULL,
|
||||
display_name TEXT NOT NULL,
|
||||
hostname TEXT NOT NULL,
|
||||
description TEXT,
|
||||
category TEXT,
|
||||
icon TEXT,
|
||||
favicon TEXT,
|
||||
favorite INTEGER NOT NULL DEFAULT 0,
|
||||
alias TEXT NOT NULL DEFAULT '[]',
|
||||
"order" REAL NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
`);
|
||||
|
||||
// Leichte Migration für Datenbanken, die vor Einführung von "visible"
|
||||
|
||||
115
apps/backend/src/db/repositories/bookmarks.ts
Normal file
115
apps/backend/src/db/repositories/bookmarks.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Bookmark, BookmarkCreateInput, BookmarkUpdateInput } from "@launchpad/shared";
|
||||
import { db } from "../client.js";
|
||||
import { bookmarks } from "../schema.js";
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function mapRow(row: typeof bookmarks.$inferSelect): Bookmark {
|
||||
return {
|
||||
id: row.id,
|
||||
url: row.url,
|
||||
displayName: row.displayName,
|
||||
hostname: row.hostname,
|
||||
description: row.description,
|
||||
category: row.category,
|
||||
icon: row.icon,
|
||||
favicon: row.favicon,
|
||||
favorite: row.favorite,
|
||||
alias: JSON.parse(row.alias) as string[],
|
||||
order: row.order,
|
||||
};
|
||||
}
|
||||
|
||||
export function extractHostname(url: string): string {
|
||||
try {
|
||||
return new URL(url).hostname;
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
export function listBookmarks(): Bookmark[] {
|
||||
return db.select().from(bookmarks).all().map(mapRow);
|
||||
}
|
||||
|
||||
export function getBookmark(id: string): Bookmark | null {
|
||||
const row = db.select().from(bookmarks).where(eq(bookmarks.id, id)).get();
|
||||
return row ? mapRow(row) : null;
|
||||
}
|
||||
|
||||
export interface CreateBookmarkOptions {
|
||||
displayName: string;
|
||||
favicon?: string | null;
|
||||
}
|
||||
|
||||
export function createBookmark(
|
||||
input: BookmarkCreateInput,
|
||||
resolved: CreateBookmarkOptions
|
||||
): Bookmark {
|
||||
const id = randomUUID();
|
||||
const timestamp = nowIso();
|
||||
|
||||
db.insert(bookmarks)
|
||||
.values({
|
||||
id,
|
||||
url: input.url,
|
||||
displayName: resolved.displayName,
|
||||
hostname: extractHostname(input.url),
|
||||
description: input.description ?? null,
|
||||
category: input.category ?? null,
|
||||
icon: input.icon ?? null,
|
||||
favicon: resolved.favicon ?? null,
|
||||
favorite: input.favorite ?? false,
|
||||
alias: JSON.stringify(input.alias ?? []),
|
||||
order: input.order ?? 0,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
})
|
||||
.run();
|
||||
|
||||
return getBookmark(id)!;
|
||||
}
|
||||
|
||||
export function updateBookmark(id: string, input: BookmarkUpdateInput): Bookmark | null {
|
||||
const existing = getBookmark(id);
|
||||
if (!existing) return null;
|
||||
|
||||
db.update(bookmarks)
|
||||
.set({
|
||||
...(input.url !== undefined && { url: input.url, hostname: extractHostname(input.url) }),
|
||||
...(input.displayName !== undefined && { displayName: input.displayName }),
|
||||
...(input.description !== undefined && { description: input.description }),
|
||||
...(input.category !== undefined && { category: input.category }),
|
||||
...(input.icon !== undefined && { icon: input.icon }),
|
||||
...(input.favorite !== undefined && { favorite: input.favorite }),
|
||||
...(input.alias !== undefined && { alias: JSON.stringify(input.alias) }),
|
||||
...(input.order !== undefined && { order: input.order }),
|
||||
updatedAt: nowIso(),
|
||||
})
|
||||
.where(eq(bookmarks.id, id))
|
||||
.run();
|
||||
|
||||
return getBookmark(id);
|
||||
}
|
||||
|
||||
export function deleteBookmark(id: string): boolean {
|
||||
const result = db.delete(bookmarks).where(eq(bookmarks.id, id)).run();
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
export function reorderBookmarks(input: { id: string; order: number }[]): Bookmark[] {
|
||||
db.transaction((tx) => {
|
||||
for (const entry of input) {
|
||||
tx.update(bookmarks)
|
||||
.set({ order: entry.order, updatedAt: nowIso() })
|
||||
.where(eq(bookmarks.id, entry.id))
|
||||
.run();
|
||||
}
|
||||
});
|
||||
|
||||
return listBookmarks();
|
||||
}
|
||||
@@ -75,3 +75,25 @@ export const scanLogs = sqliteTable("scan_logs", {
|
||||
message: text("message").notNull(),
|
||||
createdAt: text("created_at").notNull(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Manuell angelegtes Lesezeichen – im Unterschied zu Diensten nicht an ein
|
||||
* gescanntes Gerät gebunden, eigenständige Tabelle. Erscheint zusammen mit
|
||||
* Diensten in der Suche (siehe packages/shared rankServices), wird aber
|
||||
* separat verwaltet (Admin -> Lesezeichen).
|
||||
*/
|
||||
export const bookmarks = sqliteTable("bookmarks", {
|
||||
id: text("id").primaryKey(),
|
||||
url: text("url").notNull(),
|
||||
displayName: text("display_name").notNull(),
|
||||
hostname: text("hostname").notNull(), // aus der URL abgeleitet
|
||||
description: text("description"),
|
||||
category: text("category"),
|
||||
icon: text("icon"),
|
||||
favicon: text("favicon"),
|
||||
favorite: integer("favorite", { mode: "boolean" }).notNull().default(false),
|
||||
alias: text("alias").notNull().default("[]"),
|
||||
order: real("order").notNull().default(0),
|
||||
createdAt: text("created_at").notNull(),
|
||||
updatedAt: text("updated_at").notNull(),
|
||||
});
|
||||
|
||||
@@ -10,8 +10,10 @@ import { scanRoutes } from "./routes/scan.js";
|
||||
import { logRoutes } from "./routes/logs.js";
|
||||
import { pluginRoutes } from "./routes/plugins.js";
|
||||
import { resetRoutes } from "./routes/reset.js";
|
||||
import { bookmarkRoutes } from "./routes/bookmarks.js";
|
||||
import { loadPlugins } from "./plugins/loader.js";
|
||||
import * as serviceRepo from "./db/repositories/services.js";
|
||||
import * as bookmarkRepo from "./db/repositories/bookmarks.js";
|
||||
import * as categoryRepo from "./db/repositories/categories.js";
|
||||
|
||||
const PORT = Number(process.env.PORT ?? 3001);
|
||||
@@ -40,10 +42,10 @@ async function main() {
|
||||
// der Suche als Kategorie auftaucht.
|
||||
const existingCategoryNames = Array.from(
|
||||
new Set(
|
||||
serviceRepo
|
||||
.listServices()
|
||||
.map((s) => s.category)
|
||||
.filter((c): c is string => !!c)
|
||||
[
|
||||
...serviceRepo.listServices().map((s) => s.category),
|
||||
...bookmarkRepo.listBookmarks().map((b) => b.category),
|
||||
].filter((c): c is string => !!c)
|
||||
)
|
||||
);
|
||||
const syncedCount = categoryRepo.syncCategoriesFromServiceValues(existingCategoryNames);
|
||||
@@ -62,6 +64,7 @@ async function main() {
|
||||
await app.register(logRoutes);
|
||||
await app.register(pluginRoutes);
|
||||
await app.register(resetRoutes);
|
||||
await app.register(bookmarkRoutes);
|
||||
|
||||
app.get("/", async () => {
|
||||
return { name: "LaunchPad API", status: "running" };
|
||||
|
||||
86
apps/backend/src/routes/bookmarks.ts
Normal file
86
apps/backend/src/routes/bookmarks.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { BookmarkCreateSchema, BookmarkReorderSchema, BookmarkUpdateSchema } from "@launchpad/shared";
|
||||
import * as bookmarkRepo from "../db/repositories/bookmarks.js";
|
||||
import * as categoryRepo from "../db/repositories/categories.js";
|
||||
import { probeHttp } from "../scanner/http.js";
|
||||
|
||||
export async function bookmarkRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.get("/api/bookmarks", async () => {
|
||||
return bookmarkRepo.listBookmarks();
|
||||
});
|
||||
|
||||
app.get("/api/bookmarks/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const bookmark = bookmarkRepo.getBookmark(id);
|
||||
if (!bookmark) {
|
||||
return reply.code(404).send({ error: "Lesezeichen nicht gefunden" });
|
||||
}
|
||||
return bookmark;
|
||||
});
|
||||
|
||||
app.post("/api/bookmarks", async (request, reply) => {
|
||||
const parsed = BookmarkCreateSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: "Ungültige Eingabe", issues: parsed.error.issues });
|
||||
}
|
||||
|
||||
let displayName = parsed.data.displayName;
|
||||
let favicon: string | null = null;
|
||||
|
||||
// Titel/Favicon automatisch ziehen, falls kein Name angegeben wurde oder
|
||||
// schlicht um ein Favicon zu bekommen (derselbe Mechanismus wie beim
|
||||
// Netzwerk-Scanner, siehe apps/backend/src/scanner/http.ts).
|
||||
try {
|
||||
const probe = await probeHttp(parsed.data.url, 5000);
|
||||
if (!displayName) {
|
||||
displayName = probe.title ?? bookmarkRepo.extractHostname(parsed.data.url);
|
||||
}
|
||||
favicon = probe.faviconUrl ?? null;
|
||||
} catch {
|
||||
if (!displayName) {
|
||||
displayName = bookmarkRepo.extractHostname(parsed.data.url);
|
||||
}
|
||||
}
|
||||
|
||||
if (parsed.data.category) {
|
||||
categoryRepo.ensureCategory(parsed.data.category);
|
||||
}
|
||||
|
||||
const bookmark = bookmarkRepo.createBookmark(parsed.data, { displayName, favicon });
|
||||
return reply.code(201).send(bookmark);
|
||||
});
|
||||
|
||||
// Muss vor der /:id-Route stehen, damit "reorder" nicht als ID interpretiert wird.
|
||||
app.patch("/api/bookmarks/reorder", async (request, reply) => {
|
||||
const parsed = BookmarkReorderSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: "Ungültige Eingabe", issues: parsed.error.issues });
|
||||
}
|
||||
return bookmarkRepo.reorderBookmarks(parsed.data);
|
||||
});
|
||||
|
||||
app.patch("/api/bookmarks/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const parsed = BookmarkUpdateSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: "Ungültige Eingabe", issues: parsed.error.issues });
|
||||
}
|
||||
if (parsed.data.category) {
|
||||
categoryRepo.ensureCategory(parsed.data.category);
|
||||
}
|
||||
const bookmark = bookmarkRepo.updateBookmark(id, parsed.data);
|
||||
if (!bookmark) {
|
||||
return reply.code(404).send({ error: "Lesezeichen nicht gefunden" });
|
||||
}
|
||||
return bookmark;
|
||||
});
|
||||
|
||||
app.delete("/api/bookmarks/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const deleted = bookmarkRepo.deleteBookmark(id);
|
||||
if (!deleted) {
|
||||
return reply.code(404).send({ error: "Lesezeichen nicht gefunden" });
|
||||
}
|
||||
return reply.code(204).send();
|
||||
});
|
||||
}
|
||||
@@ -58,17 +58,19 @@ export async function scanRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
const created = results.filter((r) => r.created).length;
|
||||
const updated = results.filter((r) => !r.created).length;
|
||||
const ports = discovered.map((d) => d.port).sort((a, b) => a - b);
|
||||
|
||||
logRepo.logScan({
|
||||
type: "device",
|
||||
targetId: device.id,
|
||||
level: "info",
|
||||
message: `${device.hostname} (${device.ip}): ${discovered.length} Dienst(e) gefunden, ${created} neu, ${updated} aktualisiert`,
|
||||
message: `${device.hostname} (${device.ip}): ${discovered.length} Dienst(e) gefunden (Ports: ${ports.join(", ") || "keine"}), ${created} neu, ${updated} aktualisiert`,
|
||||
});
|
||||
|
||||
return {
|
||||
deviceId: device.id,
|
||||
scannedPorts: discovered.length,
|
||||
ports,
|
||||
created,
|
||||
updated,
|
||||
services: results.map((r) => r.service),
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import * as XLSX from "xlsx";
|
||||
import { ServiceCreateSchema, ServiceReorderSchema, ServiceUpdateSchema } from "@launchpad/shared";
|
||||
import * as deviceRepo from "../db/repositories/devices.js";
|
||||
import * as serviceRepo from "../db/repositories/services.js";
|
||||
import * as categoryRepo from "../db/repositories/categories.js";
|
||||
|
||||
interface ServiceListQuery {
|
||||
deviceId?: string;
|
||||
@@ -9,6 +11,45 @@ interface ServiceListQuery {
|
||||
favorite?: string;
|
||||
}
|
||||
|
||||
interface ExportRow {
|
||||
displayName: string;
|
||||
category: string;
|
||||
alias: string;
|
||||
favorite: string;
|
||||
visible: string;
|
||||
order: number;
|
||||
hostname: string;
|
||||
port: number;
|
||||
https: string;
|
||||
url: string;
|
||||
deviceHostname: string;
|
||||
deviceIp: string;
|
||||
}
|
||||
|
||||
function buildExportRows(): ExportRow[] {
|
||||
const services = serviceRepo.listServices();
|
||||
const devices = deviceRepo.listDevices();
|
||||
const deviceById = new Map(devices.map((d) => [d.id, d]));
|
||||
|
||||
return services.map((s) => {
|
||||
const device = deviceById.get(s.deviceId);
|
||||
return {
|
||||
displayName: s.displayName,
|
||||
category: s.category ?? "",
|
||||
alias: s.alias.join(";"),
|
||||
favorite: s.favorite ? "true" : "false",
|
||||
visible: s.visible ? "true" : "false",
|
||||
order: s.order,
|
||||
hostname: s.hostname,
|
||||
port: s.port,
|
||||
https: s.https ? "true" : "false",
|
||||
url: s.url,
|
||||
deviceHostname: device?.hostname ?? "",
|
||||
deviceIp: device?.ip ?? "",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function serviceRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.get("/api/services", async (request) => {
|
||||
const query = request.query as ServiceListQuery;
|
||||
@@ -43,6 +84,136 @@ export async function serviceRoutes(app: FastifyInstance): Promise<void> {
|
||||
return reply.code(201).send(service);
|
||||
});
|
||||
|
||||
// Müssen vor der /:id-Route stehen, damit "export"/"import" nicht als ID interpretiert wird.
|
||||
app.get("/api/services/export", async (request, reply) => {
|
||||
const query = request.query as { format?: string };
|
||||
const format = query.format === "xlsx" ? "xlsx" : query.format === "json" ? "json" : "csv";
|
||||
const rows = buildExportRows();
|
||||
|
||||
if (format === "json") {
|
||||
reply.header("Content-Disposition", 'attachment; filename="launchpad-services.json"');
|
||||
reply.type("application/json");
|
||||
return rows;
|
||||
}
|
||||
|
||||
const worksheet = XLSX.utils.json_to_sheet(rows);
|
||||
|
||||
if (format === "xlsx") {
|
||||
const workbook = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, "Dienste");
|
||||
const buffer = XLSX.write(workbook, { type: "buffer", bookType: "xlsx" }) as Buffer;
|
||||
reply.header("Content-Disposition", 'attachment; filename="launchpad-services.xlsx"');
|
||||
reply.type("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
return reply.send(buffer);
|
||||
}
|
||||
|
||||
const csv = XLSX.utils.sheet_to_csv(worksheet);
|
||||
reply.header("Content-Disposition", 'attachment; filename="launchpad-services.csv"');
|
||||
reply.type("text/csv; charset=utf-8");
|
||||
return reply.send(csv);
|
||||
});
|
||||
|
||||
app.post("/api/services/import", async (request, reply) => {
|
||||
const body = request.body as { format?: string; content?: string } | undefined;
|
||||
if (!body?.content) {
|
||||
return reply.code(400).send({ error: "Kein Dateiinhalt übermittelt" });
|
||||
}
|
||||
|
||||
let rows: Record<string, unknown>[];
|
||||
try {
|
||||
if (body.format === "json") {
|
||||
const text = Buffer.from(body.content, "base64").toString("utf-8");
|
||||
rows = JSON.parse(text);
|
||||
} else {
|
||||
const buffer = Buffer.from(body.content, "base64");
|
||||
const workbook = XLSX.read(buffer, { type: "buffer" });
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: "" });
|
||||
}
|
||||
} catch (err) {
|
||||
return reply.code(400).send({
|
||||
error: "Datei konnte nicht gelesen werden",
|
||||
detail: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
|
||||
let imported = 0;
|
||||
let skipped = 0;
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const deviceHostname = String(row.deviceHostname ?? "").trim();
|
||||
const deviceIp = String(row.deviceIp ?? "").trim();
|
||||
const hostname = String(row.hostname ?? deviceHostname).trim();
|
||||
const port = Number(row.port);
|
||||
const displayName = String(row.displayName ?? "").trim();
|
||||
const url = String(row.url ?? "").trim();
|
||||
|
||||
if (!displayName || !hostname || !port || !url) {
|
||||
errors.push(`Zeile übersprungen (Pflichtfelder fehlen): ${JSON.stringify(row)}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Gerät über IP finden, sonst über Hostname, sonst neu anlegen.
|
||||
const allDevices = deviceRepo.listDevices();
|
||||
let device = deviceIp ? allDevices.find((d) => d.ip === deviceIp) : undefined;
|
||||
if (!device && deviceHostname) {
|
||||
device = allDevices.find((d) => d.hostname === deviceHostname);
|
||||
}
|
||||
if (!device) {
|
||||
device = deviceRepo.createDevice({
|
||||
hostname: deviceHostname || hostname,
|
||||
ip: deviceIp || hostname,
|
||||
});
|
||||
}
|
||||
|
||||
// Bereits vorhanden (gleiches Gerät + Port)? -> überspringen, nicht
|
||||
// doppelt anlegen und nichts Bestehendes verändern/löschen.
|
||||
const existing = serviceRepo.listServicesByDevice(device.id).find((s) => s.port === port);
|
||||
if (existing) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const category = row.category ? String(row.category).trim() : undefined;
|
||||
|
||||
serviceRepo.createService({
|
||||
deviceId: device.id,
|
||||
displayName,
|
||||
hostname,
|
||||
url,
|
||||
https: String(row.https ?? "").toLowerCase() === "true",
|
||||
port,
|
||||
category: category || undefined,
|
||||
alias: row.alias
|
||||
? String(row.alias)
|
||||
.split(";")
|
||||
.map((a) => a.trim())
|
||||
.filter(Boolean)
|
||||
: undefined,
|
||||
favorite: String(row.favorite ?? "").toLowerCase() === "true",
|
||||
order:
|
||||
row.order !== undefined && row.order !== "" ? Number(row.order) : undefined,
|
||||
visible:
|
||||
row.visible !== undefined && row.visible !== ""
|
||||
? String(row.visible).toLowerCase() === "true"
|
||||
: undefined,
|
||||
});
|
||||
|
||||
if (category) {
|
||||
categoryRepo.ensureCategory(category);
|
||||
}
|
||||
|
||||
imported++;
|
||||
} catch (err) {
|
||||
errors.push(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return { imported, skipped, errors };
|
||||
});
|
||||
|
||||
// Muss vor der /:id-Route stehen, damit "reorder" nicht als ID interpretiert wird.
|
||||
app.patch("/api/services/reorder", async (request, reply) => {
|
||||
const parsed = ServiceReorderSchema.safeParse(request.body);
|
||||
|
||||
Reference in New Issue
Block a user