a lot of work, but i'd guess mostly api in the works

This commit is contained in:
2026-05-27 20:45:14 +02:00
parent 68458be71f
commit 50872d8951
22 changed files with 1425 additions and 1257 deletions
+19
View File
@@ -0,0 +1,19 @@
import { customType } from 'drizzle-orm/mysql-core';
export const mediumblob = customType<{
data: Buffer;
driverData: Buffer;
}>({
dataType() {
return 'MEDIUMBLOB';
}
});
export const longblob = customType<{
data: Buffer;
driverData: Buffer;
}>({
dataType() {
return 'LONGBLOB';
}
});
+72 -5
View File
@@ -1,4 +1,16 @@
import { mysqlTable, serial, int, text, tinyint } from 'drizzle-orm/mysql-core';
import {
boolean,
char,
int,
longtext,
mysqlTable,
serial,
text,
timestamp,
tinyint,
varchar
} from 'drizzle-orm/mysql-core';
import { longblob, mediumblob } from './custom-types';
export const task = mysqlTable('task', {
id: serial('id').primaryKey(),
@@ -6,10 +18,65 @@ export const task = mysqlTable('task', {
priority: int('priority').notNull().default(1)
});
export const settings = mysqlTable('settings', {
var: text('var').notNull().unique(),
state: tinyint('state')
export const config = mysqlTable('config', {
key: varchar('key', { length: 64 }).primaryKey(),
value: longtext('value').notNull()
});
export type Setting = typeof settings.$inferSelect;
export const projects = mysqlTable('projects', {
id: tinyint('id').notNull().primaryKey().autoincrement(),
name: text('name').notNull(),
data: longtext('data', {}).notNull(),
enabled: tinyint('enabled').notNull()
});
export const locales = mysqlTable('locales', {
code: char('code').notNull().unique(),
name: char('name').notNull(),
dictionary: longtext().notNull(),
flag: longtext('').notNull(),
enabled: tinyint('enabled').notNull()
});
export const groups = mysqlTable('groups', {
gid: int('gid').primaryKey().autoincrement(),
name: varchar('name', { length: 32 }).notNull().unique()
});
export const users = mysqlTable('users', {
uid: int('uid').primaryKey().autoincrement(),
username: varchar('username', { length: 32 }).notNull().unique(),
password: varchar('password', { length: 128 }).notNull(),
home: int('home').notNull(),
gid: int('gid')
.notNull()
.references(() => groups.gid),
accessible: boolean('accessible').notNull(),
face: mediumblob('face')
});
export const filesystem = mysqlTable(
'filesystem',
{
id: int('id').primaryKey().default(1),
data: longtext('data').notNull(),
checksum: varchar('checksum', { length: 32 }).notNull(),
updatedAt: timestamp('updated_at').defaultNow().onUpdateNow()
} /* ,
{
// Ensures only one row can exist
singleRow: check('single_row_check', `id = 1`)
} */
);
export const fileContents = mysqlTable('file_contents', {
guid: varchar('guid', { length: 36 }).primaryKey(),
data: longblob('data').notNull(),
mimeType: varchar('mime_type', { length: 127 }).default('text/plain')
});
export const allowList = mysqlTable('allow_list', {
ip: int('ip').notNull()
});
export type Config = typeof config.$inferSelect;
+4 -4
View File
@@ -1,6 +1,5 @@
import type { Bash } from './bash';
import { FileSystem } from '$lib/termos/filesystem/filesystem';
import type { TreeNode } from './fs';
import { Posix } from './posix';
export enum SortNodeBy {
NAME = 'name',
@@ -15,11 +14,12 @@ export enum SortNodeBy {
export class Sort {
public static nodeArraySort(
this: Bash,
nodes: TreeNode[] | number[],
reverse: boolean = false,
sortBy: SortNodeBy = SortNodeBy.NAME
): TreeNode[] {
const Fs = FileSystem.instance;
if (nodes.length === 0) {
console.warn('Tried to sort an empty node array!');
return [];
@@ -28,7 +28,7 @@ export class Sort {
if (typeof nodes[0] === 'number') {
for (const inode of nodes as number[]) {
const node = this.getFs().getNodeByINode(inode);
const node = Fs.getNodeByInode(inode);
parsedNodes.push(node);
}
Sort.nodeQSort(parsedNodes, reverse, sortBy, 0, parsedNodes.length - 1);
View File
+10 -20
View File
@@ -1,5 +1,4 @@
import type { User } from '../shell/shell';
import { MD5 } from '../util/hash';
export class FileSystem {
static #instance: FileSystem;
@@ -13,10 +12,10 @@ export class FileSystem {
if (!this._root) throw new Error('First entry in the filesystem map empty!');
}
public static async Init() {
let fsJson: JSON = await this._fetchFileSystem('/src/lib/assets/fs/fs.json');
const fsChecksum = MD5.hash(JSON.stringify(fsJson));
public static async Init(fsJson: JSON) {
//const fsChecksum = MD5.hash(JSON.stringify(fsJson));
/*
const cache: string | null = localStorage.getItem('fs-json');
if (cache) {
const fsCacheChecksum = MD5.hash(cache);
@@ -31,24 +30,17 @@ export class FileSystem {
}
localStorage.setItem('fs-json', JSON.stringify(fsJson));
*/
const fs: Map<number, TreeNode> = this._jsonToNodeTable(fsJson);
// This produces a different checksum!
// Find a way to produce the same hash from Map and a fetched json file or cached stringified json
console.log(MD5.hash(JSON.stringify(Array.from(fs))));
FileSystem.#instance = new FileSystem(fs);
}
private static async _fetchFileSystem(path: string): Promise<JSON> {
const response = await fetch(path);
if (!response.ok) throw new Error('Failed to fetch the file system json');
return await response.json();
}
private async _fetchFsSignature(path: string): Promise<any> {
/* private async _fetchFsSignature(path: string): Promise<any> {
try {
const response = await fetch(path);
if (!response.ok) {
@@ -60,11 +52,9 @@ export class FileSystem {
} catch (error) {
console.error('Failed to fetch the file system signature', error);
}
}
} */
private _fsToJsonString(): string {}
private static async fetchFsJson(): Promise<JSON> {
/* private static async fetchFsJson(): Promise<JSON> {
const checksum: string | null = localStorage.getItem('fs-checksum');
if (checksum !== sig || signature === null || localStorage.getItem('fs') === null) {
@@ -83,7 +73,7 @@ export class FileSystem {
return JSON.parse(fs);
}
}
} */
private static _jsonToNodeTable(data: JSON): Map<number, TreeNode> {
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
@@ -317,7 +307,7 @@ export class FileSystem {
throw new Error(`FileSystem was not initialized properly!`);
}
return FileSystem.instance;
return FileSystem.#instance;
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ export abstract class Command {
public abstract readonly _help: string; //TODO: Dont know where to pull the help text from yet
public abstract result: CommandResult;
public abstract Main(this: Shell, flags: CommandFlag[], args: string[]): void;
public abstract Main(flags: CommandFlag[], args: string[]): void;
}
export type CommandFlag = {
+11 -6
View File
@@ -1,9 +1,8 @@
import type { Stack } from '$lib/stores/stack';
import { FileSystem } from '../filesystem/filesystem';
import type { Command } from './command';
import type { Process } from './process';
export class Shell {
private readonly _fs: FileSystem;
private _passwd: User[];
private _group: Group[];
@@ -14,9 +13,15 @@ export class Shell {
private user: User;
private _process?: Process;
constructor() {
this._fs = new FileSystem();
}
constructor() {}
public static Initialize(
username: string,
password: string,
commands: Map<string, Command>,
passwd: Map<number, User>,
group: Map<number, Group>
) {}
}
export enum ExitCode {
+19
View File
@@ -0,0 +1,19 @@
<script lang="ts">
import { Type } from '$lib/termos/filesystem/filesystem';
import { File, Folder } from '@lucide/svelte';
let {
nodeName,
nodeType,
isProject = true
}: { nodeName: string; nodeType: Type; isProject: boolean } = $props();
</script>
<div class=" flex flex-row items-center rounded-md bg-bg-lighter-dark p-2">
{#if nodeType == Type.Directory}
<Folder class="text-primary-dark" strokeWidth={1} />
{:else}
<File strokeWidth={1} />
{/if}
<h4 class={isProject ? 'text-primary-dark' : 'text-text-dark'}>{nodeName}</h4>
</div>
+1 -3
View File
@@ -1,13 +1,11 @@
<script lang="ts">
import { ChevronRight, Power, SquarePen } from '@lucide/svelte';
let { projectName, checked = true }: { projectName: string; checked: boolean } = $props();
</script>
<div
class=" flex items-center text-text-dark saturate-50 has-checked:saturate-100 light:text-text-light"
>
<div class=" flex w-full flex-col justify-center gap-1 rounded-lg bg-bg-mid-dark">
<div class=" flex w-48 flex-col justify-center gap-1 rounded-lg bg-bg-mid-dark">
<h5 class=" m-4 font-primary text-xl font-bold">{projectName}</h5>
<div class="flex items-center gap-2">
<label
+58
View File
@@ -0,0 +1,58 @@
import { db } from '$lib/server/db';
import { filesystem } from '$lib/server/db/schema';
import { MD5 } from '$lib/termos/util/hash';
import { eq } from 'drizzle-orm';
export async function GET({ request }): Promise<Response> {
const row = await db
.select({
data: filesystem.data,
checksum: filesystem.checksum
})
.from(filesystem)
.where(eq(filesystem.id, 1))
.limit(1);
if (!row.length) {
return new Response('Filesystem is not initialized on the database', { status: 500 });
}
const { data, checksum } = row[0];
const clientETag = request.headers.get('if-none-match');
if (clientETag === `"${checksum}"`) {
return new Response(null, {
status: 304,
headers: { ETag: `"${checksum}"` }
});
}
return new Response(data, {
status: 200,
headers: {
'Content-Type': 'application/json',
ETag: `"${checksum}"`,
'Cache-Control': 'no-cache'
}
});
}
export async function POST({ request }) {
const newData = await request.text();
try {
const parsed = JSON.parse(newData);
//TODO: Schema validation
} catch {
//TODO: Change that to a proper http headers error
return new Response(null, {
status: 400
});
}
const checksum: string = MD5.hash(newData);
await db.update(filesystem).set({ data: newData, checksum }).where(eq(filesystem.id, 1));
return new Response(JSON.stringify({ success: true }), { status: 200 });
}
+27
View File
@@ -0,0 +1,27 @@
import { db } from '$lib/server/db';
import { users } from '$lib/server/db/schema';
import { json } from '@sveltejs/kit';
export async function GET({ request }): Promise<Response> {
const rows = await db
.select({
uid: users.uid,
username: users.username,
password: users.password,
home: users.home,
gid: users.gid,
accessible: users.accessible
})
.from(users);
if (!rows.length) {
return new Response('Filesystem is not initialized on the database', { status: 500 });
}
const result: {}[] = rows.map((u) => ({
...u,
avatarUrl: `/api/users/${u.uid}/avatar`
}));
return json(result);
}
+36
View File
@@ -0,0 +1,36 @@
import { db } from '$lib/server/db';
import { users } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
export async function GET({ params, request }): Promise<Response> {
const row = await db
.select({
uid: users.uid,
username: users.username,
password: users.password,
home: users.home,
gid: users.gid,
accessible: users.accessible
})
.from(users)
.where(eq(users.uid, Number(params.uid)))
.limit(1);
if (!row.length) {
return new Response(`User not found`, { status: 404 });
}
const user = row[0];
return new Response(
JSON.stringify({
...user,
avatarUrl: `/api/users/${user.uid}/avatar`
}),
{
headers: {
'Content-Type': 'application/json'
}
}
);
}
@@ -0,0 +1,11 @@
import { db } from '$lib/server/db';
import { users } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
export async function PUT({ params, request }) {
const uid = Number(params.uid);
const arrayBuffer = await request.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
await db.update(users).set({ face: buffer }).where(eq(users.uid, uid));
return new Response(null, { status: 204 });
}
+5 -6
View File
@@ -1,11 +1,10 @@
<script lang="ts">
import '../../app.css';
import favicon from '$lib/assets/favicon.svg';
import { getContext, setContext, type Snippet } from 'svelte';
import { BookA, ChartLine, ChartNoAxesColumn, Construction, FolderArchive, Plus } from '@lucide/svelte';
import { BookA, ChartLine, ChartNoAxesColumn, FolderArchive, Plus } from '@lucide/svelte';
import { type Snippet } from 'svelte';
import '../../app.css';
import SidebarButton from '../../modules/panel/SidebarButton.svelte';
let { children, data}: { children: Snippet, data: any } = $props();
let { children, data }: { children: Snippet; data: any } = $props();
</script>
<svelte:head>
@@ -36,7 +35,7 @@
</SidebarButton>
</form>
</div>
<div class="flex w-full grow">
<div class=" w-full">
{@render children()}
</div>
</div>
+17
View File
@@ -0,0 +1,17 @@
import { db } from '$lib/server/db';
import { locales } from '$lib/server/db/schema';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async () => {
return {
locales: await db
.select({
code: locales.code,
name: locales.name,
dictionary: locales.dictionary,
flag: locales.flag,
enabled: locales.enabled
})
.from(locales)
};
};
+15 -9
View File
@@ -1,19 +1,25 @@
<script lang="ts">
import LangModule from '../../../modules/panel/LangModule.svelte';
import plFlag from '$lib/assets/plFlag.svg';
import enFlag from '$lib/assets/enFlag.svg';
import deFlag from '$lib/assets/deFlag.svg';
import frFlag from '$lib/assets/frFlag.svg';
import jaFlag from '$lib/assets/jaFlag.svg';
let { data }: { data: any } = $props();
</script>
<div>
<form name="langs" class="m-10 flex flex-col gap-4">
<LangModule checked langName="Polish" icon={plFlag} />
<form name="locales" class="m-10 flex flex-col gap-4">
{#each data.locales as locale}
<LangModule checked={locale.enabled} langName={locale.name} icon={locale.flag} />
{/each}
<!-- <LangModule checked langName="Polish" icon={plFlag} />
<LangModule checked langName="English" icon={enFlag} />
<LangModule checked langName="German" icon={deFlag} />
<LangModule langName="Japanese" icon={jaFlag} />
<LangModule langName="French" icon={frFlag} />
<LangModule langName="French" icon={frFlag} /> -->
</form>
<div></div>
<div>
<form>
<input type="file" />
<input type="image" alt="NaN" />
<input type="text" />
</form>
</div>
</div>
+29 -5
View File
@@ -1,10 +1,34 @@
import { db } from "$lib/server/db";
import { settings } from "$lib/server/db/schema";
import { eq } from "drizzle-orm";
import type { PageServerLoad } from "./$types";
import fsData from '$lib/assets/fs/fs.json';
import { db } from '$lib/server/db';
import { projects, settings } from '$lib/server/db/schema';
import { FileSystem } from '$lib/termos/filesystem/filesystem';
import { Sort, SortNodeBy } from '$lib/termos/util/sort';
import { eq } from 'drizzle-orm';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async () => {
FileSystem.Init(fsData as any);
const fs = FileSystem.instance;
const node = fs.getNodeByInode(13); //Gordonox home dir
let nodes = node.children.map((child) => fs.getNodeByInode(child));
nodes = Sort.nodeArraySort(nodes, false, SortNodeBy.NAME);
return {
settings: await db.select({setting: settings.state}).from(settings).where(eq(settings.var, 'maintenance')).limit(1)
settings: await db
.select({ setting: settings.state })
.from(settings)
.where(eq(settings.var, 'maintenance'))
.limit(1),
projects: await db
.select({
id: projects.id,
name: projects.name,
data: projects.data,
enabled: projects.enabled
})
.from(projects),
nodes: nodes
};
};
+51 -9
View File
@@ -1,33 +1,75 @@
<script lang="ts">
import { Construction } from '@lucide/svelte';
import { Construction, Eye, EyeOff } from '@lucide/svelte';
import NodeModule from '../../../modules/panel/NodeModule.svelte';
import ProjectModule from '../../../modules/panel/ProjectModule.svelte';
import { setMaintenanceState } from '../settings.remote';
let { data }: { data: any } = $props();
let maintenance = $state(Boolean(data.settings[0].setting));
console.log(maintenance);
let showHidden = $state(false);
console.log(data.projects[0].name);
function handleToggle() {
console.log(maintenance);
maintenance = !maintenance;
maintenance = !maintenance;
console.log(maintenance);
let result = setMaintenanceState(Number(maintenance) as 1 | 0);
console.log(result);
}
}
function toggleHidden() {
showHidden = !showHidden;
}
</script>
<div class=" m-10">
<ProjectModule projectName="ProjectName" checked={false} />
</div>
<div
class=" grid-cols-[1.5fr, 1fr] grid w-full"
style="grid-template-areas:
'a b'; "
>
<div class=" m-10">
{#each data.projects as project}
<ProjectModule projectName={project.name} checked={project.enabled} />
{/each}
</div>
<div class="m-8 flex w-xl flex-col justify-self-end">
<div>
<button title="ButtonShowHidden" onclick={toggleHidden}>
{#if !showHidden}
<EyeOff stroke-width={1} class="text-text-muted-dark" />
{:else}
<Eye stroke-width={1} />
{/if}
</button>
</div>
<div class=" flex flex-col gap-1">
{#each data.nodes as node}
{#if showHidden}
<NodeModule nodeName={node.name} nodeType={node.type} isProject={false} />
{/if}
{#if !node.name.startsWith('.') && !showHidden}
<NodeModule nodeName={node.name} nodeType={node.type} isProject={false} />
{/if}
{/each}
</div>
</div>
</div>
<div class=" mt-4">
<Construction strokeWidth={1} />
<label
for='maintenence'
for="maintenence"
class="relative m-2 ml-auto block h-5 w-10 cursor-pointer rounded-full bg-bg-lighter-dark shadow-subtle"
>
<input type="checkbox" checked={maintenance} onclick={async () => await setMaintenanceState(Number(!maintenance))} id='maintenence' class=" peer sr-only" />
<input
type="checkbox"
checked={maintenance}
onclick={async () => await setMaintenanceState(Number(!maintenance))}
id="maintenence"
class=" peer sr-only"
/>
<span
class=" absolute top-0.5 left-0.5 h-4/5 w-2/5 rounded-full bg-bg-dark peer-checked:left-5.5 peer-checked:bg-primary-dark"
>
+6 -8
View File
@@ -1,11 +1,9 @@
import { query } from "$app/server";
import { db } from "$lib/server/db";
import { settings } from "$lib/server/db/schema";
import { eq } from "drizzle-orm";
import z from "zod";
import { query } from '$app/server';
import { db } from '$lib/server/db';
import { settings } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import z from 'zod';
export const setMaintenanceState = query(z.number(), async (state) => {
await db.update(settings)
.set({ state })
.where(eq(settings.var, 'maintenance'));
await db.update(settings).set({ state }).where(eq(settings.var, 'maintenance'));
});
+1 -4
View File
@@ -1,5 +1,4 @@
<script lang="ts">
import { FileSystem } from '$lib/termos/filesystem/filesystem';
import { MD5 } from '$lib/termos/util/hash';
import { onMount } from 'svelte';
@@ -7,7 +6,5 @@
console.log(MD5.hash('a'));
console.log(MD5.hash('abc'));
onMount(() => {
FileSystem.Init();
});
onMount(() => {});
</script>