39 Commits

Author SHA1 Message Date
tueem e05aa849c7 Merge pull request 'Add frontend' (#20) from feat/frontend into dev
build / Go-Build (push) Successful in 1m28s
docker / docker (push) Successful in 5m38s
Reviewed-on: #20
2026-05-28 20:37:53 +00:00
tueem 293c720eeb fix(frontend): key as config flag
build / Go-Build (push) Successful in 1m29s
build / Go-Build (pull_request) Successful in 1m27s
2026-05-28 12:17:04 +02:00
tueem 2dfc206fea feat(frontend): add frontend files and handling 2026-05-28 12:16:23 +02:00
tueem 7347565cda fix(cors): add PATCH to allowed CORS methods
build / Go-Build (push) Failing after 14m14s
2026-05-27 23:59:18 +02:00
tueem e87097e692 Merge pull request 'Add multiple Page capability' (#19) from feat/multi-page into dev
build / Go-Build (push) Successful in 1m27s
Reviewed-on: #19
2026-05-27 21:24:02 +00:00
tueem 70e14ec63c feat(page): add Page action endpoints
build / Go-Build (push) Successful in 1m26s
build / Go-Build (pull_request) Successful in 1m27s
2026-05-27 23:07:35 +02:00
tueem 664ae1f7d3 fix(page): fix AddPage not checking if the template actually existed. 2026-05-27 23:07:08 +02:00
tueem ae65322aa0 fix(page): move pages back when one is deleted inbetween. 2026-05-27 22:53:21 +02:00
tueem ba2332ecb6 feat(template): add multiple page support to templates
build / Go-Build (push) Successful in 1m30s
2026-05-27 22:02:11 +02:00
tueem 2aab1bcdd2 feat(template): add multi page upload capability
build / Go-Build (push) Successful in 1m30s
2026-05-27 00:59:25 +02:00
tueem 7017af9f3f Merge pull request 'Add name to template' (#17) from feat/names into dev
build / Go-Build (push) Successful in 1m30s
Reviewed-on: #17
2026-05-26 13:02:16 +00:00
tueem 633859cabe feat(template): add name to the template definition
build / Go-Build (push) Successful in 3m1s
build / Go-Build (pull_request) Successful in 1m27s
2026-05-26 14:47:03 +02:00
tueem 20cb740eb6 fix(download): fix filename parsing
build / Go-Build (push) Successful in 1m29s
2026-05-26 02:33:00 +02:00
tueem 9097d4257d fix(download): use path instead of filepath
build / Go-Build (push) Successful in 1m26s
2026-05-26 02:05:26 +02:00
tueem 75ebe4ec70 fix(public): fix wrong mux for public endoint
build / Go-Build (push) Successful in 1m25s
2026-05-26 01:37:26 +02:00
tueem 0277fcfdbc fix(download): add POST as an allowed download method for frontend
build / Go-Build (push) Successful in 1m25s
2026-05-26 01:20:16 +02:00
tueem d891321780 fix(cors): add CORS middleware
build / Go-Build (push) Successful in 1m28s
2026-05-26 00:48:00 +02:00
tueem 54a16fab4a fix(get): answer with valid json array
build / Go-Build (push) Failing after 13m5s
2026-05-25 23:55:24 +02:00
tueem 48291430f5 Merge pull request 'Add GET endpoint for all svg templates' (#15) from feat/get into dev
build / Go-Build (push) Successful in 1m25s
Reviewed-on: #15
2026-05-18 12:57:39 +00:00
tueem b378f30c05 feat(svg): add GET endpoint for all svg templates
build / Go-Build (pull_request) Successful in 1m26s
build / Go-Build (push) Successful in 1m26s
2026-05-18 14:41:25 +02:00
tueem 4f9cb5fbe9 Merge pull request 'Add template delete functionality' (#13) from feat/delete into dev
build / Go-Build (push) Successful in 1m27s
Reviewed-on: #13
2026-05-17 11:34:57 +00:00
tueem e39821a3e2 feat(svg): added svg template delete endpoint
build / Go-Build (push) Successful in 1m23s
build / Go-Build (pull_request) Successful in 1m23s
2026-05-15 17:24:45 +02:00
tueem 372bf4f97f Merge pull request 'Add SVG Templating' (#10) from feat/template into dev
build / Go-Build (push) Successful in 1m30s
Reviewed-on: #10
2026-05-15 12:32:23 +00:00
tueem f296eeeec7 fix(docker): adjust dockerfile for resvg
build / Go-Build (push) Successful in 3m31s
build / Go-Build (pull_request) Successful in 1m29s
2026-04-28 20:23:38 +02:00
tueem 26e543ac48 feat(format): switch to resvg backend
build / Go-Build (push) Successful in 28s
build / Go-Build (pull_request) Successful in 27s
2026-02-13 16:01:06 +01:00
tueem 0118a53d3e Merge branch 'dev' into feat/template
build / Go-Build (push) Successful in 1m8s
build / Go-Build (pull_request) Successful in 28s
2026-02-12 19:46:30 +01:00
tueem 6b61fe1e54 feat(fonts): add font endpoints
build / Go-Build (push) Successful in 27s
2026-02-12 15:41:23 +01:00
tueem 56abe1dee4 fix(docker): fix Dockerfile
build / Go-Build (push) Failing after 11m3s
build / Go-Build (pull_request) Successful in 28s
2026-02-09 23:23:44 +01:00
tueem 7c5d319043 fix(database): move database file to storage dir 2026-02-09 23:23:24 +01:00
tueem 205b70eeab feat(template): add Templating functionality and endpoint
build / Go-Build (push) Successful in 1m38s
build / Go-Build (pull_request) Successful in 39s
2026-02-09 11:09:19 +01:00
tueem de3ba44093 fix(storage): change to mkdirall to avoid error 2026-02-09 11:08:48 +01:00
tueem 343abe9bb5 fix(storage): add missing io.Copy 2026-02-09 09:59:03 +01:00
tueem ba90d5a0ed fix(db): incorrect columen name 2026-02-09 09:56:03 +01:00
tueem 6cf349bafa refactor(upload): move Regex to variable 2026-02-09 08:19:30 +01:00
tueem 823f5f091a fix(storage): fix return value of CreatePublic to return the trimmed file name 2026-02-09 08:18:44 +01:00
tueem 541caffd65 feat(template): add DB Get functions 2026-02-09 08:18:00 +01:00
tueem 1031ad7e8c feat(template): add Fileserver for download
build / Go-Build (push) Failing after 12m37s
2026-02-08 22:46:58 +01:00
tueem 741b196497 feat(formatconverter): add formatconverter method using inkscape 2026-02-08 19:42:28 +01:00
tueem 7c6d8f4206 feat(template): add public storage and temp file method 2026-02-04 12:53:00 +01:00
32 changed files with 4656 additions and 94 deletions
+1
View File
@@ -25,3 +25,4 @@ go.work.sum
# env file
.env
storage.db
.DS_Store
+16
View File
@@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/svg-templater",
"args": ["-data", "${workspaceFolder}/data"]
}
]
}
+10 -2
View File
@@ -1,11 +1,19 @@
# Build stage
FROM golang:latest AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -v -o svg-templater ./...
RUN CGO_ENABLED=0 GOOS=linux go build -v -o svg-templater ./cmd/svg-templater
FROM alpine:latest
# Final stage
FROM debian:bookworm-slim
WORKDIR /root/
EXPOSE 3000
VOLUME ["/var/lib/svg-templater"]
RUN apt update && apt install -y curl tar \
&& curl -L https://github.com/linebender/resvg/releases/download/v0.47.0/resvg-linux-x86_64.tar.gz | tar -xz \
&& mv resvg /usr/local/bin/resvg \
&& chmod +x /usr/local/bin/resvg
COPY --from=builder /app/svg-templater /usr/local/bin/svg-templater
CMD ["svg-templater"]
+6
View File
@@ -0,0 +1,6 @@
package svgtemplater
import "embed"
//go:embed frontend/*
var Frontend embed.FS
+3 -8
View File
@@ -1,19 +1,14 @@
package main
import (
"log"
"tomatentum.net/svg-templater/internal/command"
"tomatentum.net/svg-templater/internal/database"
"tomatentum.net/svg-templater/pkg/format"
)
func main() {
if err := database.OpenSQLite(); err != nil {
log.Fatal("Failed opening DB:\n", err)
return
if !format.CheckResvg() {
panic("Resvg not found")
}
defer database.Close()
database.InitDB()
command.PrepareCommandLine()
command.HandleCommandline()
}
+1955
View File
File diff suppressed because it is too large Load Diff
+361
View File
@@ -0,0 +1,361 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG Templater - Premium Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@300;400;500;600;700;800&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body class="dark-theme">
<div class="app-container">
<!-- Navigation Header -->
<header class="app-header">
<div class="logo-area">
<div class="logo-icon">
<svg viewBox="0 0 24 24" width="22" height="22" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round">
<polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
<polyline points="2 17 12 22 22 17"></polyline>
<polyline points="2 12 12 17 22 12"></polyline>
</svg>
</div>
<h1>SVG <span>Templater</span></h1>
</div>
<div class="header-status">
<div class="status-badge" id="app-mode-badge">
<span class="pulse-dot"></span>
<span id="mode-text">Connecting...</span>
</div>
<span class="status-meta">
<span class="status-meta-item"><span id="stats-total-count">0</span> Vorlagen</span>
<span class="status-meta-item">Host: <span id="stats-api-host" class="text-truncate">Localhost</span></span>
<span id="stats-app-mode" class="hidden">Live</span>
</span>
</div>
</header>
<!-- Main Workspace -->
<main class="workspace-area">
<!-- VIEW 1: HOME PAGE (Upload + List) -->
<div id="view-home" class="view-content active">
<div class="grid-layout">
<!-- Left: Upload & Fonts Column -->
<div class="left-column">
<!-- Upload Section -->
<div class="card upload-card">
<div class="card-header">
<h2>Template hochladen</h2>
<p>Laden Sie eine SVG-Datei hoch, um Platzhalter wie <code>{{ variable }}</code> automatisch zu extrahieren.</p>
</div>
<div class="card-body">
<div class="drop-zone" id="svg-drop-zone">
<input type="file" id="svg-file-input" accept=".svg" class="file-input-hidden">
<div class="drop-zone-content">
<div class="drop-icon">
<svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" stroke-width="1.5" fill="none">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" y1="3" x2="12" y2="15"></line>
</svg>
</div>
<h3>SVG Datei hierher ziehen</h3>
<p>oder <span>Computer durchsuchen</span></p>
<span class="file-limits">Ausschließlich valide .svg Dateien</span>
</div>
</div>
</div>
</div>
<!-- Fonts Management Section -->
<div class="card font-card" style="margin-top: 28px;">
<div class="card-header">
<h2>Schriften verwalten</h2>
<p>Laden Sie globale TTF/OTF-Schriften hoch, die für Text-Renderings verwendet werden können.</p>
</div>
<div class="card-body">
<div class="font-list-container">
<h3>Installierte Schriften</h3>
<div class="spinner-small hidden" id="fonts-loading"></div>
<div class="font-list-empty" id="fonts-empty">
Keine benutzerdefinierten Schriften geladen.
</div>
<ul class="font-list hidden" id="fonts-list">
<!-- Injected dynamically -->
</ul>
</div>
<div class="form-divider" style="margin: 20px 0;"></div>
<div class="font-upload-area">
<input type="file" id="font-file-input" accept=".ttf,.otf" class="file-input-hidden" style="display: none;">
<button class="submit-btn amber-gradient" id="btn-upload-font" style="width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px;">
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2.5" fill="none">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" y1="3" x2="12" y2="15"></line>
</svg>
<span>Schriftart hochladen</span>
</button>
</div>
</div>
</div>
</div>
<!-- Right: Templates List -->
<div class="card templates-card">
<div class="card-header list-header-flex">
<div>
<h2>Meine Vorlagen</h2>
<p>Wählen Sie ein SVG-Template aus, um Variablen auszufüllen und Renderings zu erstellen.</p>
</div>
<button class="icon-btn-toggle" id="btn-toggle-demo" title="Demo-Modus umschalten">
<svg viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" stroke-width="2" fill="none">
<polygon points="5 3 19 12 5 21 5 3"></polygon>
</svg>
<span>Demo Mode</span>
</button>
</div>
<div class="card-body">
<!-- Loading indicator -->
<div class="loading-container hidden" id="templates-loading">
<div class="spinner"></div>
<p>Lade SVG Templates...</p>
</div>
<!-- Empty state -->
<div class="empty-state" id="templates-empty">
<div class="empty-icon">
<svg viewBox="0 0 24 24" width="40" height="40" stroke="currentColor" stroke-width="1.5" fill="none">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
<line x1="9" y1="9" x2="15" y2="15"></line>
<line x1="15" y1="9" x2="9" y2="15"></line>
</svg>
</div>
<h3>Keine Templates vorhanden</h3>
<p>Laden Sie Ihre erste SVG-Vorlage hoch oder aktivieren Sie den Demo-Modus, um fortzufahren.</p>
</div>
<!-- Templates Grid container -->
<div class="templates-grid hidden" id="templates-grid">
<!-- Cards injected dynamically via app.js -->
</div>
</div>
</div>
</div>
</div>
<!-- VIEW 2: EDITOR PAGE (Selected Template Form + Live Preview) -->
<div id="view-editor" class="view-content">
<div class="editor-navigation">
<button class="back-btn" id="btn-back-home">
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2.5" fill="none">
<polyline points="15 18 9 12 15 6"></polyline>
</svg>
Zurück zur Übersicht
</button>
<div class="active-template-title" style="display: flex; flex-direction: column; gap: 6px;">
<div style="display: flex; align-items: center; gap: 10px;">
<span class="tag">Vorlage</span>
<h2 id="editor-template-name">template_name.svg</h2>
<button class="preview-action-btn" id="btn-rename-active" title="Name zuweisen/ändern" style="height: 28px; width: 28px; padding: 0; display: flex; align-items: center; justify-content: center;">
<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2" fill="none">
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
<path d="M18.5 2.5a2.121 2.121 0 1 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
</svg>
</button>
</div>
<span class="template-id-sub" style="font-size: 11px; color: var(--text-muted); margin-top: 2px;">ID: <code id="editor-template-id" style="font-size: 10px; color: #ff79c6 !important; background: #08090d; border: 1px solid var(--border-color); padding: 2px 6px; border-radius: 2px;">template_id</code></span>
</div>
</div>
<div class="grid-layout-editor">
<div class="left-column-editor" style="display: flex; flex-direction: column; gap: 28px;">
<!-- Left: Variables Input Form -->
<div class="card variables-card">
<div class="card-header">
<h2>Variablen ausfüllen</h2>
<p>Geben Sie die Werte für die im SVG definierten Platzhalter ein.</p>
</div>
<div class="card-body">
<div id="dynamic-variables-form">
<div class="form-inputs-container" id="dynamic-inputs-area">
<!-- Injected dynamically via app.js -->
</div>
<div class="form-divider"></div>
<div class="rendering-settings">
<h3>Ausgabe-Einstellungen</h3>
<div class="setting-row">
<label>Dateiformat</label>
<div class="format-selector">
<button type="button" class="format-btn active" data-format="svg" id="format-svg">SVG</button>
<button type="button" class="format-btn" data-format="png" id="format-png">PNG</button>
</div>
</div>
<div class="setting-row resolution-settings hidden" id="resolution-settings">
<label>Auflösung (PNG)</label>
<div class="resolution-inputs">
<div class="input-with-label">
<input type="number" id="render-width" placeholder="Auto" min="1">
<span>Breite (px)</span>
</div>
<div class="input-with-label">
<input type="number" id="render-height" placeholder="Auto" min="1">
<span>Höhe (px)</span>
</div>
</div>
</div>
</div>
<button type="button" class="submit-btn purple-gradient" id="btn-submit-render">
<span class="btn-spinner hidden" id="render-spinner"></span>
<svg viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" stroke-width="2" fill="none" id="render-btn-icon">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</svg>
<span id="render-btn-text">Rendering erstellen</span>
</button>
</div>
</div>
</div>
<!-- Left: Pages Manager Panel -->
<div class="card pages-manager-card" id="editor-pages-manager-card">
<div class="card-header" style="padding: 20px 24px;">
<h2 style="font-size: 16px;">Seiten verwalten</h2>
<p style="font-size: 12px; margin-top: 2px;">Fügen Sie neue Seiten hinzu oder löschen Sie bestehende Seiten.</p>
</div>
<div class="card-body" style="padding: 20px 24px;">
<div class="pages-list-container" style="max-height: 240px; overflow-y: auto; margin-bottom: 16px; padding-right: 4px;">
<ul class="font-list" id="editor-pages-list" style="list-style: none; display: flex; flex-direction: column; gap: 10px; margin: 0; padding: 0;">
<!-- Injected dynamically via app.js -->
</ul>
</div>
<div class="form-divider" style="margin: 16px 0;"></div>
<div class="page-upload-area">
<input type="file" id="page-file-input" accept=".svg" multiple class="file-input-hidden" style="display: none;">
<button type="button" class="submit-btn indigo-gradient" id="btn-add-page" style="width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px; font-size: 12px; padding: 10px 16px;">
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2.5" fill="none">
<line x1="12" y1="5" x2="12" y2="19"></line>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
<span>Seite(n) hinzufügen</span>
</button>
</div>
</div>
</div>
</div>
<!-- Right: Live Canvas Preview -->
<div class="card preview-card">
<div class="card-header preview-header">
<h2>Live-Vorschau</h2>
<div class="preview-actions">
<div class="page-navigator" id="page-navigator" style="display: none; align-items: center; gap: 8px; margin-right: 8px;">
<button class="preview-action-btn" id="btn-page-prev" title="Vorherige Seite" style="width: 32px; height: 32px; padding: 0; display: flex; align-items: center; justify-content: center;">
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2.5" fill="none">
<polyline points="15 18 9 12 15 6"></polyline>
</svg>
</button>
<span id="page-indicator" style="font-size: 11px; font-weight: 700; color: var(--text-secondary); font-family: var(--font-body); min-width: 90px; text-align: center;">Seite 1 / 1</span>
<button class="preview-action-btn" id="btn-page-next" title="Nächste Seite" style="width: 32px; height: 32px; padding: 0; display: flex; align-items: center; justify-content: center;">
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2.5" fill="none">
<polyline points="9 18 15 12 9 6"></polyline>
</svg>
</button>
</div>
<span class="zoom-badge" id="zoom-badge" style="font-size: 11px; font-weight: 700; color: var(--text-secondary); background: rgba(255, 255, 255, 0.04); border: 1px solid var(--border-color); padding: 7px 10px; border-radius: 6px; font-family: var(--font-body); min-width: 54px; text-align: center; display: inline-flex; align-items: center; justify-content: center; height: 32px;">100%</span>
<button class="preview-action-btn" id="btn-zoom-in" title="Vergrößern">
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="11" y1="8" x2="11" y2="14"></line>
<line x1="8" y1="11" x2="14" y2="11"></line>
</svg>
</button>
<button class="preview-action-btn" id="btn-zoom-out" title="Verkleinern">
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="8" y1="11" x2="14" y2="11"></line>
</svg>
</button>
<button class="preview-action-btn" id="btn-zoom-reset" title="Zoom zurücksetzen">
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path>
<polyline points="3 3 3 8 8 8"></polyline>
</svg>
</button>
<button class="preview-action-btn" id="btn-fullscreen" title="Vollbildmodus">
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
<path d="M15 3h6v6"></path>
<path d="M9 21H3v-6"></path>
<path d="M21 3l-7 7"></path>
<path d="M3 21l7-7"></path>
</svg>
</button>
<button class="download-action-btn hidden" id="btn-download-preview" title="Grafik herunterladen" style="margin-left: 8px;">
<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2.5" fill="none">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</svg>
<span>Download</span>
</button>
<button class="download-action-btn download-all-btn hidden" id="btn-download-all" title="Alle Seiten gleichzeitig herunterladen" style="margin-left: 8px;">
<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2.5" fill="none">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</svg>
<span>Alle Seiten</span>
</button>
</div>
</div>
<div class="card-body canvas-body">
<div class="canvas-viewport" id="preview-viewport">
<!-- Interactive dynamic placeholder / SVG preview canvas -->
<div class="canvas-container" id="preview-canvas-container">
<div class="canvas-loading hidden" id="preview-loading-overlay">
<div class="spinner"></div>
<p>Rendere Grafik...</p>
</div>
<div class="canvas-placeholder" id="preview-placeholder">
<svg viewBox="0 0 24 24" width="64" height="64" stroke="currentColor" stroke-width="1.2" fill="none" class="pulse-opacity">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
<circle cx="8.5" cy="8.5" r="1.5"></circle>
<polyline points="21 15 16 10 5 21"></polyline>
</svg>
<p>Werte eintragen und Rendering starten</p>
</div>
<img id="preview-image" class="hidden" alt="Rendered Preview" draggable="false">
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<footer class="app-footer">
<p>&copy; 2026 SVG Templater Dashboard. Mit Liebe pair-programmiert von Antigravity.</p>
</footer>
</div>
<!-- Toast Notifications Container -->
<div class="toast-container" id="toast-container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="app.js"></script>
</body>
</html>
+1124
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -2,10 +2,12 @@ module tomatentum.net/svg-templater
go 1.24.9
require github.com/glebarez/go-sqlite v1.22.0
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/glebarez/go-sqlite v1.22.0
github.com/google/uuid v1.5.0 // indirect
github.com/hymkor/exregexp-go v0.2.0
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/image v0.36.0
+2
View File
@@ -4,6 +4,8 @@ github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hymkor/exregexp-go v0.2.0 h1:tyIB8S9gpUwiBi3aDXXXL2yIXqTMWZzW3hs+UNDqcRM=
github.com/hymkor/exregexp-go v0.2.0/go.mod h1:bm661vkJcg9TbcYNr7QOcOgGlr+Jxy1Qb84YjVON3bg=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+17 -1
View File
@@ -2,7 +2,9 @@ package command
import (
"flag"
"log"
"tomatentum.net/svg-templater/internal/database"
"tomatentum.net/svg-templater/internal/server"
"tomatentum.net/svg-templater/pkg/svg"
)
@@ -12,6 +14,7 @@ var (
generateTokenFlag bool
deleteTokenFlag bool
datapath string
frontendkey string
)
func PrepareCommandLine() {
@@ -19,10 +22,22 @@ func PrepareCommandLine() {
flag.BoolVar(&generateTokenFlag, "tokengen", false, "Generate token with name")
flag.BoolVar(&deleteTokenFlag, "tokendel", false, "Delete token with name")
flag.StringVar(&datapath, "data", "/var/lib/svg-templater", "Override data directory")
flag.StringVar(&frontendkey, "frontendkey", "", "Specify the api key the frontend should use")
}
func HandleCommandline() {
flag.Parse()
if !help {
svg.Storage = svg.NewFileStorage(datapath, "public", "fonts")
if err := database.OpenSQLite(datapath); err != nil {
log.Fatal("Failed opening DB:\n", err)
return
}
database.InitDB()
}
defer database.Close()
if generateTokenFlag {
GenerateTokenCommand()
} else if deleteTokenFlag {
@@ -30,8 +45,9 @@ func HandleCommandline() {
} else if help {
flag.PrintDefaults()
} else {
svg.Storage = svg.NewFileStorage(datapath, "fonts")
svg.Storage = svg.NewFileStorage(datapath, "public", "fonts")
server.PrepareHTTP()
server.PrepareFrontend(frontendkey)
server.Start()
}
}
+8 -2
View File
@@ -3,6 +3,7 @@ package database
import (
"database/sql"
"log"
"path/filepath"
_ "github.com/glebarez/go-sqlite"
)
@@ -11,8 +12,8 @@ const FILENAME string = "storage.db"
var database *sql.DB
func OpenSQLite() error {
db, err := sql.Open("sqlite", FILENAME)
func OpenSQLite(basepath string) error {
db, err := sql.Open("sqlite", filepath.Join(basepath, FILENAME))
if err != nil {
return err
}
@@ -24,6 +25,8 @@ func OpenSQLite() error {
func InitDB() {
_, err := database.Exec(TOKENTABLECREATE)
_, err = database.Exec(SVGTABLECREATE)
_, err = database.Exec(SVGPAGETABLECREATE)
if err != nil {
log.Fatal("Failed to init database:\n", err)
}
@@ -31,5 +34,8 @@ func InitDB() {
}
func Close() error {
if database == nil {
return nil
}
return database.Close()
}
+90 -10
View File
@@ -1,28 +1,108 @@
package database
import (
"encoding/json"
"tomatentum.net/svg-templater/pkg/svg"
)
const SVGTABLECREATE string = `
CREATE TABLE IF NOT EXISTS svg (
name varchar(16) PRIMARY KEY NOT NULL,
templatekeys longtext NOT NULL
id varchar(16) PRIMARY KEY NOT NULL,
name varchar(32)
);`
const INSERTSVGSQL string = "INSERT INTO svg VALUES (?, ?);"
const GETSPECIFICSVGSQL string = "SELECT * FROM svg WHERE id = ?;"
const GETSVGSQL string = "SELECT * FROM svg;"
const DELETESVGSQL string = "DELETE FROM svg WHERE id = ?;"
const RENAMESVGSQL string = "UPDATE svg SET name = ? WHERE id = ?;"
const EXISTSSVGSQL string = "SELECT COUNT(*) FROM svg WHERE id = ?;"
func InsertSVG(data *svg.TemplateData) error {
json, err := json.Marshal(data.TemplateKeys)
if err != nil {
return err
}
if _, err := database.Exec(INSERTSVGSQL, data.Id, string(json)); err != nil {
if _, err := database.Exec(INSERTSVGSQL, data.Id, data.Name); err != nil {
return err
}
return nil
}
func GetSVG() ([]svg.TemplateData, error) {
result, err := database.Query(GETSVGSQL)
if err != nil {
return nil, err
}
defer result.Close()
templates := make([]svg.TemplateData, 0)
for result.Next() {
var (
id string
name string
)
if err := result.Scan(&id, &name); err != nil {
return nil, err
}
pages, err := GetSVGPages(id)
if err != nil {
return nil, err
}
templates = append(templates, svg.TemplateData{Id: id, Name: name, Pages: pages})
}
if err := result.Err(); err != nil {
return nil, err
}
return templates, nil
}
func GetSpecificSVG(id string) (svg.TemplateData, error) {
result := database.QueryRow(GETSPECIFICSVGSQL, id)
var name string
if err := result.Scan(&id, &name); err != nil {
return svg.TemplateData{}, err
}
pages, err := GetSVGPages(id)
if err != nil {
return svg.TemplateData{}, err
}
return svg.TemplateData{Id: id, Name: name, Pages: pages}, nil
}
func DeleteSvg(id string) (bool, error) {
res, err := database.Exec(DELETESVGSQL, id)
if err != nil {
return false, err
}
num, err := res.RowsAffected()
if err != nil {
return false, err
}
if num == 0 {
return false, nil
}
return DeleteAllSVGPages(id)
}
func RenameSvg(id string, name string) error {
_, err := database.Exec(RENAMESVGSQL, name, id)
if err != nil {
return err
}
return nil
}
func Exists(id string) (bool, error) {
res := database.QueryRow(EXISTSSVGSQL, id)
var count int
if err := res.Scan(&count); err != nil {
return false, err
}
return count > 0, nil
}
+129
View File
@@ -0,0 +1,129 @@
package database
import (
"encoding/json"
"tomatentum.net/svg-templater/pkg/svg"
)
func AddPage(page svg.TemplatePage) {
}
func DeletePage(templateID string, page int) {
}
const SVGPAGETABLECREATE string = `
CREATE TABLE IF NOT EXISTS svgpage (
id varchar(16) NOT NULL,
page int NOT NULL,
templatekeys longtext NOT NULL,
PRIMARY KEY (id, page)
);`
const INSERTSVGPAGESQL string = "INSERT INTO svgpage VALUES (?, ?, ?);"
const GETSPECIFICSVGPAGESSQL string = "SELECT * FROM svgpage WHERE id = ?;"
const DELETESVGPAGESQL string = "DELETE FROM svgpage WHERE id = ? AND page = ?;"
const DELETEALLSVGPAGESQL string = "DELETE FROM svgpage WHERE id = ?;"
const COUNTSVGPAGESQL string = "SELECT COUNT(*) FROM svgpage WHERE id = ?;"
const UPDATEPAGESQL string = "UPDATE svgpage SET page = page - 1 WHERE page > ?;"
func InsertSVGPage(data *svg.TemplatePage) (int, error) {
json, err := json.Marshal(data.TemplateKeys)
if err != nil {
return 0, err
}
count, err := GetPageCount(data.TemplateId)
if err != nil {
return 0, err
}
if _, err := database.Exec(INSERTSVGPAGESQL, data.TemplateId, count+1, string(json)); err != nil {
return 0, err
}
return count + 1, nil
}
func GetSVGPages(id string) ([]svg.TemplatePage, error) {
res, err := database.Query(GETSPECIFICSVGPAGESSQL, id)
if err != nil {
return nil, err
}
defer res.Close()
pages := make([]svg.TemplatePage, 0)
for res.Next() {
var (
id string
page int
keysjson []byte
keys []string
)
if err := res.Scan(&id, &page, &keysjson); err != nil {
return nil, err
}
if err := json.Unmarshal(keysjson, &keys); err != nil {
return nil, err
}
pages = append(pages, svg.TemplatePage{TemplateId: id, Page: page, TemplateKeys: keys})
}
return pages, nil
}
func DeleteSVGPage(id string, page int) (bool, error) {
res, err := database.Exec(DELETESVGPAGESQL, id, page)
if err != nil {
return false, err
}
num, err := res.RowsAffected()
if err != nil {
return false, err
}
if num == 0 {
return false, nil
}
if err := movePages(id, page); err != nil {
return false, err
}
return true, nil
}
func DeleteAllSVGPages(id string) (bool, error) {
res, err := database.Exec(DELETEALLSVGPAGESQL, id)
if err != nil {
return false, err
}
num, err := res.RowsAffected()
if err != nil {
return false, err
}
if num == 0 {
return false, nil
}
return true, nil
}
func GetPageCount(id string) (int, error) {
res := database.QueryRow(COUNTSVGPAGESQL, id)
var count int
if err := res.Scan(&count); err != nil {
return 0, err
}
return count, nil
}
func movePages(id string, deletedPage int) error {
_, err := database.Exec(UPDATEPAGESQL, deletedPage)
return err
}
+26
View File
@@ -0,0 +1,26 @@
package routes
import (
"net/http"
"tomatentum.net/svg-templater/pkg/svg/actions"
)
func DeleteSvg(writer http.ResponseWriter, reader *http.Request) {
id := reader.PathValue("id")
if id == "" {
http.Error(writer, "No ID provided", http.StatusBadRequest)
return
}
success, err := actions.Delete(id)
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
if !success {
http.Error(writer, "No template to delete.", http.StatusBadRequest)
return
}
}
+112
View File
@@ -0,0 +1,112 @@
package routes
import (
"encoding/json"
"log"
"net/http"
"net/url"
"path"
"strconv"
"tomatentum.net/svg-templater/pkg/format"
"tomatentum.net/svg-templater/pkg/svg/actions"
)
type downloadRequest struct {
TemplateKeys map[string]string
}
type downloadResponse struct {
Urls []string
}
func DownloadSVG(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
http.Error(w, "Incorrect Content-Type. Needs application/json.", http.StatusUnsupportedMediaType)
return
}
var request downloadRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var err error
id := r.PathValue("id")
if id == "" {
http.Error(w, "No ID provided", http.StatusBadRequest)
return
}
widthString := r.URL.Query().Get("w")
width := 0
if widthString != "" {
width, err = strconv.Atoi(widthString)
if err != nil {
http.Error(w, "Invalid w parameter", http.StatusBadRequest)
return
}
}
heightString := r.URL.Query().Get("h")
height := 0
if heightString != "" {
height, err = strconv.Atoi(heightString)
if err != nil {
http.Error(w, "Invalid h parameter", http.StatusBadRequest)
return
}
}
convParam := format.ConversionParameters{
Format: r.URL.Query().Get("format"),
Width: width,
Height: height,
}
if convParam.Format == "" {
convParam.Format = "svg"
}
templateParam := actions.TemplateParameters{
Id: id,
Keys: request.TemplateKeys,
}
filenames, err := actions.ProvideFile(&templateParam, &convParam)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
urlsparsed := make([]string, len(filenames))
for i, filename := range filenames {
urlsparsed[i] = getPublicUrl(r, filename)
log.Printf("Made %s page %d available as %s\n", id, i, urlsparsed[i])
}
response := downloadResponse{
Urls: urlsparsed,
}
w.Header().Add("Content-Type", "application/json")
json, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(json)
}
func getPublicUrl(r *http.Request, subpath string) string {
newURL := url.URL{
Host: r.Host,
Path: path.Join("public", subpath),
}
newURL.Scheme = "http"
if r.TLS != nil {
newURL.Scheme = "https"
}
return newURL.String()
}
+36 -3
View File
@@ -1,12 +1,45 @@
package routes
import "net/http"
import (
"encoding/json"
"log"
"net/http"
"strings"
"tomatentum.net/svg-templater/pkg/svg"
)
func AddFont(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "font/ttf" {
contentType := r.Header.Get("Content-Type")
if contentType != "font/ttf" && contentType != "font/otf" {
http.Error(w, "", http.StatusUnsupportedMediaType)
return
}
log.Println("Received font add request")
format := strings.TrimPrefix(contentType, "font/")
if err := svg.Storage.AddFont(r.Body, format); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Println(err)
return
}
}
func GetFonts(w http.ResponseWriter, r *http.Request) {
log.Println("Serving all available fonts")
fonts, err := svg.Storage.GetFonts()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Println(err)
return
}
json, err := json.Marshal(fonts)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Println(err)
return
}
w.Header().Add("Content-Type", "application/json")
w.Write(json)
}
+30
View File
@@ -0,0 +1,30 @@
package routes
import (
"encoding/json"
"net/http"
"tomatentum.net/svg-templater/internal/database"
)
func Get(w http.ResponseWriter, r *http.Request) {
svgs, err := database.GetSVG()
if err != nil {
http.Error(w, "Cannot fetch svgs from database", http.StatusInternalServerError)
return
}
data, err := json.Marshal(svgs)
if err != nil {
http.Error(w, "An Error occurred while encoding json.", http.StatusInternalServerError)
return
}
_, err = w.Write(data)
if err != nil {
http.Error(w, "Could not write data.", http.StatusInternalServerError)
return
}
}
+80
View File
@@ -0,0 +1,80 @@
package routes
import (
"encoding/json"
"io"
"net/http"
"strconv"
"tomatentum.net/svg-templater/pkg/svg"
"tomatentum.net/svg-templater/pkg/svg/actions"
)
func AddPage(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(128000000); err != nil {
http.Error(w, "Couldn't parse form data.", http.StatusBadRequest)
return
}
fileheaders := r.MultipartForm.File["files"]
id := r.PathValue("id")
pages := make([]svg.TemplatePage, len(fileheaders))
for i, fileh := range fileheaders {
file, err := fileh.Open()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
buf, err := io.ReadAll(file)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
page, err := actions.AddPage(id, buf)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
pages[i] = page
}
err := json.NewEncoder(w).Encode(pages)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func DeletePage(w http.ResponseWriter, r *http.Request) {
id, pagestring := r.PathValue("id"), r.PathValue("page")
page, err := strconv.Atoi(pagestring)
if err != nil {
http.Error(w, "Page must be a number", http.StatusBadRequest)
return
}
ok, err := actions.DeletePage(id, page)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !ok {
http.Error(w, "Could not delete page", http.StatusInternalServerError)
return
}
}
+37
View File
@@ -0,0 +1,37 @@
package routes
import (
"encoding/json"
"net/http"
"tomatentum.net/svg-templater/pkg/svg/actions"
)
type renameRequest struct {
Name string
}
func RenameSvg(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
http.Error(w, "Incorrect Content-Type. Needs application/json.", http.StatusUnsupportedMediaType)
return
}
var request renameRequest
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
http.Error(w, "Could not decode body.", http.StatusBadRequest)
return
}
id := r.PathValue("id")
err = actions.RenameSvg(id, request.Name)
if err != nil {
http.Error(w, "Error while renaming", http.StatusInternalServerError)
return
}
}
+29 -14
View File
@@ -10,38 +10,53 @@ import (
"tomatentum.net/svg-templater/pkg/svg/actions"
)
func CreateSVG(writer http.ResponseWriter, r http.Request) {
func CreateSVG(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get("Content-Type")
if contentType != "image/svg+xml" {
http.Error(writer, "Incorrect Content-Type. Needs image/svg+xml.", http.StatusUnsupportedMediaType)
if err := r.ParseMultipartForm(128000000); err != nil {
http.Error(w, "Couldn't parse form data.", http.StatusBadRequest)
return
}
readsvg, err := io.ReadAll(r.Body)
fileheaders := r.MultipartForm.File["files"]
files := make([][]byte, len(fileheaders))
for i, fileh := range fileheaders {
file, err := fileh.Open()
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
log.Println("Error while reading Body\n", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if ok, err := validateSVG(readsvg); err != nil || !ok {
http.Error(writer, err.Error(), http.StatusUnsupportedMediaType)
buf, err := io.ReadAll(file)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if ok, err := validateSVG(buf); err != nil || !ok {
http.Error(w, err.Error(), http.StatusUnsupportedMediaType)
log.Println("Wrong Media Type was uploaded\n", err)
return
}
data, err := actions.Create(readsvg)
files[i] = buf
}
name := r.URL.Query().Get("name")
data, err := actions.Create(files, name)
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Println("Failed creating SVG template\n", err)
return
}
writer.Header().Add("Content-Type", "application/json")
json.NewEncoder(writer).Encode(data)
log.Println("Created SVG Template " + data.Id)
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}
func validateSVG(svgbuf []byte) (bool, error) {
+16
View File
@@ -0,0 +1,16 @@
package server
import "net/http"
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
+98 -8
View File
@@ -1,35 +1,125 @@
package server
import (
"fmt"
"io/fs"
"log"
"net/http"
"text/template"
svgtemplater "tomatentum.net/svg-templater"
"tomatentum.net/svg-templater/internal/routes"
"tomatentum.net/svg-templater/pkg/auth"
"tomatentum.net/svg-templater/pkg/svg"
)
var mux http.ServeMux
func PrepareHTTP() {
registerAuthorized("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "You are authorized!")
mux = *http.NewServeMux()
registerAuthorizedFunc("/svg/", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
routes.CreateSVG(w, r)
return
case "GET":
routes.Get(w, r)
return
}
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
})
registerAuthorized("/svg/", func(w http.ResponseWriter, r *http.Request) {
registerAuthorizedFunc("/svg/{id}", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET", "POST":
routes.DownloadSVG(w, r)
return
case "PATCH":
routes.RenameSvg(w, r)
return
case "DELETE":
routes.DeleteSvg(w, r)
return
}
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
})
registerAuthorizedFunc("/svg/{id}/page/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
routes.CreateSVG(w, *r)
routes.AddPage(w, r)
})
registerAuthorizedFunc("/svg/{id}/page/{page}", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "DELETE" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
routes.DeletePage(w, r)
})
registerAuthorizedFunc("/font/", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
routes.GetFonts(w, r)
case "POST":
routes.AddFont(w, r)
}
})
mux.Handle("/public/", http.StripPrefix("/public/", http.FileServer(svg.Storage.GetPublicDir())))
}
func PrepareFrontend(key string) {
webFS, _ := fs.Sub(svgtemplater.Frontend, "frontend")
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/app.js" {
http.FileServer(http.FS(webFS)).ServeHTTP(w, r)
return
}
tmplData, err := fs.ReadFile(webFS, "app.js")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl, err := template.New("index").Delims("[[", "]]").Parse(string(tmplData))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Execute with environment variables
data := map[string]string{
"APIKey": key,
"APIUrl": "",
}
if err := tmpl.Execute(w, data); err != nil {
http.Error(w, "Coudln't render template", http.StatusInternalServerError)
return
}
})
}
func Start() {
log.Println("Starting http server on :3000")
if err := http.ListenAndServe(":3000", nil); err != nil {
handler := corsMiddleware(&mux)
if err := http.ListenAndServe(":3000", handler); err != nil {
panic(err)
}
}
func registerAuthorized(path string, f func(w http.ResponseWriter, r *http.Request)) {
http.HandleFunc(path, auth.AuthMiddleware(http.HandlerFunc(f)))
func registerAuthorized(path string, handler http.Handler) {
mux.HandleFunc(path, auth.AuthMiddleware(handler))
log.Println("Registered authorized handler for", path)
}
func registerAuthorizedFunc(path string, f func(w http.ResponseWriter, r *http.Request)) {
registerAuthorized(path, http.HandlerFunc(f))
}
+94
View File
@@ -0,0 +1,94 @@
package format
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"tomatentum.net/svg-templater/pkg/svg"
)
type ConversionParameters struct {
Format string
Width, Height int
}
func ConvertByte(svgblob []byte, param ConversionParameters) ([]byte, error) {
reader, err := ConvertReader(svgblob, param)
if err != nil {
return nil, err
}
defer reader.Close()
result, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
return result, nil
}
func ConvertReader(svgblob []byte, param ConversionParameters) (io.ReadCloser, error) {
if param.Format == "svg" {
return io.NopCloser(bytes.NewReader(svgblob)), nil
}
file, err := svg.CreateTemp(bytes.NewReader(svgblob), "svg")
if err != nil {
return nil, err
}
defer os.Remove(file)
switch param.Format {
case "png":
return convertPNG(file, param)
}
return nil, errors.New("Format not supported")
}
func convertPNG(input string, param ConversionParameters) (io.ReadCloser, error) {
var args []string
var outExt string
fontsdir := svg.Storage.GetFontsDir()
args = append(args, "--skip-system-fonts")
args = append(args, "--use-fonts-dir", fontsdir)
if param.Width > 0 {
args = append(args, "-w", strconv.Itoa(param.Width))
}
if param.Height > 0 {
args = append(args, "-h", strconv.Itoa(param.Height))
}
outFile := strings.TrimSuffix(input, filepath.Ext(input)) + outExt
args = append(args, input)
args = append(args, outFile)
cmd := exec.Command("resvg", args...)
cmd.Dir = svg.TempDir
out, err := cmd.CombinedOutput()
log.Println(string(out))
if err != nil {
return nil, fmt.Errorf("resvg failed: %w: %s", err, string(out))
}
file, err := os.Open(outFile)
if err != nil {
return nil, err
}
return file, nil
}
func CheckResvg() bool {
_, err := exec.LookPath("resvg")
return err == nil
}
+30
View File
@@ -0,0 +1,30 @@
package actions
import (
"log"
"strings"
"tomatentum.net/svg-templater/internal/database"
"tomatentum.net/svg-templater/pkg/svg"
)
func Delete(id string) (bool, error) {
if success, err := database.DeleteSvg(id); err != nil || !success {
return success, err
}
entries, err := svg.Storage.List()
if err != nil {
return false, err
}
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), id) {
svg.Storage.Delete(entry.Name())
}
}
log.Println("Deleted SVG Template " + id)
return true, nil
}
+34
View File
@@ -0,0 +1,34 @@
package actions
import (
"bytes"
"log"
"strconv"
"tomatentum.net/svg-templater/pkg/format"
"tomatentum.net/svg-templater/pkg/svg"
)
func ProvideFile(r *TemplateParameters, conversion *format.ConversionParameters) ([]string, error) {
templatedPages, err := Template(r)
if err != nil {
return nil, err
}
log.Printf("Converting %s to format %s (w=%d,h=%d)", r.Id, conversion.Format, conversion.Width, conversion.Height)
filenames := make([]string, len(templatedPages))
for i, pagedata := range templatedPages {
result, err := format.ConvertByte(pagedata, *conversion)
if err != nil {
return nil, err
}
filenames[i], err = svg.Storage.CreatePublic(bytes.NewReader(result), strconv.Itoa(i+1), conversion.Format)
if err != nil {
return nil, err
}
log.Printf("Converted %s page %d to format %s (w=%d,h=%d)", r.Id, i, conversion.Format, conversion.Width, conversion.Height)
}
return filenames, nil
}
+85
View File
@@ -0,0 +1,85 @@
package actions
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"regexp"
"strconv"
"tomatentum.net/svg-templater/internal/database"
"tomatentum.net/svg-templater/pkg/svg"
)
const FILEFORMAT string = "%s-%d"
func AddPage(id string, svgbuf []byte) (svg.TemplatePage, error) {
exists, err := database.Exists(id)
if err != nil {
return svg.TemplatePage{}, err
}
if !exists {
return svg.TemplatePage{}, errors.New("Template does not exist.")
}
data := svg.TemplatePage{TemplateId: id}
populateKeys(&data, svgbuf)
page, err := database.InsertSVGPage(&data)
data.Page = page
if err != nil {
return svg.TemplatePage{}, err
}
_, err = svg.Storage.Create(fmt.Sprintf(FILEFORMAT, id, page), bytes.NewReader(svgbuf))
if err != nil {
return svg.TemplatePage{}, err
}
log.Println("Created SVG Template " + data.TemplateId + " Page " + strconv.Itoa(page))
return data, nil
}
func GetPage(id string, page int) ([]byte, error) {
file, err := svg.Storage.Get(fmt.Sprintf(FILEFORMAT, id, page))
if err != nil {
return nil, err
}
defer file.Close()
return io.ReadAll(file)
}
func DeletePage(id string, page int) (bool, error) {
if success, err := database.DeleteSVGPage(id, page); err != nil || !success {
return success, err
}
if err := svg.Storage.Delete(fmt.Sprintf(FILEFORMAT, id, page)); err != nil {
return false, err
}
log.Println("Deleted SVG Template " + id + " page " + strconv.Itoa(page))
return true, nil
}
func populateKeys(data *svg.TemplatePage, svgblob []byte) {
regex := regexp.MustCompile(svg.KeyRegex)
result := regex.FindAllSubmatch(svgblob, -1)
templateKeys := make([]string, len(result))
for i, matches := range result {
varname := matches[1] // first capture group
templateKeys[i] = string(varname)
}
data.TemplateKeys = templateKeys
log.Println("Found keys:\n", templateKeys)
}
+17
View File
@@ -0,0 +1,17 @@
package actions
import (
"log"
"tomatentum.net/svg-templater/internal/database"
)
func RenameSvg(id string, name string) error {
err := database.RenameSvg(id, name)
if err != nil {
return err
}
log.Printf("Changed template %s name to %s.\n", id, name)
return nil
}
+73
View File
@@ -0,0 +1,73 @@
package actions
import (
"errors"
"log"
"maps"
"regexp"
"slices"
"github.com/hymkor/exregexp-go"
"tomatentum.net/svg-templater/internal/database"
"tomatentum.net/svg-templater/pkg/svg"
)
type TemplateParameters struct {
Id string
Keys map[string]string
}
func Template(r *TemplateParameters) ([][]byte, error) {
data, err := database.GetSpecificSVG(r.Id)
if err != nil {
return nil, err
}
mapkeys := slices.Collect(maps.Keys(r.Keys))
ok, err := verifyTemplate(data, mapkeys)
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("Template does not exist.")
}
log.Printf("Replacing keys of %s template\n", r.Id)
pagesdata := make([][]byte, len(data.Pages))
for _, page := range data.Pages {
pagedata, err := GetPage(page.TemplateId, page.Page)
if err != nil {
return nil, err
}
replaceAll(&pagedata, r.Keys)
pagesdata[page.Page-1] = pagedata
log.Printf("Finished replacing keys of %s page %d\n", r.Id, page.Page)
}
log.Printf("Finished replacing keys of %s template\n", r.Id)
return pagesdata, nil
}
func replaceAll(svgblob *[]byte, keys map[string]string) {
regex := regexp.MustCompile(svg.KeyRegex)
*svgblob = []byte(exregexp.ReplaceAllStringSubmatchFunc(regex, string(*svgblob), func(s []string) string {
log.Printf("Replacing key %s with %s\n", s[1], keys[s[1]])
return keys[s[1]]
}))
}
func verifyTemplate(data svg.TemplateData, keys []string) (bool, error) {
for _, key := range data.AllKeys() {
if !slices.Contains(keys, key) {
return false, nil
}
}
return true, nil
}
+15 -22
View File
@@ -1,43 +1,36 @@
package actions
import (
"bytes"
"crypto/rand"
"encoding/hex"
"log"
"regexp"
"tomatentum.net/svg-templater/internal/database"
"tomatentum.net/svg-templater/pkg/svg"
)
func Create(svgbuf []byte) (svg.TemplateData, error) {
data := svg.TemplateData{Id: generateId(), TemplateKeys: nil}
populateKeys(&data, svgbuf)
_, err := svg.Storage.Create(data.Id, bytes.NewReader(svgbuf))
if err != nil {
return svg.TemplateData{}, err
}
func Create(svgbufs [][]byte, name string) (svg.TemplateData, error) {
data := svg.TemplateData{Id: generateId(), Name: name}
if err := database.InsertSVG(&data); err != nil {
return svg.TemplateData{}, err
}
return data, nil
}
pages := make([]svg.TemplatePage, len(svgbufs))
for i, pagebuf := range svgbufs {
page, err := AddPage(data.Id, pagebuf)
func populateKeys(data *svg.TemplateData, svg []byte) {
regex := regexp.MustCompile(`\{\{\s*(.*?)\s*\}\}`)
result := regex.FindAllSubmatch(svg, -1)
templateKeys := make([]string, len(result))
for i, matches := range result {
varname := matches[1] // first capture group
templateKeys[i] = string(varname)
if err != nil {
return svg.TemplateData{}, err
}
data.TemplateKeys = templateKeys
log.Println("Found keys:\n", templateKeys)
pages[i] = page
}
data.Pages = pages
log.Println("Created SVG Template " + data.Id)
return data, nil
}
func generateId() string {
+89 -18
View File
@@ -2,8 +2,10 @@ package svg
import (
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
@@ -12,19 +14,26 @@ import (
)
type SvgStorage interface {
Create(id string, svg io.Reader) (string, error)
Get(id string) (io.Reader, error)
Create(name string, svg io.Reader) (string, error)
Get(name string) (io.ReadCloser, error)
Delete(name string) error
List() ([]os.DirEntry, error)
AddFont(reader io.Reader, format string) error
GetFonts() ([]string, error)
GetFontsDir() (string, error)
GetFontsDir() string
CreatePublic(data io.Reader, suffix string, filetype string) (string, error)
GetPublic(path string) (io.ReadCloser, error)
GetPublicDir() http.Dir
}
var _ SvgStorage = FileSvgStorage{}
var TempDir string = ""
type FileSvgStorage struct {
basepath string
fontssubpath string
basepath, publicSubPath, fontssubpath string
}
func NewFileStorage(path string, fontssubpath string) *FileSvgStorage {
func NewFileStorage(path, publicSubPath, fontssubpath string) *FileSvgStorage {
err := os.MkdirAll(path, 0755)
if err != nil {
panic(err)
@@ -34,11 +43,11 @@ func NewFileStorage(path string, fontssubpath string) *FileSvgStorage {
panic(err)
}
log.Println("Initialized file storage handler")
return &FileSvgStorage{path, fontssubpath}
return &FileSvgStorage{path, publicSubPath, fontssubpath}
}
func (f FileSvgStorage) Create(id string, svg io.Reader) (string, error) {
file, err := os.Create(filepath.Join(f.basepath, id+".svg"))
func (f FileSvgStorage) Create(name string, svg io.Reader) (string, error) {
file, err := os.Create(filepath.Join(f.basepath, name+".svg"))
if err != nil {
return "", err
@@ -54,19 +63,76 @@ func (f FileSvgStorage) Create(id string, svg io.Reader) (string, error) {
return file.Name(), nil
}
func (f FileSvgStorage) Get(id string) (io.Reader, error) {
file, err := os.Open(filepath.Join(f.basepath, "svg", id+".svg"))
func (f FileSvgStorage) Get(name string) (io.ReadCloser, error) {
file, err := os.Open(filepath.Join(f.basepath, name+".svg"))
if err != nil {
return nil, err
}
return file, nil
}
func (f FileSvgStorage) AddFont(fontreader io.Reader, format string) error {
fontblob, err := io.ReadAll(fontreader)
if err != nil {
return err
func (f FileSvgStorage) Delete(name string) error {
var path string
if strings.HasSuffix(name, ".svg") {
path = filepath.Join(f.basepath, name)
} else {
path = filepath.Join(f.basepath, name+".svg")
}
defer log.Println("Deleted File: " + path)
return os.Remove(path)
}
func (f FileSvgStorage) List() ([]os.DirEntry, error) {
return os.ReadDir(f.basepath)
}
func (f FileSvgStorage) CreatePublic(data io.Reader, suffix string, filetype string) (string, error) {
path := filepath.Join(f.basepath, f.publicSubPath)
if err := os.MkdirAll(path, 0755); err != nil {
return "", err
}
file, err := os.CreateTemp(path, fmt.Sprintf("*-%s."+filetype, suffix))
if err != nil {
return "", err
}
defer file.Close()
_, err = io.Copy(file, data)
if err != nil {
return "", err
}
return filepath.Base(file.Name()), nil
}
func (f FileSvgStorage) GetPublic(path string) (io.ReadCloser, error) {
file, err := os.Open(filepath.Join(f.basepath, f.publicSubPath, path))
if err != nil {
return nil, err
}
return file, nil
}
func (f FileSvgStorage) GetPublicDir() http.Dir {
return http.Dir(filepath.Join(f.basepath, f.publicSubPath))
}
func CreateTemp(data io.Reader, filetype string) (string, error) {
file, err := os.CreateTemp(TempDir, "*."+filetype)
if err != nil {
return "", err
}
defer file.Close()
_, err = io.Copy(file, data)
if err != nil {
return "", err
}
return file.Name(), nil
}
func (f FileSvgStorage) AddFont(fontreader io.Reader, format string) error {
if format != "ttf" && format != "otf" {
return errors.New("Format not supported")
}
@@ -75,7 +141,11 @@ func (f FileSvgStorage) AddFont(fontreader io.Reader, format string) error {
return err
}
defer file.Close()
file.Write(fontblob)
log.Printf("Writing %s font to %s\n", format, file.Name())
_, err = io.Copy(file, fontreader)
if err != nil {
return err
}
return nil
}
@@ -102,11 +172,12 @@ func (f FileSvgStorage) GetFonts() ([]string, error) {
fonts[i] = fontname
}
}
log.Printf("Got fonts \n%s\n", strings.Join(fonts, "\n"))
return fonts, nil
}
func (f FileSvgStorage) GetFontsDir() (string, error) {
return filepath.Join(f.basepath, f.fontssubpath), nil
func (f FileSvgStorage) GetFontsDir() string {
return filepath.Join(f.basepath, f.fontssubpath)
}
func getFontName(svgblob []byte) (string, error) {
+25
View File
@@ -1,8 +1,33 @@
package svg
import "slices"
const KeyRegex string = `\{\{\s*(.*?)\s*\}\}`
type TemplateData struct {
Id string
Name string
Pages []TemplatePage
}
type TemplatePage struct {
TemplateId string
Page int
TemplateKeys []string
}
var Storage SvgStorage
func (d TemplateData) AllKeys() []string {
keys := make([]string, 0)
for _, page := range d.Pages {
for _, key := range page.TemplateKeys {
if !slices.Contains(keys, key) {
keys = append(keys, key)
}
}
}
return keys
}