Ability to bulk import or export articles as gzip, handle domain prefix logic in API and other smaller improvements

This commit is contained in:
thiloho
2024-10-30 21:33:44 +01:00
parent f7180ebd92
commit 037165947b
32 changed files with 409 additions and 223 deletions

View File

@@ -99,6 +99,14 @@
};
};
systemd.services.postgresql = {
path = with pkgs; [
# Tar and gzip are needed for tar.gz exports
gnutar
gzip
];
};
services.getty.autologinUser = "dev";
system.stateVersion = "24.05";

View File

@@ -169,6 +169,14 @@ in
extraPlugins = with pkgs.postgresql16Packages; [ pgjwt ];
};
systemd.services.postgresql = {
path = with pkgs; [
# Tar and gzip are needed for tar.gz exports
gnutar
gzip
];
};
services.nginx = {
enable = true;
recommendedProxySettings = true;

View File

@@ -1,4 +1,6 @@
-- migrate:up
CREATE EXTENSION unaccent;
CREATE SCHEMA internal;
CREATE SCHEMA api;
@@ -27,6 +29,17 @@ GRANT USAGE ON SCHEMA internal TO authenticated_user;
ALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;
CREATE FUNCTION internal.immutable_unaccent (TEXT)
RETURNS TEXT
AS $$
SELECT
unaccent ($1);
$$
LANGUAGE sql
IMMUTABLE;
GRANT EXECUTE ON FUNCTION internal.immutable_unaccent TO authenticated_user;
CREATE TABLE internal.user (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
username VARCHAR(16) UNIQUE NOT NULL CHECK (LENGTH(username) >= 3 AND username ~ '^[a-zA-Z0-9_-]+$'),
@@ -91,7 +104,7 @@ CREATE TABLE internal.docs_category (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
website_id UUID REFERENCES internal.website (id) ON DELETE CASCADE NOT NULL,
user_id UUID REFERENCES internal.user (id) ON DELETE SET NULL DEFAULT (CURRENT_SETTING('request.jwt.claims', TRUE)::JSON ->> 'user_id') ::UUID,
category_name VARCHAR(50) NOT NULL CHECK (TRIM(category_name) != ''),
category_name VARCHAR(50) NOT NULL CHECK (TRIM(category_name) != '' AND category_name != 'Uncategorized'),
category_weight INT CHECK (category_weight >= 0) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CLOCK_TIMESTAMP(),
last_modified_at TIMESTAMPTZ NOT NULL DEFAULT CLOCK_TIMESTAMP(),
@@ -105,6 +118,7 @@ CREATE TABLE internal.article (
website_id UUID REFERENCES internal.website (id) ON DELETE CASCADE NOT NULL,
user_id UUID REFERENCES internal.user (id) ON DELETE SET NULL DEFAULT (CURRENT_SETTING('request.jwt.claims', TRUE)::JSON ->> 'user_id') ::UUID,
title VARCHAR(100) NOT NULL CHECK (TRIM(title) != ''),
slug VARCHAR(100) GENERATED ALWAYS AS (REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(LOWER(TRIM(REGEXP_REPLACE(internal.immutable_unaccent (title), '\s+', '-', 'g'))), '[^\w-]', '', 'g'), '-+', '-', 'g'), '^-+', '', 'g'), '-+$', '', 'g')) STORED,
meta_description VARCHAR(250) CHECK (TRIM(meta_description) != ''),
meta_author VARCHAR(100) CHECK (TRIM(meta_author) != ''),
cover_image UUID REFERENCES internal.media (id) ON DELETE SET NULL,
@@ -115,6 +129,7 @@ CREATE TABLE internal.article (
created_at TIMESTAMPTZ NOT NULL DEFAULT CLOCK_TIMESTAMP(),
last_modified_at TIMESTAMPTZ NOT NULL DEFAULT CLOCK_TIMESTAMP(),
last_modified_by UUID REFERENCES internal.user (id) ON DELETE SET NULL,
UNIQUE (website_id, slug),
UNIQUE (website_id, category, article_weight)
);
@@ -168,6 +183,8 @@ DROP TABLE internal.user;
DROP SCHEMA api;
DROP FUNCTION internal.immutable_unaccent;
DROP SCHEMA internal;
DROP ROLE anon;
@@ -180,3 +197,5 @@ DROP ROLE authenticator;
ALTER DEFAULT PRIVILEGES GRANT EXECUTE ON FUNCTIONS TO PUBLIC;
DROP EXTENSION unaccent;

View File

@@ -1,5 +1,5 @@
-- migrate:up
CREATE DOMAIN "*/*" AS bytea;
CREATE DOMAIN "*/*" AS BYTEA;
CREATE FUNCTION api.upload_file (BYTEA, OUT file_id UUID)
AS $$

View File

@@ -1,7 +1,7 @@
-- migrate:up
CREATE TABLE internal.domain_prefix (
website_id UUID PRIMARY KEY REFERENCES internal.website (id) ON DELETE CASCADE,
prefix VARCHAR(16) UNIQUE NOT NULL CHECK (LENGTH(prefix) >= 3 AND prefix ~ '^[a-z]+(-[a-z]+)*$'),
prefix VARCHAR(16) UNIQUE NOT NULL CHECK (LENGTH(prefix) >= 3 AND prefix ~ '^[a-z]+(-[a-z]+)*$' AND prefix != 'previews'),
created_at TIMESTAMPTZ NOT NULL DEFAULT CLOCK_TIMESTAMP(),
last_modified_at TIMESTAMPTZ NOT NULL DEFAULT CLOCK_TIMESTAMP(),
last_modified_by UUID REFERENCES internal.user (id) ON DELETE SET NULL
@@ -14,9 +14,9 @@ SELECT
FROM
internal.domain_prefix;
GRANT SELECT, INSERT (website_id, prefix), UPDATE (website_id, prefix), DELETE ON internal.domain_prefix TO authenticated_user;
GRANT SELECT ON internal.domain_prefix TO authenticated_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON api.domain_prefix TO authenticated_user;
GRANT SELECT ON api.domain_prefix TO authenticated_user;
ALTER TABLE internal.domain_prefix ENABLE ROW LEVEL SECURITY;
@@ -24,17 +24,64 @@ CREATE POLICY view_domain_prefix ON internal.domain_prefix
FOR SELECT
USING (internal.user_has_website_access (website_id, 10));
CREATE POLICY update_domain_prefix ON internal.domain_prefix
FOR UPDATE
USING (internal.user_has_website_access (website_id, 30));
CREATE FUNCTION api.set_domain_prefix (website_id UUID, prefix VARCHAR(16), OUT was_set BOOLEAN)
AS $$
DECLARE
_has_access BOOLEAN;
_old_domain_prefix VARCHAR(16);
_base_path CONSTANT TEXT := '/var/www/archtika-websites/';
_old_path TEXT;
_new_path TEXT;
BEGIN
_has_access = internal.user_has_website_access (set_domain_prefix.website_id, 30);
SELECT
d.prefix INTO _old_domain_prefix
FROM
internal.domain_prefix AS d
WHERE
d.website_id = set_domain_prefix.website_id;
INSERT INTO internal.domain_prefix (website_id, prefix)
VALUES (set_domain_prefix.website_id, set_domain_prefix.prefix)
ON CONFLICT ON CONSTRAINT domain_prefix_pkey
DO UPDATE SET
prefix = EXCLUDED.prefix;
_old_path = _base_path || COALESCE(_old_domain_prefix, set_domain_prefix.website_id::TEXT);
_new_path = _base_path || set_domain_prefix.prefix;
IF _old_path != _new_path THEN
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''mv -T %s %s''', _old_path, _new_path);
END IF;
was_set := TRUE;
END;
$$
LANGUAGE plpgsql
SECURITY DEFINER;
CREATE POLICY delete_domain_prefix ON internal.domain_prefix
FOR DELETE
USING (internal.user_has_website_access (website_id, 30));
GRANT EXECUTE ON FUNCTION api.set_domain_prefix TO authenticated_user;
CREATE POLICY insert_domain_prefix ON internal.domain_prefix
FOR INSERT
WITH CHECK (internal.user_has_website_access (website_id, 30));
CREATE FUNCTION api.delete_domain_prefix (website_id UUID, OUT was_deleted BOOLEAN)
AS $$
DECLARE
_has_access BOOLEAN;
_old_domain_prefix VARCHAR(16);
_base_path CONSTANT TEXT := '/var/www/archtika-websites/';
_old_path TEXT;
_new_path TEXT;
BEGIN
_has_access = internal.user_has_website_access (delete_domain_prefix.website_id, 30);
DELETE FROM internal.domain_prefix AS d
WHERE d.website_id = delete_domain_prefix.website_id
RETURNING
prefix INTO _old_domain_prefix;
_old_path = _base_path || _old_domain_prefix;
_new_path = _base_path || delete_domain_prefix.website_id;
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''mv -T %s %s''', _old_path, _new_path);
was_deleted := TRUE;
END;
$$
LANGUAGE plpgsql
SECURITY DEFINER;
GRANT EXECUTE ON FUNCTION api.delete_domain_prefix TO authenticated_user;
CREATE TRIGGER update_domain_prefix_last_modified
BEFORE INSERT OR UPDATE OR DELETE ON internal.domain_prefix
@@ -51,6 +98,10 @@ DROP TRIGGER track_changes_domain_prefix ON internal.domain_prefix;
DROP TRIGGER update_domain_prefix_last_modified ON internal.domain_prefix;
DROP FUNCTION api.set_domain_prefix;
DROP FUNCTION api.delete_domain_prefix;
DROP VIEW api.domain_prefix;
DROP TABLE internal.domain_prefix;

View File

@@ -42,9 +42,7 @@ BEGIN
w.user_id = $1
GROUP BY
w.id,
w.title
ORDER BY
storage_size_bytes DESC', _union_queries);
w.title', _union_queries);
RETURN QUERY EXECUTE _query
USING _user_id;
END;

View File

@@ -8,6 +8,7 @@ DECLARE
_base_path CONSTANT TEXT := '/var/www/archtika-websites/';
_preview_path TEXT;
_prod_path TEXT;
_article_slug TEXT;
BEGIN
IF TG_TABLE_NAME = 'website' THEN
_website_id := OLD.id;
@@ -17,7 +18,7 @@ BEGIN
SELECT
d.prefix INTO _domain_prefix
FROM
internal.domain_prefix d
internal.domain_prefix AS d
WHERE
d.website_id = _website_id;
_preview_path := _base_path || 'previews/' || _website_id;
@@ -25,11 +26,20 @@ BEGIN
IF TG_TABLE_NAME = 'website' THEN
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''rm -rf %s''', _preview_path);
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''rm -rf %s''', _prod_path);
ELSE
ELSIF TG_TABLE_NAME = 'article' THEN
SELECT
a.slug INTO _article_slug
FROM
internal.article AS a
WHERE
a.id = OLD.id;
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''rm -f %s/articles/%s.html''', _preview_path, _article_slug);
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''rm -f %s/articles/%s.html''', _prod_path, _article_slug);
ELSIF TG_TABLE_NAME = 'legal_information' THEN
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''rm -f %s/legal-information.html''', _preview_path);
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''rm -f %s/legal-information.html''', _prod_path);
END IF;
RETURN OLD;
RETURN COALESCE(NEW, OLD);
END;
$$
LANGUAGE plpgsql
@@ -40,6 +50,11 @@ CREATE TRIGGER _cleanup_filesystem_website
FOR EACH ROW
EXECUTE FUNCTION internal.cleanup_filesystem ();
CREATE TRIGGER _cleanup_filesystem_article
BEFORE UPDATE OR DELETE ON internal.article
FOR EACH ROW
EXECUTE FUNCTION internal.cleanup_filesystem ();
CREATE TRIGGER _cleanup_filesystem_legal_information
BEFORE DELETE ON internal.legal_information
FOR EACH ROW
@@ -48,6 +63,8 @@ CREATE TRIGGER _cleanup_filesystem_legal_information
-- migrate:down
DROP TRIGGER _cleanup_filesystem_website ON internal.website;
DROP TRIGGER _cleanup_filesystem_article ON internal.article;
DROP TRIGGER _cleanup_filesystem_legal_information ON internal.legal_information;
DROP FUNCTION internal.cleanup_filesystem;

