24 Commits

Author SHA1 Message Date
tueem f58d8ef280 fix(docker): implement entrypoint for env var support
build / Go-Build (push) Successful in 1m36s
docker / docker (push) Successful in 4m58s
2026-05-29 00:40:14 +02:00
tueem da6abf0cbe fix(ci): docker only on tags and build on all
docker / docker (push) Successful in 5m3s
build / Go-Build (push) Successful in 1m39s
2026-05-28 23:42:17 +02:00
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
30 changed files with 4248 additions and 135 deletions
+4 -2
View File
@@ -3,8 +3,10 @@ name: build
on:
pull_request:
push:
branches-ignore:
- main
branches:
- '**'
tags:
- '**'
jobs:
Go-Build:
+2 -2
View File
@@ -2,8 +2,8 @@ name: docker
on:
push:
branches:
- 'main'
tags:
- '**'
jobs:
docker:
+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"]
}
]
}
+3 -1
View File
@@ -16,4 +16,6 @@ RUN apt update && apt install -y curl tar \
&& 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"]
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
+6
View File
@@ -0,0 +1,6 @@
package svgtemplater
import "embed"
//go:embed frontend/*
var Frontend embed.FS
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
CMD="svg-templater"
if [ -n "$API_KEY" ]; then
CMD="$CMD --frontendkey $API_KEY"
fi
if [ -n "$DATA_DIR" ]; then
CMD="$CMD --data $DATA_DIR"
fi
eval exec $CMD "$@"
+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
View File
@@ -14,6 +14,7 @@ var (
generateTokenFlag bool
deleteTokenFlag bool
datapath string
frontendkey string
)
func PrepareCommandLine() {
@@ -21,6 +22,7 @@ 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() {
@@ -45,6 +47,7 @@ func HandleCommandline() {
} else {
svg.Storage = svg.NewFileStorage(datapath, "public", "fonts")
server.PrepareHTTP()
server.PrepareFrontend(frontendkey)
server.Start()
}
}
+5
View File
@@ -25,6 +25,8 @@ func OpenSQLite(basepath string) 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)
}
@@ -32,5 +34,8 @@ func InitDB() {
}
func Close() error {
if database == nil {
return nil
}
return database.Close()
}
+57 -23
View File
@@ -1,28 +1,24 @@
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 name = ?;"
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
}
@@ -39,16 +35,18 @@ func GetSVG() ([]svg.TemplateData, error) {
for result.Next() {
var (
id string
keysjson []byte
keys []string
name string
)
if err := result.Scan(&id, &keysjson); err != nil {
if err := result.Scan(&id, &name); err != nil {
return nil, err
}
if err := json.Unmarshal(keysjson, &keys); err != nil {
pages, err := GetSVGPages(id)
if err != nil {
return nil, err
}
templates = append(templates, svg.TemplateData{Id: id, TemplateKeys: keys})
templates = append(templates, svg.TemplateData{Id: id, Name: name, Pages: pages})
}
if err := result.Err(); err != nil {
@@ -60,15 +58,51 @@ func GetSVG() ([]svg.TemplateData, error) {
func GetSpecificSVG(id string) (svg.TemplateData, error) {
result := database.QueryRow(GETSPECIFICSVGSQL, id)
var (
keysjson []byte
keys []string
)
if err := result.Scan(&id, &keysjson); err != nil {
var name string
if err := result.Scan(&id, &name); err != nil {
return svg.TemplateData{}, err
}
if err := json.Unmarshal(keysjson, &keys); err != nil {
pages, err := GetSVGPages(id)
if err != nil {
return svg.TemplateData{}, err
}
return svg.TemplateData{Id: id, TemplateKeys: keys}, nil
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
}
}
+16 -9
View File
@@ -5,7 +5,7 @@ import (
"log"
"net/http"
"net/url"
"path/filepath"
"path"
"strconv"
"tomatentum.net/svg-templater/pkg/format"
@@ -17,7 +17,7 @@ type downloadRequest struct {
}
type downloadResponse struct {
Url string
Urls []string
}
func DownloadSVG(w http.ResponseWriter, r *http.Request) {
@@ -73,16 +73,23 @@ func DownloadSVG(w http.ResponseWriter, r *http.Request) {
Keys: request.TemplateKeys,
}
filename, err := actions.ProvideFile(&templateParam, &convParam)
filenames, err := actions.ProvideFile(&templateParam, &convParam)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
urlparsed := getPublicUrl(r, filename)
log.Printf("Made %s available as %s\n", id, urlparsed)
response := downloadResponse{
Url: urlparsed,
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 {
@@ -92,10 +99,10 @@ func DownloadSVG(w http.ResponseWriter, r *http.Request) {
w.Write(json)
}
func getPublicUrl(r *http.Request, path string) string {
func getPublicUrl(r *http.Request, subpath string) string {
newURL := url.URL{
Host: r.Host,
Path: filepath.Join("public", path),
Path: path.Join("public", subpath),
}
newURL.Scheme = "http"
if r.TLS != nil {
+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)
})
}
+79 -11
View File
@@ -1,32 +1,62 @@
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() {
registerAuthorizedFunc("/", 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)
})
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}", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
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.DownloadSVG(w, r)
routes.DeletePage(w, r)
})
registerAuthorizedFunc("/font/", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
@@ -37,18 +67,56 @@ func PrepareHTTP() {
}
})
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(svg.Storage.GetPublicDir())))
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, handler http.Handler) {
http.HandleFunc(path, auth.AuthMiddleware(handler))
mux.HandleFunc(path, auth.AuthMiddleware(handler))
log.Println("Registered authorized handler for", path)
}
+2 -4
View File
@@ -55,10 +55,8 @@ func convertPNG(input string, param ConversionParameters) (io.ReadCloser, error)
var args []string
var outExt string
fontsdir, err := svg.Storage.GetFontsDir()
if err != nil {
return nil, err
}
fontsdir := svg.Storage.GetFontsDir()
args = append(args, "--skip-system-fonts")
args = append(args, "--use-fonts-dir", fontsdir)
+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
}
+18 -6
View File
@@ -3,20 +3,32 @@ 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) {
templatedSvgblob, err := Template(r)
func ProvideFile(r *TemplateParameters, conversion *format.ConversionParameters) ([]string, error) {
templatedPages, err := Template(r)
if err != nil {
return "", err
return nil, err
}
log.Printf("Converting %s to format %s (w=%d,h=%d)", r.Id, conversion.Format, conversion.Width, conversion.Height)
result, err := format.ConvertByte(templatedSvgblob, *conversion)
filenames := make([]string, len(templatedPages))
for i, pagedata := range templatedPages {
result, err := format.ConvertByte(pagedata, *conversion)
if err != nil {
return "", err
return nil, err
}
return svg.Storage.CreatePublic(bytes.NewReader(result), conversion.Format)
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
}
+25 -18
View File
@@ -2,7 +2,6 @@ package actions
import (
"errors"
"io"
"log"
"maps"
"regexp"
@@ -18,29 +17,42 @@ type TemplateParameters struct {
Keys map[string]string
}
func Template(r *TemplateParameters) ([]byte, error) {
mapkeys := slices.Collect(maps.Keys(r.Keys))
ok, err := verifyTemplate(r.Id, mapkeys)
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)
reader, err := svg.Storage.Get(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
}
defer reader.Close()
svgblob, err := io.ReadAll(reader)
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)
}
replaceAll(&svgblob, r.Keys)
log.Printf("Finished replacing keys of %s template\n", r.Id)
return svgblob, nil
return pagesdata, nil
}
func replaceAll(svgblob *[]byte, keys map[string]string) {
@@ -51,13 +63,8 @@ func replaceAll(svgblob *[]byte, keys map[string]string) {
}))
}
func verifyTemplate(id string, keys []string) (bool, error) {
data, err := database.GetSpecificSVG(id)
if err != nil {
return false, err
}
for _, key := range data.TemplateKeys {
func verifyTemplate(data svg.TemplateData, keys []string) (bool, error) {
for _, key := range data.AllKeys() {
if !slices.Contains(keys, key) {
return false, 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, 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)
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 {
+32 -13
View File
@@ -2,6 +2,7 @@ package svg
import (
"errors"
"fmt"
"io"
"log"
"net/http"
@@ -13,12 +14,14 @@ import (
)
type SvgStorage interface {
Create(id string, svg io.Reader) (string, error)
Get(id string) (io.ReadCloser, 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)
CreatePublic(data io.Reader, filetype string) (string, error)
GetFontsDir() string
CreatePublic(data io.Reader, suffix string, filetype string) (string, error)
GetPublic(path string) (io.ReadCloser, error)
GetPublicDir() http.Dir
}
@@ -43,8 +46,8 @@ func NewFileStorage(path, publicSubPath, fontssubpath string) *FileSvgStorage {
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
@@ -60,21 +63,37 @@ func (f FileSvgStorage) Create(id string, svg io.Reader) (string, error) {
return file.Name(), nil
}
func (f FileSvgStorage) Get(id string) (io.ReadCloser, error) {
file, err := os.Open(filepath.Join(f.basepath, 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) CreatePublic(data io.Reader, filetype string) (string, error) {
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, "*."+filetype)
file, err := os.CreateTemp(path, fmt.Sprintf("*-%s."+filetype, suffix))
if err != nil {
return "", err
}
@@ -84,7 +103,7 @@ func (f FileSvgStorage) CreatePublic(data io.Reader, filetype string) (string, e
return "", err
}
return strings.TrimPrefix(file.Name(), path), nil
return filepath.Base(file.Name()), nil
}
func (f FileSvgStorage) GetPublic(path string) (io.ReadCloser, error) {
@@ -157,8 +176,8 @@ func (f FileSvgStorage) GetFonts() ([]string, error) {
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) {
+23
View File
@@ -1,10 +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
}