chore: add docker infrastructure, gists feature, attachment system, and admin CLI tools

- Add .dockerignore, Dockerfile, and docker compose targets to Makefile for containerized deployment
- Implement gists router with CRUD operations, database schema, and polymorphic comment/vote reuse
- Create attachment upload system with thumbnail generation, MIME detection, and storage path management
- Add attachments_prune CLI command to clean orphaned attachment records and files
- Introduce rate limiting middleware with 60 requests per minute window
- Add custom 404 and 500 error handlers with SEO-optimized template responses
- Extend database initialization with gists and attachments indexes plus upload site settings defaults
- Update load_comments to include attachment mapping for comment resources
- Register gists and uploads routers in main application and update AGENTS.md documentation
This commit is contained in:
2026-05-12 13:07:34 +00:00
parent ff2585b098
commit aa88f18c03
69 changed files with 3069 additions and 450 deletions
+149 -5
View File
@@ -14,6 +14,15 @@ class Application {
this.initCommentReply();
this.initEmojiPickers();
this.initMentionInputs();
this.initConfirmations();
this.initImageFallbacks();
this.initClipboardCopy();
this.initAutoSubmitSelects();
this.initTogglers();
this.initStopPropagation();
this.initMessageThread();
this.initPlatformTags();
this.initAttachmentUploaders();
}
loadCSS(href) {
@@ -238,9 +247,9 @@ class Application {
initContentRenderer() {
document.querySelectorAll("[data-render]").forEach((el) => {
contentRenderer.applyTo(el);
window.contentRenderer.applyTo(el);
});
contentRenderer.highlightAll();
window.contentRenderer.highlightAll();
}
initCommentReply() {
@@ -271,11 +280,145 @@ class Application {
}
initMentionInputs() {
if (typeof MentionInput === "undefined") return;
if (!window.MentionInput) return;
document.querySelectorAll("[data-mention]").forEach((el) => {
if (el.dataset.mentionInitialized) return;
el.dataset.mentionInitialized = "true";
new MentionInput(el);
new window.MentionInput(el);
});
}
initConfirmations() {
document.querySelectorAll("[data-confirm]").forEach((btn) => {
btn.addEventListener("click", (e) => {
if (!confirm(btn.dataset.confirm)) {
e.preventDefault();
}
});
});
}
initImageFallbacks() {
document.querySelectorAll(".image-fallback").forEach((img) => {
img.addEventListener("error", () => {
const container = img.closest(".news-card-image, .news-detail-image") || img.parentElement;
if (container) container.style.display = "none";
});
});
}
initClipboardCopy() {
document.querySelectorAll("[data-copy]").forEach((btn) => {
btn.addEventListener("click", async () => {
const source = document.getElementById(btn.dataset.copy);
if (!source) return;
try {
await navigator.clipboard.writeText(source.textContent);
const original = btn.textContent;
btn.textContent = "Copied!";
setTimeout(() => { btn.textContent = original; }, 2000);
} catch {
// silently fail
}
});
});
}
initAutoSubmitSelects() {
document.querySelectorAll("[data-auto-submit]").forEach((select) => {
select.addEventListener("change", () => {
const form = select.closest("form");
if (form) form.submit();
});
});
}
initTogglers() {
document.querySelectorAll("[data-toggle]").forEach((btn) => {
btn.addEventListener("click", () => {
const target = document.getElementById(btn.dataset.toggle);
if (target) target.classList.toggle("hidden");
});
});
}
initStopPropagation() {
document.querySelectorAll("[data-stop-propagation]").forEach((el) => {
el.addEventListener("click", (e) => e.stopPropagation());
});
}
initMessageThread() {
const thread = document.querySelector(".messages-thread");
if (thread) thread.scrollTop = thread.scrollHeight;
}
initPlatformTags() {
const platformsInput = document.getElementById("platforms-input");
const hiddenInput = document.getElementById("platforms");
const tagsContainer = document.getElementById("platforms-tags");
if (!platformsInput || !hiddenInput || !tagsContainer) return;
const addPlatform = (val) => {
val = val.trim();
if (!val) return;
const tag = document.createElement("span");
tag.className = "platform-tag";
tag.textContent = val;
const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "x";
remove.style.marginLeft = "4px";
remove.style.fontSize = "0.75rem";
remove.style.padding = "0";
remove.style.background = "none";
remove.style.border = "none";
remove.style.color = "inherit";
remove.style.cursor = "pointer";
remove.addEventListener("click", () => {
tag.remove();
updatePlatforms();
});
tag.appendChild(remove);
tagsContainer.appendChild(tag);
platformsInput.value = "";
updatePlatforms();
};
const updatePlatforms = () => {
const values = [];
tagsContainer.querySelectorAll(".platform-tag").forEach((t) => {
values.push(t.textContent.replace("x", "").trim());
});
hiddenInput.value = values.join(",");
};
platformsInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
addPlatform(platformsInput.value);
}
});
document.querySelectorAll(".platform-preset").forEach((btn) => {
btn.addEventListener("click", () => {
addPlatform(btn.dataset.platform);
});
});
}
initAttachmentManagers() {
if (!window.AttachmentUploader) return;
document.querySelectorAll(".attachment-upload-container").forEach((container) => {
if (container.dataset.attachmentInitialized) return;
container.dataset.attachmentInitialized = "true";
const form = container.closest("form");
if (form) {
form.dataset.maxSize = container.dataset.maxSize;
form.dataset.maxFiles = container.dataset.maxFiles;
form.dataset.allowedTypes = container.dataset.allowedTypes || "";
new window.AttachmentUploader(form);
}
});
}
@@ -290,7 +433,7 @@ class Application {
btn.title = "Add emoji";
btn.innerHTML = "\u{1F600}";
const picker = new EmojiPicker(textarea);
const picker = new window.EmojiPicker(textarea);
btn.addEventListener("click", () => picker.toggle());
const parent = textarea.parentElement;
@@ -307,3 +450,4 @@ class Application {
}
const app = new Application();
window.app = app;
+7 -8
View File
@@ -68,9 +68,8 @@ class ContentRenderer {
const parts = [];
let lastIndex = 0;
const urlRe = /(https?:\/\/[^\s<]+)/g;
const mentionRe = /(?:^|[\s(])@([a-zA-Z0-9_-]+)/g;
const mentionRe = /(?:^|\s|\x28)@([a-zA-Z0-9_-]+)/g;
let match;
let mentionMatch;
while ((match = urlRe.exec(text)) !== null) {
if (match.index > lastIndex) {
@@ -93,9 +92,9 @@ class ContentRenderer {
fragment.appendChild(document.createTextNode(part.value));
} else if (part.type === "mention") {
const a = document.createElement("a");
a.href = `/profile/${part.username}`;
a.href = "/profile/" + part.username;
a.className = "mention-link";
a.textContent = `@${part.username}`;
a.textContent = "@" + part.username;
fragment.appendChild(a);
} else {
const el = this.urlToEmbed(part.value);
@@ -119,7 +118,7 @@ class ContentRenderer {
}
splitMentions(text, parts) {
const mentionRe = /(?:^|[\s(])@([a-zA-Z0-9_-]+)/g;
const mentionRe = /(?:^|\s|\x28)@([a-zA-Z0-9_-]+)/g;
let m;
let last = 0;
while ((m = mentionRe.exec(text)) !== null) {
@@ -127,10 +126,10 @@ class ContentRenderer {
parts.push({ type: "text", value: text.substring(last, m.index) });
}
const prefix = m[0][0];
if (prefix && /\S/.test(prefix)) {
if (prefix) {
parts.push({ type: "text", value: prefix });
}
parts.push({ type: "mention", username: m[1], value: m[0] });
parts.push({ type: "mention", username: m[1] });
last = m.index + m[0].length;
}
if (last < text.length) {
@@ -195,4 +194,4 @@ class ContentRenderer {
}
}
const contentRenderer = new ContentRenderer();
window.contentRenderer = new ContentRenderer();
+1
View File
@@ -58,3 +58,4 @@ class EmojiPicker {
this.wrapper.style.display = "none";
}
}
window.EmojiPicker = EmojiPicker;
+71
View File
@@ -0,0 +1,71 @@
class GistEditor {
constructor() {
this.editor = null;
this.init();
}
init() {
if (typeof CodeMirror === "undefined") return;
const textarea = document.getElementById("gist-source-editor");
if (!textarea || textarea.dataset.cminit) return;
textarea.dataset.cminit = "1";
this.editor = CodeMirror.fromTextArea(textarea, {
lineNumbers: true,
mode: textarea.dataset.language || "plaintext",
theme: "monokai",
indentUnit: 4,
tabSize: 4,
lineWrapping: true,
extraKeys: {
"Ctrl-S": () => {
const form = textarea.closest("form");
if (form) {
this.editor.save();
form.submit();
}
},
},
});
this.editor.setSize(null, 400);
const langSelect = document.getElementById("gist-language");
if (langSelect) {
langSelect.addEventListener("change", () => {
let mode = langSelect.value;
const modeMap = {
"c": "text/x-csrc",
"cpp": "text/x-c++src",
"java": "text/x-java",
"bash": "text/x-sh",
"ruby": "text/x-ruby",
"php": "text/x-php",
"perl": "text/x-perl",
"haskell": "text/x-haskell",
"lua": "text/x-lua",
"elixir": "text/x-elixir",
"dart": "text/x-dart",
"r": "text/x-rsrc",
"scala": "text/x-scala",
};
this.editor.setOption("mode", modeMap[mode] || mode);
});
}
const form = textarea.closest("form");
if (form) {
form.addEventListener("submit", () => {
this.editor.save();
});
}
}
refresh() {
if (this.editor) {
setTimeout(() => this.editor.refresh(), 100);
}
}
}
window.GistEditor = GistEditor;
+133
View File
@@ -0,0 +1,133 @@
class MentionInput {
constructor(element) {
this.input = element;
this.dropdown = null;
this.debounceTimer = null;
this.selectedIndex = -1;
this.lastMatch = null;
this.build();
}
build() {
const wrap = document.createElement("div");
wrap.className = "mention-wrapper";
this.input.parentNode.insertBefore(wrap, this.input);
wrap.appendChild(this.input);
this.dropdown = document.createElement("div");
this.dropdown.className = "mention-dropdown";
wrap.appendChild(this.dropdown);
this.input.addEventListener("input", () => this.onInput());
this.input.addEventListener("keydown", (e) => this.onKeydown(e));
this.input.addEventListener("blur", () => {
setTimeout(() => { this.dropdown.style.display = "none"; }, 200);
});
}
onInput() {
clearTimeout(this.debounceTimer);
const pos = this.input.selectionStart;
const text = this.input.value.substring(0, pos);
let match = text.match(/(?:^|\s|\x28)@([a-zA-Z0-9_-]*)$/);
if (!match) {
this.dropdown.style.display = "none";
this.lastMatch = null;
return;
}
const query = match[1];
this.lastMatch = { query, index: match.index + (text[match.index] === "@" ? 0 : 1) };
if (query.length < 1) {
this.dropdown.style.display = "none";
return;
}
this.debounceTimer = setTimeout(() => this.fetch(query), 200);
}
async fetch(query) {
try {
const resp = await fetch("/profile/search?q=" + encodeURIComponent(query));
const data = await resp.json();
const results = data.results || [];
if (results.length === 0) {
this.dropdown.style.display = "none";
return;
}
this.render(results);
} catch (e) {
this.dropdown.style.display = "none";
}
}
render(results) {
this.dropdown.innerHTML = "";
this.selectedIndex = -1;
for (const r of results) {
const item = document.createElement("button");
item.type = "button";
item.className = "mention-dropdown-item";
item.dataset.username = r.username;
item.innerHTML = '<img src="/avatar/multiavatar/' + encodeURIComponent(r.username) + '?size=24" class="avatar-img" style="width:24px;height:24px;border-radius:50%" alt="" loading="lazy"><span>@' + r.username + '</span>';
item.addEventListener("mousedown", (e) => {
e.preventDefault();
this.insert(r.username);
});
this.dropdown.appendChild(item);
}
this.dropdown.style.display = "block";
}
onKeydown(e) {
const items = this.dropdown.querySelectorAll(".mention-dropdown-item");
if (this.dropdown.style.display !== "block" || items.length === 0) {
return;
}
if (e.key === "ArrowDown") {
e.preventDefault();
this.selectedIndex = Math.min(this.selectedIndex + 1, items.length - 1);
this.highlight(items);
} else if (e.key === "ArrowUp") {
e.preventDefault();
this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
this.highlight(items);
} else if (e.key === "Enter" || e.key === "Tab") {
if (this.selectedIndex >= 0 && items[this.selectedIndex]) {
e.preventDefault();
this.insert(items[this.selectedIndex].dataset.username);
}
} else if (e.key === "Escape") {
this.dropdown.style.display = "none";
}
}
highlight(items) {
items.forEach((item, i) => {
item.classList.toggle("active", i === this.selectedIndex);
});
if (this.selectedIndex >= 0 && items[this.selectedIndex]) {
items[this.selectedIndex].scrollIntoView({ block: "nearest" });
}
}
insert(username) {
if (!this.lastMatch) return;
const val = this.input.value;
let before = val.substring(0, this.lastMatch.index);
let after = val.substring(this.lastMatch.index + this.lastMatch.query.length + 1);
before = before.replace(/@+$/, "");
after = after.replace(/^@+/, "");
this.input.value = before + "@" + username + " " + after;
const newPos = before.length + username.length + 2;
this.input.setSelectionRange(newPos, newPos);
this.input.focus();
this.input.dispatchEvent(new Event("input", { bubbles: true }));
this.dropdown.style.display = "none";
this.lastMatch = null;
}
}
window.MentionInput = MentionInput;
+60
View File
@@ -0,0 +1,60 @@
class ServiceMonitor {
constructor() {
this.pollInterval = 5000;
}
start() {
this.pollServices();
setInterval(() => this.pollServices(), this.pollInterval);
}
formatDate(isoStr, includeTime) {
if (!isoStr) return "-";
try {
const d = new Date(isoStr);
if (isNaN(d.getTime())) return isoStr.slice(0, 19);
const dd = String(d.getDate()).padStart(2, "0");
const mm = String(d.getMonth() + 1).padStart(2, "0");
const yyyy = d.getFullYear();
if (includeTime) {
const hh = String(d.getHours()).padStart(2, "0");
const mi = String(d.getMinutes()).padStart(2, "0");
return `${dd}/${mm}/${yyyy} ${hh}:${mi}`;
}
return `${dd}/${mm}/${yyyy}`;
} catch {
return isoStr.slice(0, 19);
}
}
async pollServices() {
try {
const resp = await fetch("/admin/services/data");
const data = await resp.json();
const container = document.getElementById("services-list");
if (!container) return;
for (const svc of data.services) {
const card = container.querySelector(`.service-card[data-service="${svc.name}"]`);
if (!card) continue;
const statusEl = card.querySelector(".service-status");
if (statusEl) {
statusEl.textContent = svc.status;
statusEl.className = "service-status " + svc.status;
}
const metaItems = card.querySelectorAll(".meta-item");
if (metaItems.length >= 3) {
metaItems[0].textContent = "Uptime: " + (svc.uptime || "-");
metaItems[1].textContent = "Last run: " + this.formatDate(svc.last_run, true);
metaItems[2].textContent = "Next run: " + this.formatDate(svc.next_run, true);
}
const logPre = card.querySelector(".log-output");
if (logPre) {
logPre.textContent = (svc.log_buffer || []).map((l) => l + "\n").join("") || "No log entries yet.\n";
}
}
} catch {
// silently ignore poll errors
}
}
}
window.ServiceMonitor = ServiceMonitor;