View File

@@ -0,0 +1,49 @@
-- migrate:up
CREATE FUNCTION api.export_articles_zip (website_id UUID)
RETURNS "*/*"
AS $$
DECLARE
_has_access BOOLEAN;
_headers TEXT;
_article RECORD;
_markdown_dir TEXT := '/tmp/website-' || export_articles_zip.website_id;
BEGIN
_has_access = internal.user_has_website_access (export_articles_zip.website_id, 20);
SELECT
FORMAT('[{ "Content-Type": "application/gzip" },'
'{ "Content-Disposition": "attachment; filename=\"%s\"" }]',
'archtika-export-articles-' || export_articles_zip.website_id || '.tar.gz') INTO _headers;
PERFORM
SET_CONFIG('response.headers', _headers, TRUE);
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''mkdir -p %s''', _markdown_dir || '/articles');
FOR _article IN (
SELECT a.id, a.website_id, a.slug, a.main_content
FROM internal.article AS a
WHERE a.website_id = export_articles_zip.website_id)
LOOP
EXECUTE FORMAT(
'COPY (SELECT %L) TO ''%s''',
_article.main_content,
_markdown_dir || '/articles/' || _article.slug || '.md'
);
END LOOP;
EXECUTE FORMAT('COPY (SELECT '''') TO PROGRAM ''tar -czf %s -C %s articles && rm %s''',
_markdown_dir || '/export.tar.gz',
_markdown_dir,
_markdown_dir || '/articles/*.md'
);
RETURN pg_read_binary_file(_markdown_dir || '/export.tar.gz');
END;
$$
LANGUAGE plpgsql
SECURITY DEFINER;
GRANT EXECUTE ON FUNCTION api.export_articles_zip TO authenticated_user;
-- migrate:down
DROP FUNCTION api.export_articles_zip;

View File

@@ -11,7 +11,7 @@
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --check . && eslint .",
"format": "prettier --write .",
"gents": "pg-to-ts generate -c postgres://postgres@localhost:15432/archtika -o src/lib/db-schema.ts -s internal"
"gents": "pg-to-ts generate -c postgres://postgres@localhost:15432/archtika -o src/lib/db-schema.ts -s internal --datesAsStrings"
},
"devDependencies": {
"@playwright/test": "1.47.0",

View File

@@ -1,16 +1,30 @@
<script lang="ts">
const { date }: { date: Date } = $props();
const { date }: { date: string } = $props();
const options: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
const dateObject = new Date(date);
const calcTimeAgo = (date: Date) => {
const formatter = new Intl.RelativeTimeFormat("en");
const ranges = [
["years", 60 * 60 * 24 * 365],
["months", 60 * 60 * 24 * 30],
["weeks", 60 * 60 * 24 * 7],
["days", 60 * 60 * 24],
["hours", 60 * 60],
["minutes", 60],
["seconds", 1]
] as const;
const secondsElapsed = (date.getTime() - Date.now()) / 1000;
for (const [rangeType, rangeVal] of ranges) {
if (rangeVal < Math.abs(secondsElapsed)) {
const delta = secondsElapsed / rangeVal;
return formatter.format(Math.round(delta), rangeType);
}
}
};
</script>
<time datetime={new Date(date).toLocaleString("sv").replace(" ", "T")}>
{new Date(date).toLocaleString("en-us", { ...options })}
<time datetime={dateObject.toLocaleString("sv").replace(" ", "T")}>
{calcTimeAgo(dateObject)}
</time>

View File

@@ -9,6 +9,14 @@
}: { children: Snippet; id: string; text: string; isWider?: boolean } = $props();
const modalId = `${id}-modal`;
$effect(() => {
window.addEventListener("keydown", (e) => {
if (e.key === "Escape" && window.location.hash === `#${modalId}`) {
window.location.hash = "!";
}
});
});
</script>
<a href={`#${modalId}`} role="button">{text}</a>

View File

@@ -17,15 +17,16 @@ export interface Article {
website_id: string;
user_id: string | null;
title: string;
slug: string | null;
meta_description: string | null;
meta_author: string | null;
cover_image: string | null;
publication_date: Date | null;
publication_date: string | null;
main_content: string | null;
category: string | null;
article_weight: number | null;
created_at: Date;
last_modified_at: Date;
created_at: string;
last_modified_at: string;
last_modified_by: string | null;
}
export interface ArticleInput {
@@ -33,15 +34,16 @@ export interface ArticleInput {
website_id: string;
user_id?: string | null;
title: string;
slug?: string | null;
meta_description?: string | null;
meta_author?: string | null;
cover_image?: string | null;
publication_date?: Date | null;
publication_date?: string | null;
main_content?: string | null;
category?: string | null;
article_weight?: number | null;
created_at?: Date;
last_modified_at?: Date;
created_at?: string;
last_modified_at?: string;
last_modified_by?: string | null;
}
const article = {
@@ -51,6 +53,7 @@ const article = {
"website_id",
"user_id",
"title",
"slug",
"meta_description",
"meta_author",
"cover_image",
@@ -81,7 +84,7 @@ export interface ChangeLog {
website_id: string | null;
user_id: string | null;
username: string;
tstamp: Date;
tstamp: string;
table_name: string;
operation: string;
old_value: any | null;
@@ -92,7 +95,7 @@ export interface ChangeLogInput {
website_id?: string | null;
user_id?: string | null;
username?: string;
tstamp?: Date;
tstamp?: string;
table_name: string;
operation: string;
old_value?: any | null;
@@ -126,16 +129,16 @@ export interface Collab {
website_id: string;
user_id: string;
permission_level: number;
added_at: Date;
last_modified_at: Date;
added_at: string;
last_modified_at: string;
last_modified_by: string | null;
}
export interface CollabInput {
website_id: string;
user_id: string;
permission_level?: number;
added_at?: Date;
last_modified_at?: Date;
added_at?: string;
last_modified_at?: string;
last_modified_by?: string | null;
}
const collab = {
@@ -166,8 +169,8 @@ export interface DocsCategory {
user_id: string | null;
category_name: string;
category_weight: number;
created_at: Date;
last_modified_at: Date;
created_at: string;
last_modified_at: string;
last_modified_by: string | null;
}
export interface DocsCategoryInput {
@@ -176,8 +179,8 @@ export interface DocsCategoryInput {
user_id?: string | null;
category_name: string;
category_weight: number;
created_at?: Date;
last_modified_at?: Date;
created_at?: string;
last_modified_at?: string;
last_modified_by?: string | null;
}
const docs_category = {
@@ -207,15 +210,15 @@ const docs_category = {
export interface DomainPrefix {
website_id: string;
prefix: string;
created_at: Date;
last_modified_at: Date;
created_at: string;
last_modified_at: string;
last_modified_by: string | null;
}
export interface DomainPrefixInput {
website_id: string;
prefix: string;
created_at?: Date;
last_modified_at?: Date;
created_at?: string;
last_modified_at?: string;
last_modified_by?: string | null;
}
const domain_prefix = {
@@ -235,13 +238,13 @@ const domain_prefix = {
export interface Footer {
website_id: string;
additional_text: string;
last_modified_at: Date;
last_modified_at: string;
last_modified_by: string | null;
}
export interface FooterInput {
website_id: string;
additional_text: string;
last_modified_at?: Date;
last_modified_at?: string;
last_modified_by?: string | null;
}
const footer = {
@@ -263,7 +266,7 @@ export interface Header {
logo_type: string;
logo_text: string | null;
logo_image: string | null;
last_modified_at: Date;
last_modified_at: string;
last_modified_by: string | null;
}
export interface HeaderInput {
@@ -271,7 +274,7 @@ export interface HeaderInput {
logo_type?: string;
logo_text?: string | null;
logo_image?: string | null;
last_modified_at?: Date;
last_modified_at?: string;
last_modified_by?: string | null;
}
const header = {
@@ -300,14 +303,14 @@ export interface Home {
website_id: string;
main_content: string;
meta_description: string | null;
last_modified_at: Date;
last_modified_at: string;
last_modified_by: string | null;
}
export interface HomeInput {
website_id: string;
main_content: string;
meta_description?: string | null;
last_modified_at?: Date;
last_modified_at?: string;
last_modified_by?: string | null;
}
const home = {
@@ -333,15 +336,15 @@ const home = {
export interface LegalInformation {
website_id: string;
main_content: string;
created_at: Date;
last_modified_at: Date;
created_at: string;
last_modified_at: string;
last_modified_by: string | null;
}
export interface LegalInformationInput {
website_id: string;
main_content: string;
created_at?: Date;
last_modified_at?: Date;
created_at?: string;
last_modified_at?: string;
last_modified_by?: string | null;
}
const legal_information = {
@@ -365,7 +368,7 @@ export interface Media {
blob: string;
mimetype: string;
original_name: string;
created_at: Date;
created_at: string;
}
export interface MediaInput {
id?: string;
@@ -374,7 +377,7 @@ export interface MediaInput {
blob: string;
mimetype: string;
original_name: string;
created_at?: Date;
created_at?: string;
}
const media = {
tableName: "media",
@@ -397,7 +400,7 @@ export interface Settings {
background_color_dark_theme: string;
background_color_light_theme: string;
favicon_image: string | null;
last_modified_at: Date;
last_modified_at: string;
last_modified_by: string | null;
}
export interface SettingsInput {
@@ -407,7 +410,7 @@ export interface SettingsInput {
background_color_dark_theme?: string;
background_color_light_theme?: string;
favicon_image?: string | null;
last_modified_at?: Date;
last_modified_at?: string;
last_modified_by?: string | null;
}
const settings = {
@@ -440,7 +443,7 @@ export interface User {
password_hash: string;
user_role: string;
max_number_websites: number;
created_at: Date;
created_at: string;
}
export interface UserInput {
id?: string;
@@ -448,7 +451,7 @@ export interface UserInput {
password_hash: string;
user_role?: string;
max_number_websites?: number;
created_at?: Date;
created_at?: string;
}
const user = {
tableName: "user",
@@ -468,8 +471,8 @@ export interface Website {
title: string;
max_storage_size: number;
is_published: boolean;
created_at: Date;
last_modified_at: Date;
created_at: string;
last_modified_at: string;
last_modified_by: string | null;
}
export interface WebsiteInput {
@@ -479,8 +482,8 @@ export interface WebsiteInput {
title: string;
max_storage_size?: number;
is_published?: boolean;
created_at?: Date;
last_modified_at?: Date;
created_at?: string;
last_modified_at?: string;
last_modified_by?: string | null;
}
const website = {

View File

@@ -19,6 +19,7 @@
nestingLevel={1}
{apiUrl}
title={article.title}
slug={article.slug as string}
metaDescription={article.meta_description}
{websiteUrl}
/>

View File

@@ -2,7 +2,7 @@
import Head from "../common/Head.svelte";
import Nav from "../common/Nav.svelte";
import Footer from "../common/Footer.svelte";
import { md, slugify, type WebsiteOverview } from "$lib/utils";
import { md, type WebsiteOverview } from "$lib/utils";
const {
websiteOverview,
@@ -62,7 +62,7 @@
{/if}
<p>
<strong>
<a href="./articles/{slugify(article.title)}">{article.title}</a>
<a href="./articles/{article.slug}">{article.title}</a>
</strong>
</p>
{#if article.meta_description}

View File

@@ -1,11 +1,12 @@
<script lang="ts">
import { slugify, type WebsiteOverview } from "../../utils";
import { type WebsiteOverview } from "../../utils";
const {
websiteOverview,
nestingLevel,
apiUrl,
title,
slug,
metaDescription,
websiteUrl
}: {
@@ -13,6 +14,7 @@
nestingLevel: number;
apiUrl: string;
title: string;
slug?: string;
metaDescription?: string | null;
websiteUrl: string;
} = $props();
@@ -20,7 +22,7 @@
const constructedTitle =
websiteOverview.title === title ? title : `${websiteOverview.title} | ${title}`;
let ogUrl = `${websiteUrl.replace(/\/$/, "")}${nestingLevel === 0 ? (websiteOverview.title === title ? "" : `/${slugify(title)}`) : `/articles/${slugify(title)}`}`;
let ogUrl = `${websiteUrl.replace(/\/$/, "")}${nestingLevel === 0 ? (websiteOverview.title === title ? "" : `/${slug}`) : `/articles/${slug}`}`;
</script>
<svelte:head>

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import { type WebsiteOverview, slugify } from "../../utils";
import { type WebsiteOverview } from "../../utils";
import type { Article } from "../../db-schema";
const {
@@ -61,9 +61,9 @@
<li>
<strong>{key}</strong>
<ul>
{#each categorizedArticles[key] as { title }}
{#each categorizedArticles[key] as { title, slug }}
<li>
<a href="{isIndexPage ? './articles' : '.'}/{slugify(title)}">{title}</a>
<a href="{isIndexPage ? './articles' : '.'}/{slug}">{title}</a>
</li>
{/each}
</ul>
@@ -87,7 +87,7 @@
/>
{/if}
</svelte:element>
<label style="margin-inline-start: auto;" for="toggle-theme">
<label for="toggle-theme">
<input type="checkbox" id="toggle-theme" hidden />
<svg
xmlns="http://www.w3.org/2000/svg"

View File

@@ -19,6 +19,7 @@
nestingLevel={1}
{apiUrl}
title={article.title}
slug={article.slug as string}
metaDescription={article.meta_description}
{websiteUrl}
/>

View File

@@ -26,7 +26,7 @@ export const ALLOWED_MIME_TYPES = [
"image/svg+xml"
];
export const slugify = (string: string) => {
const slugify = (string: string) => {
return string
.toString()
.normalize("NFKD") // Normalize Unicode characters

View File

@@ -76,19 +76,8 @@ export const actions: Actions = {
const data = await request.formData();
const id = data.get("id");
const deleteWebsite = await apiRequest(
fetch,
`${API_BASE_PREFIX}/website?id=eq.${id}`,
"DELETE",
{
return await apiRequest(fetch, `${API_BASE_PREFIX}/website?id=eq.${id}`, "DELETE", {
successMessage: "Successfully deleted website"
}
);
if (!deleteWebsite.success) {
return deleteWebsite;
}
return deleteWebsite;
});
}
};

View File

@@ -77,7 +77,7 @@
</details>
<ul class="website-grid unpadded">
{#each data.websites as { id, user_id, content_type, title, created_at, collab } (id)}
{#each data.websites as { id, user_id, content_type, title, created_at, last_modified_at, collab } (id)}
<li class="website-card">
<p>
<strong>
@@ -90,9 +90,13 @@
{content_type}
</li>
<li>
<strong>Created at:</strong>
<strong>Created:</strong>
<DateTime date={created_at} />
</li>
<li>
<strong>Last modified:</strong>
<DateTime date={last_modified_at} />
</li>
</ul>
<div class="website-card__actions">
<Modal id="update-website-{id}" text="Update">

View File

@@ -4,7 +4,7 @@ import { API_BASE_PREFIX, apiRequest } from "$lib/server/utils";
export const load: PageServerLoad = async ({ fetch, locals }) => {
const storageSizes = await apiRequest(
fetch,
`${API_BASE_PREFIX}/rpc/user_websites_storage_size`,
`${API_BASE_PREFIX}/rpc/user_websites_storage_size?order=max_storage_bytes.desc`,
"GET",
{
returnData: true

View File

@@ -10,7 +10,7 @@ export const load: PageServerLoad = async ({ fetch, url }) => {
const usersWithWebsites: (User & { website: Website[] })[] = (
await apiRequest(
fetch,
`${API_BASE_PREFIX}/user?select=*,website!user_id(*)&order=created_at&limit=${PAGINATION_MAX_ITEMS}&offset=${resultOffset}`,
`${API_BASE_PREFIX}/user?select=*,website!user_id(*)&order=created_at&website.order=created_at.desc&limit=${PAGINATION_MAX_ITEMS}&offset=${resultOffset}`,
"GET",
{
returnData: true
@@ -61,7 +61,7 @@ export const actions: Actions = {
body: {
max_storage_size: data.get("storage-size")
},
successMessage: "Successfully updated user website storage size"
successMessage: "Successfully updated website storage"
}
);
},

View File

@@ -1,6 +1,7 @@
import type { Actions, PageServerLoad } from "./$types";
import { API_BASE_PREFIX } from "$lib/server/utils";
import { apiRequest } from "$lib/server/utils";
import { parse } from "node:path";
import type { Article, DocsCategory } from "$lib/db-schema";
export const load: PageServerLoad = async ({ params, fetch, url, parent, locals }) => {
@@ -58,6 +59,7 @@ export const load: PageServerLoad = async ({ params, fetch, url, parent, locals
website,
home,
permissionLevel,
API_BASE_PREFIX,
user: locals.user
};
};
@@ -74,6 +76,25 @@ export const actions: Actions = {
successMessage: "Successfully created article"
});
},
importArticles: async ({ request, fetch, params }) => {
const data = await request.formData();
const files = data.getAll("import-articles") as File[];
const articles = await Promise.all(
files.map(async (file) => {
return {
website_id: params.websiteId,
title: parse(file.name).name,
main_content: await file.text()
};
})
);
return await apiRequest(fetch, `${API_BASE_PREFIX}/article`, "POST", {
body: articles,
successMessage: "Successfully imported articles"
});
},
deleteArticle: async ({ request, fetch }) => {
const data = await request.formData();

View File

@@ -31,18 +31,37 @@
<a href="#create-article">Create article</a>
</h2>
<div class="multi-wrapper">
<Modal id="create-article" text="Create article">
<h3>Create article</h3>
<form method="POST" action="?/createArticle" use:enhance={enhanceForm({ closeModal: true })}>
<form
method="POST"
action="?/createArticle"
use:enhance={enhanceForm({ closeModal: true })}
>
<label>
Title:
<input type="text" name="title" pattern="\S(.*\S)?" maxlength="100" required />
</label>
<button type="submit" disabled={data.permissionLevel === 10}>Create article</button>
</form>
</Modal>
<Modal id="import-articles" text="Import articles">
<h3>Import articles</h3>
<form
method="POST"
action="?/importArticles"
enctype="multipart/form-data"
use:enhance={enhanceForm({ closeModal: true })}
>
<label>
Markdown files:
<input type="file" name="import-articles" accept=".md" multiple required />
</label>
<button type="submit" disabled={data.permissionLevel === 10}>Import articles</button>
</form>
</Modal>
</div>
</section>
{#if data.totalArticleCount > 0}
@@ -51,6 +70,11 @@
<a href="#all-articles">All articles</a>
</h2>
<a
class="export-anchor"
href={`${data.API_BASE_PREFIX}/rpc/export_articles_zip?website_id=${data.website.id}`}
>Export articles</a
>
<details>
<summary>Search & Filter</summary>
<form method="GET">
@@ -92,7 +116,6 @@
fill="currentColor"
width="16"
height="16"
style="vertical-align: middle"
>
<path
fill-rule="evenodd"
@@ -160,4 +183,15 @@
gap: var(--space-s);
align-items: center;
}
.multi-wrapper {
display: flex;
gap: var(--space-s);
flex-wrap: wrap;
align-items: start;
}
.export-anchor {
max-inline-size: fit-content;
}
</style>

View File

@@ -36,7 +36,13 @@
<form method="POST" action="?/createCategory" use:enhance={enhanceForm({ closeModal: true })}>
<label>
Name:
<input type="text" name="category-name" maxlength="50" required />
<input
type="text"
name="category-name"
maxlength="50"
pattern="^(?!Uncategorized$).+$"
required
/>
</label>
<label>
@@ -80,6 +86,7 @@
name="category-name"
value={category_name}
maxlength="50"
pattern="^(?!Uncategorized$).+$"
required
/>
</label>

View File

@@ -44,7 +44,7 @@ export const actions: Actions = {
});
},
deleteLegalInformation: async ({ fetch, params }) => {
const deleteLegalInformation = await apiRequest(
return await apiRequest(
fetch,
`${API_BASE_PREFIX}/legal_information?website_id=eq.${params.websiteId}`,
"DELETE",
@@ -52,12 +52,6 @@ export const actions: Actions = {
successMessage: "Successfully deleted legal information"
}
);
if (!deleteLegalInformation.success) {
return deleteLegalInformation;
}
return deleteLegalInformation;
},
pasteImage: async ({ request, fetch, params }) => {
const data = await request.formData();

View File

@@ -106,7 +106,7 @@
<th>User</th>
<th>Resource</th>
<th>Operation</th>
<th>Date & Time</th>
<th>Time</th>
<th>Changes</th>
</tr>
</thead>
@@ -140,21 +140,20 @@
<button type="submit">Compute diff</button>
</form>
{#if form?.logId === id && form?.currentDiff}
<pre style="white-space: pre-wrap">{@html DOMPurify.sanitize(
form.currentDiff,
{ ALLOWED_TAGS: ["ins", "del"] }
)}</pre>
<pre>{@html DOMPurify.sanitize(form.currentDiff, {
ALLOWED_TAGS: ["ins", "del"]
})}</pre>
{/if}
{/if}
{#if new_value && !old_value}
<h4>New value</h4>
<pre style="white-space: pre-wrap">{DOMPurify.sanitize(newValue)}</pre>
<pre>{DOMPurify.sanitize(newValue)}</pre>
{/if}
{#if old_value && !new_value}
<h4>Old value</h4>
<pre style="white-space: pre-wrap">{DOMPurify.sanitize(oldValue)}</pre>
<pre>{DOMPurify.sanitize(oldValue)}</pre>
{/if}
</Modal>
</td>
@@ -169,3 +168,9 @@
/>
</section>
</WebsiteEditor>
<style>
pre {
white-space: pre-wrap;
}
</style>

View File

@@ -4,25 +4,24 @@ import BlogArticle from "$lib/templates/blog/BlogArticle.svelte";
import BlogIndex from "$lib/templates/blog/BlogIndex.svelte";
import DocsArticle from "$lib/templates/docs/DocsArticle.svelte";
import DocsIndex from "$lib/templates/docs/DocsIndex.svelte";
import { type WebsiteOverview, hexToHSL, slugify } from "$lib/utils";
import { mkdir, readFile, rename, writeFile, chmod, readdir } from "node:fs/promises";
import { type WebsiteOverview, hexToHSL } from "$lib/utils";
import { mkdir, readFile, writeFile, chmod, readdir } from "node:fs/promises";
import { join } from "node:path";
import { render } from "svelte/server";
import type { Actions, PageServerLoad } from "./$types";
const getOverviewFetchUrl = (websiteId: string) => {
return `${API_BASE_PREFIX}/website?id=eq.${websiteId}&select=*,settings(*),header(*),home(*),footer(*),article(*,docs_category(*)),legal_information(*),domain_prefix(*)`;
};
export const load: PageServerLoad = async ({ params, fetch, parent }) => {
const websiteOverview: WebsiteOverview = (
await apiRequest(
fetch,
`${API_BASE_PREFIX}/website?id=eq.${params.websiteId}&select=*,settings(*),header(*),home(*),footer(*),article(*,docs_category(*)),legal_information(*),domain_prefix(*)`,
"GET",
{
await apiRequest(fetch, getOverviewFetchUrl(params.websiteId), "GET", {
headers: {
Accept: "application/vnd.pgrst.object+json"
},
returnData: true
}
)
})
).data;
const { websitePreviewUrl, websiteProdUrl } = await generateStaticFiles(websiteOverview);
@@ -40,22 +39,15 @@ export const load: PageServerLoad = async ({ params, fetch, parent }) => {
export const actions: Actions = {
publishWebsite: async ({ fetch, params }) => {
const websiteOverview: WebsiteOverview = (
await apiRequest(
fetch,
`${API_BASE_PREFIX}/website?id=eq.${params.websiteId}&select=*,settings(*),header(*),home(*),footer(*),article(*,docs_category(*)),legal_information(*),domain_prefix(*)`,
"GET",
{
await apiRequest(fetch, getOverviewFetchUrl(params.websiteId), "GET", {
headers: {
Accept: "application/vnd.pgrst.object+json"
},
returnData: true
}
)
})
).data;
await generateStaticFiles(websiteOverview, false);
return await apiRequest(
const publish = await apiRequest(
fetch,
`${API_BASE_PREFIX}/website?id=eq.${params.websiteId}`,
"PATCH",
@@ -66,78 +58,33 @@ export const actions: Actions = {
successMessage: "Successfully published website"
}
);
if (!publish.success) {
return publish;
}
await generateStaticFiles(websiteOverview, false);
return publish;
},
createUpdateCustomDomainPrefix: async ({ request, fetch, params }) => {
const data = await request.formData();
const oldDomainPrefix = (
await apiRequest(
fetch,
`${API_BASE_PREFIX}/domain_prefix?website_id=eq.${params.websiteId}`,
"GET",
{
headers: {
Accept: "application/vnd.pgrst.object+json"
},
returnData: true
}
)
).data;
const newDomainPrefix = await apiRequest(fetch, `${API_BASE_PREFIX}/domain_prefix`, "POST", {
headers: {
Prefer: "resolution=merge-duplicates",
Accept: "application/vnd.pgrst.object+json"
},
return await apiRequest(fetch, `${API_BASE_PREFIX}/rpc/set_domain_prefix`, "POST", {
body: {
website_id: params.websiteId,
prefix: data.get("domain-prefix")
},
successMessage: "Successfully created/updated domain prefix"
});
if (!newDomainPrefix.success) {
return newDomainPrefix;
}
await rename(
join(
"/",
"var",
"www",
"archtika-websites",
oldDomainPrefix?.prefix ? oldDomainPrefix.prefix : params.websiteId
),
join("/", "var", "www", "archtika-websites", data.get("domain-prefix") as string)
);
return newDomainPrefix;
},
deleteCustomDomainPrefix: async ({ fetch, params }) => {
const customPrefix = await apiRequest(
fetch,
`${API_BASE_PREFIX}/domain_prefix?website_id=eq.${params.websiteId}`,
"DELETE",
{
headers: {
Prefer: "return=representation",
Accept: "application/vnd.pgrst.object+json"
return await apiRequest(fetch, `${API_BASE_PREFIX}/rpc/delete_domain_prefix`, "POST", {
body: {
website_id: params.websiteId
},
successMessage: "Successfully deleted domain prefix",
returnData: true
}
);
if (!customPrefix.success) {
return customPrefix;
}
await rename(
join("/", "var", "www", "archtika-websites", customPrefix.data.prefix),
join("/", "var", "www", "archtika-websites", params.websiteId)
);
return customPrefix;
successMessage: "Successfully deleted domain prefix"
});
}
};
@@ -211,10 +158,7 @@ const generateStaticFiles = async (websiteData: WebsiteOverview, isPreview = tru
}
});
await writeFile(
join(uploadDir, "articles", `${slugify(article.title)}.html`),
fileContents(head, body)
);
await writeFile(join(uploadDir, "articles", `${article.slug}.html`), fileContents(head, body));
}
if (websiteData.legal_information) {

View File

@@ -71,7 +71,7 @@
placeholder="my-blog"
minlength="3"
maxlength="16"
pattern="^[a-z]+(-[a-z]+)*$"
pattern="^(?!previews$)[a-z]+(-[a-z]+)*$"
required
/>
</label>

View File

@@ -88,11 +88,16 @@ summary {
background-color: var(--bg-secondary);
}
summary:has(svg),
label:has(svg) {
display: inline-grid;
place-content: center;
}
label[for="toggle-theme"] {
margin-inline-start: auto;
}
label[for="toggle-theme"] svg:first-of-type {
display: var(--display-light);
}
@@ -113,6 +118,7 @@ label[for="toggle-theme"] svg:last-of-type {
}
button:disabled {
user-select: none;
pointer-events: none;
opacity: 0.5;
z-index: -10;

View File

@@ -1,4 +1,5 @@
import { test, expect } from "@playwright/test";
import { randomBytes } from "node:crypto";
import {
userOwner,
authenticate,
@@ -7,6 +8,8 @@ import {
collabTestingWebsite
} from "./shared";
const genArticleName = () => randomBytes(12).toString("hex");
test.describe("Website owner", () => {
test.beforeEach(async ({ page }) => {
await authenticate(userOwner, page);
@@ -21,7 +24,7 @@ test.describe("Website owner", () => {
test(`Create article`, async ({ page }) => {
await page.getByRole("button", { name: "Create article" }).click();
await page.locator("#create-article-modal").getByLabel("Title:").click();
await page.locator("#create-article-modal").getByLabel("Title:").fill("Article");
await page.locator("#create-article-modal").getByLabel("Title:").fill(genArticleName());
await page
.locator("#create-article-modal")
.getByRole("button", { name: "Create article" })
@@ -34,7 +37,7 @@ test.describe("Website owner", () => {
test.beforeEach(async ({ page }) => {
await page.getByRole("button", { name: "Create article" }).click();
await page.locator("#create-article-modal").getByLabel("Title:").click();
await page.locator("#create-article-modal").getByLabel("Title:").fill("Article");
await page.locator("#create-article-modal").getByLabel("Title:").fill(genArticleName());
await page
.locator("#create-article-modal")
.getByRole("button", { name: "Create article" })
@@ -81,7 +84,7 @@ for (const permissionLevel of permissionLevels) {
test(`Create article`, async ({ page }) => {
await page.getByRole("button", { name: "Create article" }).click();
await page.locator("#create-article-modal").getByLabel("Title:").click();
await page.locator("#create-article-modal").getByLabel("Title:").fill("Article");
await page.locator("#create-article-modal").getByLabel("Title:").fill(genArticleName());
await page
.locator("#create-article-modal")
.getByRole("button", { name: "Create article" })

View File

@@ -47,7 +47,7 @@ test(`Update user website storage limit`, async ({ page }) => {
.locator("details")
.getByRole("button", { name: "Update storage limit" })
.click();
await expect(page.getByText("Successfully updated user website storage size")).toBeVisible();
await expect(page.getByText("Successfully updated website storage")).toBeVisible();
});
test(`Delete user`, async ({ page }) => {