Compare commits

...

17 Commits

Author SHA1 Message Date
9d541bd2bc tldr; nothing works 2025-11-28 12:31:12 +01:00
58849118d8 eod commit 2025-11-27 22:11:13 +01:00
09539a9cd0 added jwt, sqlite, build sh 2025-11-27 20:45:50 +01:00
6c6dfade42 updated .gitignore 2025-11-27 17:31:00 +01:00
e0298c9934 eod commit, working beta deployed (https://dev.security-command.org/) 2025-11-26 19:51:26 +01:00
70eb05c10b escaped string 2025-11-26 13:24:52 +00:00
330a22068f working, beta 2025-11-26 13:22:39 +00:00
635f16f8ff fuckass db shit 2025-11-26 12:29:31 +01:00
2c1cc78cb3 qol 2025-11-26 11:00:11 +01:00
ce7bc124ed hopefully fixed pointer deref / invalid mem access issue 2025-11-26 10:55:50 +01:00
3148affe4c eod commit 2025-11-25 22:10:36 +01:00
547d133add qol 2025-11-25 21:28:49 +01:00
b448ded507 updated styling pt.2 2025-11-25 21:07:48 +01:00
98d199b6d1 updated styling pt.1 2025-11-25 20:39:48 +01:00
1eeeb59fc7 works (now), lol 2025-11-25 19:46:02 +01:00
768c444b34 works, lol 2025-11-25 19:45:20 +01:00
12658c14c3 moved structs to extra file, added config db keys 2025-11-25 17:13:02 +01:00
26 changed files with 1236 additions and 759 deletions

4
.gitignore vendored
View File

@@ -13,6 +13,10 @@ main
*.lib *.lib
*.bak *.bak
*.out *.out
*.zst
*.gzip
*.env
*.db
bin/ bin/

View File

@@ -0,0 +1,33 @@
FROM ghcr.io/prantlf/vlang:latest AS builder
WORKDIR ./src/
COPY . .
RUN mkdir -p ./src/../../build/
# Build release binary. Output to /src/bin/cdn_app
# If your main file is main.v in the root of the context, this will work.
RUN v -prod -o ./src/../../build/ ./main.v
# Stage 2: runtime
FROM debian:bookworm-slim AS runtime
WORKDIR /app
# create non-root user (good practice)
RUN useradd -m appuser
# copy binary from builder
COPY --from=builder /src/bin/cdn_app /app/cdn_app
# copy templates/assets if your binary loads embedded files at runtime or expects files on disk
# (If you use V's $embed_file at compile time then templates are already embedded and this is optional)
COPY template/ /app/template/
COPY util/ /app/util/
COPY database/ /app/database/
RUN chown -R appuser:appuser /app
USER appuser
# expose container ports your app might use (adjust if you use different ports)
EXPOSE 8080 6767
ENTRYPOINT ["/app/cdn_app"]

6
app/build Normal file
View File

@@ -0,0 +1,6 @@
#!/bin/bash
cd src
v install fleximus.argon2
v install thomaspeissl.dotenv
v -prod -cflags "-static" -os linux -o ../../build/app/cdn .

View File

@@ -1,276 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Browser</title>
<link rel="stylesheet" href="../style/style.css">
</head>
<body>
<div class="container">
<div class="header">
<div class="breadcrumbs">Folder Path</div>
<div class="path-container" id="pathContainer">
<!-- Breadcrumbs will be generated here -->
</div>
<div class="controls">
<div class="meta">
<div id="summary">
<span class="meta-item"><b id="dirCount">0</b> directories</span>
<span class="meta-item"><b id="fileCount">0</b> files</span>
<span class="meta-item"><b id="totalSize">0 B</b> total</span>
</div>
<div class="layout-toggle">
<button class="layout-btn active" id="layoutList" onclick="setLayout('list')">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="18" height="7" rx="1"></rect>
<rect x="3" y="14" width="18" height="7" rx="1"></rect>
</svg>
List
</button>
<button class="layout-btn" id="layoutGrid" onclick="setLayout('grid')">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="7" height="7"></rect>
<rect x="14" y="3" width="7" height="7"></rect>
<rect x="14" y="14" width="7" height="7"></rect>
<rect x="3" y="14" width="7" height="7"></rect>
</svg>
Grid
</button>
</div>
</div>
<button class="btn theme-toggle" onclick="toggleTheme()">🌙</button>
</div>
</div>
<div class="content">
<div class="listing" id="listing">
<div class="file-list" id="fileList">
<!-- Files will be generated here -->
</div>
</div>
</div>
<script>
// Mock data - replace with actual file data
const mockFiles = [
{ name: 'documents', type: 'directory', size: null, modified: '2024-11-20' },
{ name: 'downloads', type: 'directory', size: null, modified: '2024-11-19' },
{ name: 'projects', type: 'directory', size: null, modified: '2024-11-15' },
{ name: 'report.pdf', type: 'file', size: 2457600, modified: '2024-11-18' },
{ name: 'presentation.pptx', type: 'file', size: 6082560, modified: '2024-11-17' },
{ name: 'data.json', type: 'file', size: 350208, modified: '2024-11-16' },
{ name: 'notes.txt', type: 'file', size: 12288, modified: '2024-11-14' },
{ name: 'archive.zip', type: 'file', size: 131072000, modified: '2024-11-10' },
];
let currentPath = '/home/user/documents';
let currentLayout = 'list';
// Theme management
function initTheme() {
const savedTheme = localStorage.getItem('theme') || 'dark';
document.documentElement.setAttribute('data-theme', savedTheme);
updateThemeButton();
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
const newTheme = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateThemeButton();
}
function updateThemeButton() {
const theme = document.documentElement.getAttribute('data-theme');
const btn = document.querySelector('.theme-toggle');
btn.textContent = theme === 'dark' ? '☀️' : '🌙';
}
function getIcon(type, name) {
if (type === 'directory') return '📁';
const ext = name.split('.').pop().toLowerCase();
const icons = {
pdf: '📄', pptx: '📊', xlsx: '📊', csv: '📊',
txt: '📝', md: '📝', json: '🔧', xml: '🔧',
jpg: '🖼️', png: '🖼️', gif: '🖼️', svg: '🖼️',
zip: '🗜️', rar: '🗜️', "7z": '🗜️',
mp3: '🎵', mp4: '🎬', avi: '🎬',
py: '🐍', js: '📜', html: '🌐', css: '🎨'
};
return icons[ext] || '📄';
}
function formatSize(bytes) {
if (!bytes) return '-';
const units = ['B', 'KB', 'MB', 'GB'];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return (size < 10 ? size.toFixed(2) : size.toFixed(0)) + ' ' + units[unitIndex];
}
function formatDate(dateStr) {
const date = new Date(dateStr);
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
}
function renderBreadcrumbs() {
const parts = currentPath.split('/').filter(p => p);
const pathContainer = document.getElementById('pathContainer');
let html = '<a href="#" onclick="navigateTo(\'/\'); return false;" class="breadcrumb-link">/</a>';
let accumulatedPath = '';
for (let i = 0; i < parts.length; i++) {
accumulatedPath += '/' + parts[i];
const isLast = i === parts.length - 1;
if (isLast) {
html += '<span class="breadcrumb-text">' + parts[i] + '</span>';
} else {
html += '<a href="#" onclick="navigateTo(\'' + accumulatedPath + '\'); return false;" class="breadcrumb-link">' + parts[i] + '</a>';
}
if (i < parts.length - 1) {
html += '<span class="breadcrumb-sep">/</span>';
} else {
html += '<span class="breadcrumb-sep">/</span>';
}
}
pathContainer.innerHTML = html;
}
function renderFileList() {
const fileList = document.getElementById('fileList');
if (mockFiles.length === 0) {
fileList.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📭</div>
<p>This folder is empty</p>
</div>
`;
updateSummary(0, 0, 0);
return;
}
// Sort: directories first, then alphabetically
const sorted = [...mockFiles].sort((a, b) => {
if (a.type === b.type) return a.name.localeCompare(b.name);
return a.type === 'directory' ? -1 : 1;
});
let dirCount = 0;
let fileCount = 0;
let totalSize = 0;
if (currentLayout === 'grid') {
const gridItems = sorted.map(file => {
if (file.type === 'directory') dirCount++;
else {
fileCount++;
totalSize += file.size || 0;
}
return `
<div class="grid-item" onclick="handleFileClick('${file.name}', '${file.type}')">
<div class="grid-icon">${getIcon(file.type, file.name)}</div>
<div class="grid-name">${file.name}</div>
${file.size ? `<div class="grid-size">${formatSize(file.size)}</div>` : ''}
</div>
`;
}).join('');
fileList.innerHTML = `<div class="grid">${gridItems}</div>`;
} else {
const tableRows = sorted.map(file => {
if (file.type === 'directory') dirCount++;
else {
fileCount++;
totalSize += file.size || 0;
}
return `
<tr class="file-row ${file.type}" onclick="handleFileClick('${file.name}', '${file.type}')">
<td class="icon">${getIcon(file.type, file.name)}</td>
<td class="name">${file.name}</td>
<td class="size">${file.size ? formatSize(file.size) : '-'}</td>
<td class="date">${formatDate(file.modified)}</td>
</tr>
`;
}).join('');
fileList.innerHTML = `
<table class="file-table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Size</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
${tableRows}
</tbody>
</table>
`;
}
updateSummary(dirCount, fileCount, totalSize);
}
function updateSummary(dirs, files, bytes) {
document.getElementById('dirCount').textContent = dirs;
document.getElementById('fileCount').textContent = files;
document.getElementById('totalSize').textContent = formatSize(bytes);
}
function handleFileClick(name, type) {
if (type === 'directory') {
navigateTo(currentPath + (currentPath.endsWith('/') ? '' : '/') + name);
} else {
console.log('Opening file:', name);
}
}
function navigateTo(path) {
currentPath = path;
renderBreadcrumbs();
renderFileList();
}
function navigateUp() {
const parts = currentPath.split('/').filter(p => p);
if (parts.length > 0) {
parts.pop();
currentPath = '/' + parts.join('/');
if (currentPath === '/') currentPath = '/';
navigateTo(currentPath);
}
}
function refreshList() {
renderFileList();
}
function setLayout(layout) {
currentLayout = layout;
document.getElementById('layoutList').classList.toggle('active', layout === 'list');
document.getElementById('layoutGrid').classList.toggle('active', layout === 'grid');
document.getElementById('listing').classList.toggle('list-view', layout === 'list');
document.getElementById('listing').classList.toggle('grid-view', layout === 'grid');
renderFileList();
}
// Initialize
initTheme();
renderBreadcrumbs();
renderFileList();
</script>
</body>
</html>

View File

@@ -1,260 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Browser</title>
<link rel="icon" type="image/x-icon" href="">
<link rel="stylesheet" href="../style/style.css">
</head>
<body>
<div class="container">
<div class="header">
<div class="breadcrumbs">Folder Path</div>
<div class="path-container" id="pathContainer">
<!-- Breadcrumbs will be generated here -->
</div>
<div class="controls">
<div class="meta">
<div id="summary">
<span class="meta-item"><b id="dirCount">0</b> directories</span>
<span class="meta-item"><b id="fileCount">0</b> files</span>
<span class="meta-item"><b id="totalSize">0 B</b> total</span>
</div>
<button class="btn theme-toggle" onclick="toggleTheme()">🌙</button> <!-- needs svgs -->
</div>
</div>
</div>
<div class="content">
<div class="listing" id="listing">
<div class="file-list" id="fileList">
<!-- Files will be generated here -->
</div>
</div>
</div>
</div>
<!-- <script>
// Mock data - replace with actual file data
const mockFiles = [
{ name: 'documents', type: 'directory', size: null, modified: '2024-11-20' },
{ name: 'downloads', type: 'directory', size: null, modified: '2024-11-19' },
{ name: 'projects', type: 'directory', size: null, modified: '2024-11-15' },
{ name: 'report.pdf', type: 'file', size: 2457600, modified: '2024-11-18' },
{ name: 'presentation.pptx', type: 'file', size: 6082560, modified: '2024-11-17' },
{ name: 'data.json', type: 'file', size: 350208, modified: '2024-11-16' },
{ name: 'notes.txt', type: 'file', size: 12288, modified: '2024-11-14' },
{ name: 'archive.zip', type: 'file', size: 131072000, modified: '2024-11-10' },
];
let currentPath = '/home/user/documents';
let currentLayout = 'list';
function initTheme()
{
const savedTheme = localStorage.getItem('theme') || 'dark';
document.documentElement.setAttribute('data-theme', savedTheme);
updateThemeButton();
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
const newTheme = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateThemeButton();
}
function updateThemeButton() {
const theme = document.documentElement.getAttribute('data-theme');
const btn = document.querySelector('.theme-toggle');
btn.textContent = theme === 'dark' ? '☀️' : '🌙';
}
function getIcon(type, name) {
if (type === 'directory') return '📁';
const ext = name.split('.').pop().toLowerCase();
const icons = {
pdf: '📄', pptx: '📊', xlsx: '📊', csv: '📊',
txt: '📝', md: '📝', json: '🔧', xml: '🔧',
jpg: '🖼️', png: '🖼️', gif: '🖼️', svg: '🖼️',
zip: '🗜️', rar: '🗜️', "7z": '🗜️',
mp3: '🎵', mp4: '🎬', avi: '🎬',
py: '🐍', js: '📜', html: '🌐', css: '🎨'
};
return icons[ext] || '📄';
}
function formatSize(bytes) {
if (!bytes) return '-';
const units = ['B', 'KB', 'MB', 'GB'];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return (size < 10 ? size.toFixed(2) : size.toFixed(0)) + ' ' + units[unitIndex];
}
function formatDate(dateStr) {
const date = new Date(dateStr);
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
}
function renderBreadcrumbs() {
const parts = currentPath.split('/').filter(p => p);
const pathContainer = document.getElementById('pathContainer');
let html = '<a href="#" onclick="navigateTo(\'/\'); return false;" class="breadcrumb-link">/</a>';
let accumulatedPath = '';
for (let i = 0; i < parts.length; i++) {
accumulatedPath += '/' + parts[i];
const isLast = i === parts.length - 1;
if (isLast) {
html += '<span class="breadcrumb-text">' + parts[i] + '</span>';
} else {
html += '<a href="#" onclick="navigateTo(\'' + accumulatedPath + '\'); return false;" class="breadcrumb-link">' + parts[i] + '</a>';
}
if (i < parts.length - 1) {
html += '<span class="breadcrumb-sep">/</span>';
} else {
html += '<span class="breadcrumb-sep">/</span>';
}
}
pathContainer.innerHTML = html;
}
function renderFileList() {
const fileList = document.getElementById('fileList');
if (mockFiles.length === 0) {
fileList.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📭</div>
<p>This folder is empty</p>
</div>
`;
updateSummary(0, 0, 0);
return;
}
// Sort: directories first, then alphabetically
const sorted = [...mockFiles].sort((a, b) => {
if (a.type === b.type) return a.name.localeCompare(b.name);
return a.type === 'directory' ? -1 : 1;
});
let dirCount = 0;
let fileCount = 0;
let totalSize = 0;
if (currentLayout === 'grid') {
const gridItems = sorted.map(file => {
if (file.type === 'directory') dirCount++;
else {
fileCount++;
totalSize += file.size || 0;
}
return `
<div class="grid-item" onclick="handleFileClick('${file.name}', '${file.type}')">
<div class="grid-icon">${getIcon(file.type, file.name)}</div>
<div class="grid-name">${file.name}</div>
${file.size ? `<div class="grid-size">${formatSize(file.size)}</div>` : ''}
</div>
`;
}).join('');
fileList.innerHTML = `<div class="grid">${gridItems}</div>`;
} else {
const tableRows = sorted.map(file => {
if (file.type === 'directory') dirCount++;
else {
fileCount++;
totalSize += file.size || 0;
}
return `
<tr class="file-row ${file.type}" onclick="handleFileClick('${file.name}', '${file.type}')">
<td class="icon">${getIcon(file.type, file.name)}</td>
<td class="name">${file.name}</td>
<td class="size">${file.size ? formatSize(file.size) : '-'}</td>
<td class="date">${formatDate(file.modified)}</td>
</tr>
`;
}).join('');
fileList.innerHTML = `
<table class="file-table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Size</th>
<th>Modified</th>
</tr>
</thead>
<tbody>
${tableRows}
</tbody>
</table>
`;
}
updateSummary(dirCount, fileCount, totalSize);
}
function updateSummary(dirs, files, bytes) {
document.getElementById('dirCount').textContent = dirs;
document.getElementById('fileCount').textContent = files;
document.getElementById('totalSize').textContent = formatSize(bytes);
}
function handleFileClick(name, type) {
if (type === 'directory') {
navigateTo(currentPath + (currentPath.endsWith('/') ? '' : '/') + name);
} else {
console.log('Opening file:', name);
}
}
function navigateTo(path) {
currentPath = path;
renderBreadcrumbs();
renderFileList();
}
function navigateUp() {
const parts = currentPath.split('/').filter(p => p);
if (parts.length > 0) {
parts.pop();
currentPath = '/' + parts.join('/');
if (currentPath === '/') currentPath = '/';
navigateTo(currentPath);
}
}
function refreshList() {
renderFileList();
}
function setLayout(layout) {
currentLayout = layout;
document.getElementById('layoutList').classList.toggle('active', layout === 'list');
document.getElementById('layoutGrid').classList.toggle('active', layout === 'grid');
document.getElementById('listing').classList.toggle('list-view', layout === 'list');
document.getElementById('listing').classList.toggle('grid-view', layout === 'grid');
renderFileList();
}
// Initialize
initTheme();
renderBreadcrumbs();
renderFileList();
</script> -->
</body>
</html>

Binary file not shown.

View File

@@ -0,0 +1,14 @@
module cryptography
import rand
import fleximus.argon2
pub fn hash_password(password string) !string {
salt := rand.bytes(16) or { return error('failed to generate salt: ${err}') }
hash := argon2.hash(password.bytes(), salt) or { return error('argon2 hash failed: ${err}') }
return hash
}
pub fn hash_verify(password string, hash string) !bool {
return argon2.verify(hash, password.bytes()) or { return error('argon2 verify failed: ${err}') }
}

49
app/src/database/db.v Normal file
View File

@@ -0,0 +1,49 @@
module database
import os
import orm
import util
import db.sqlite
pub struct Database {
cfg util.Config
}
pub fn get_dummy_exclusion_list(exe string, root string) []string {
return [
exe,
util.Utility.normalize_path(os.join_path(root, 'update.sh')),
]
}
fn (db &Database) get_connection() !sqlite.DB {
conn := sqlite.connect(db.cfg.database)!
if db.cfg.debug {
conn.synchronization_mode(.off)!
conn.journal_mode(.memory)!
}
sql conn {
create table User
create table Files
create table Logins
}!
return conn
}
pub fn get_database(cfg util.Config) !&Database {
return &Database{
cfg: cfg
}
}
pub fn (mut db Database) query[T](statement orm.QueryBuilder[T]) ![]T {
return statement.query()!
}
pub fn (db Database) get_query_builder[T]() &orm.QueryBuilder[T] {
conn := db.get_connection() or { panic(err) }
return orm.new_query[T](conn)
}

8
app/src/database/files.v Normal file
View File

@@ -0,0 +1,8 @@
module database
@[table: 'files']
pub struct Files {
id int @[primary; serial]
path string @[nonnull; unique]
visible bool @[default: false; nonnull]
}

46
app/src/database/logins.v Normal file
View File

@@ -0,0 +1,46 @@
module database
import time
@[table: 'login_attempts']
pub struct Logins {
mut:
ip string @[primary]
attempts int @[nonnull]
attempt_time time.Time @[nonnull]
}
pub fn Logins.by_ip(ip string, mut database_ Database) ?Logins {
query := database_.get_query_builder[Logins]().where('ip = ?', ip) or { return none }
result := database_.query[Logins](query) or { return none }
return result.first()
}
pub fn Logins.create_or_update(ip string, mut database_ Database) ?Logins {
mut login := Logins{
ip: ip
attempts: 1
attempt_time: time.now()
}
if existing := Logins.by_ip(ip, mut database_) {
login.attempts = existing.attempts + 1
login.attempt_time = time.now()
db := database_.get_connection() or { panic(err) }
sql db {
update Logins set attempts = login.attempts, attempt_time = login.attempt_time
where ip == ip
} or { return none }
} else {
db := database_.get_connection() or { panic(err) }
sql db {
insert login into Logins
} or { return none }
}
return login
}

52
app/src/database/user.v Normal file
View File

@@ -0,0 +1,52 @@
module database
import orm
import cryptography
@[table: 'users']
pub struct User {
pub:
id ?int @[primary; serial]
username string @[nonnull; unique]
password string @[nonnull]
}
pub fn User.by_id(user_id orm.Primitive, mut database_ Database) ?User {
query := database_.get_query_builder[User]().where('id = ?', user_id) or { return none }
result := database_.query[User](query) or { return none }
return result.first()
}
pub fn User.by_name(username orm.Primitive, mut database_ Database) ?User {
eprintln('qb')
query := database_.get_query_builder[User]().where('username = ?', username) or { return none }
eprintln('result')
result := database_.query[User](*query) or { return none }
eprintln('first')
return result.first()
}
pub fn User.create(username string, password string, database_ Database) ?User {
hash := cryptography.hash_password(password) or { return none }
mut user := User{
id: none
username: username
password: hash
}
db := database_.get_connection() or { panic(err) }
sql db {
insert user into User
} or { return none }
return user
}
pub fn User.verify(username orm.Primitive, password string, mut database_ Database) ?User {
eprintln('by_name')
user := User.by_name(username, mut database_) or { return none }
return if cryptography.hash_verify(password, user.password) or { false } { user } else { none }
}

19
app/src/jwt/algoritm.v Normal file
View File

@@ -0,0 +1,19 @@
module jwt
pub interface Algorithm {
name string
sign(contents string, secretOrKey string) !string
verify(token string, secretOrKey string) !Token
}
pub enum AlgorithmType {
hs256
}
pub fn new_algorithm(algorithmType AlgorithmType) Algorithm {
match algorithmType {
.hs256 {
return HS256{}
}
}
}

31
app/src/jwt/hs256.v Normal file
View File

@@ -0,0 +1,31 @@
module jwt
import crypto.hmac
import crypto.sha256
import encoding.base64
pub struct HS256 {
pub:
name string = 'HS256'
}
pub fn (algorithm HS256) sign(content string, secret string) !string {
return base64.url_encode(hmac.new(secret.bytes(), content.bytes(), sha256.sum, sha256.block_size))
}
pub fn (algorithm HS256) verify(token_raw string, secret string) !Token {
token := parse_token(token_raw)!
parts := token_raw.split('.')
header := parts[0]
claims := parts[1]
signed := algorithm.sign('${header}.${claims}', secret)!
if signed != token.signature {
return error('Invalid token')
}
if token.is_expired() {
return error('Token already expired')
}
return token
}

40
app/src/jwt/jwt.v Normal file
View File

@@ -0,0 +1,40 @@
module jwt
import json
import time
import x.json2
import encoding.base64
pub fn encode[T](claims T, algorithm Algorithm, secretOrKey string, exp int) !string {
header := new_header(algorithm)
header_b64 := base64.url_encode(json.encode(header).bytes())
mut claims_final := json2.decode[json2.Any](json.encode(claims))!.as_map()
if exp != 0 {
claims_final['exp'] = time.now().unix() + exp
}
claims_b64 := base64.url_encode(claims_final.str().bytes())
contents := '${header_b64}.${claims_b64}'
signature := algorithm.sign(contents, secretOrKey)!
return '${contents}.${signature}'
}
pub fn verify[T](token string, algorithm Algorithm, secretOrKey string) !T {
return algorithm.verify(token, secretOrKey)!.parse_claims[T]()
}
pub struct UserJwt {
pub:
id string
}
pub fn create(user_id string, secret string) !string {
return encode[UserJwt](UserJwt{ id: user_id }, new_algorithm(.hs256), secret, 7 * 24 * 60 * 60)!
}
pub fn decode(token string, secret string) !string {
return verify[UserJwt](token, new_algorithm(.hs256), secret)!.id
}

65
app/src/jwt/structs.v Normal file
View File

@@ -0,0 +1,65 @@
module jwt
import json
import time
import x.json2
import encoding.base64
pub struct JWTHeader {
pub:
alg string
typ string = 'JWT'
}
fn new_header(algorithm Algorithm) JWTHeader {
return JWTHeader{
alg: algorithm.name.str().to_upper()
}
}
struct Token {
pub:
header JWTHeader
claims string
signature string
expiration int
}
pub fn (t Token) parse_claims[T]() !T {
return json.decode(T, t.claims)
}
pub fn (t Token) is_expired() bool {
return t.expiration == -1 || time.unix(t.expiration) < time.now()
}
pub fn parse_token(token_raw string) !Token {
parts := token_raw.split('.')
if parts.len != 3 {
return error('Invalid token')
}
header_raw := if parts[0].len % 4 == 0 { parts[0] } else { parts[0] + '==' }
claims_raw := if parts[1].len % 4 == 0 { parts[1] } else { parts[1] + '==' }
decoded_header := base64.decode_str(header_raw)
decoded_claims := base64.decode_str(claims_raw)
claims := json2.decode[json2.Any](decoded_claims)!.as_map()
mut expiration_given := true
expiration_unix := claims['exp'] or {
expiration_given = false
json2.Null{}
}
token := Token{
header: json.decode(JWTHeader, decoded_header)!
claims: decoded_claims
signature: parts[2]
expiration: if expiration_given { expiration_unix.int() } else { -1 }
}
return token
}

View File

@@ -1,126 +1,271 @@
module main module main
import veb
import os import os
import log import veb
import jwt
import util
import sync
import database
import thomaspeissl.dotenv
import time
import net.http
struct Config { // structs
pub mut:
root string
port int
}
struct Embedded { pub struct CachedUser {
pub mut: pub:
style_css string user database.User
error_css string expires int
}
pub struct User {
pub mut:
name string
id int
} }
pub struct Context { pub struct Context {
veb.Context veb.Context
pub mut: pub mut:
embed Embedded app &App
user User user database.User
session_id string
} }
pub struct App { pub struct App {
veb.Controller veb.Controller
veb.StaticHandler veb.StaticHandler
veb.Middleware[Context] veb.Middleware[Context]
pub:
cfg util.Config
embed util.Embedded
pub mut: pub mut:
embed Embedded database database.Database
cache_lock sync.RwMutex
user_cache map[string]CachedUser
} }
pub struct Auth {} pub struct Auth {
veb.Controller
veb.Middleware[Context]
pub:
app &App
}
// endpoints // endpoints
@['/:path...'] @['/:path...']
pub fn (app &App) root(mut ctx Context, path string) veb.Result { pub fn (app &App) root(mut ctx Context, path string) veb.Result {
style := app.embed.style_css abs_root := util.Utility.normalize_path(os.real_path(app.cfg.root))
return ctx.html($tmpl('template/dashboard.html')) abs_path := util.Utility.normalize_path(os.real_path(os.join_path(abs_root, path)))
if !abs_path.starts_with(abs_root) && abs_path != abs_root {
return ctx.forbidden()
} }
@['/error'] if os.is_file(abs_path) {
pub fn (app &App) error(mut ctx Context) veb.Result { content := os.read_file(abs_path) or { return ctx.not_found() }
return ctx.html(ctx.error_page(500, 'Internal Server Error', 'Oops! Seems like something went wrong here.'))
ctx.res.header.add(.content_type, 'application/octet-stream')
ctx.res.header.add(.content_disposition, 'attachment; filename="${os.base(abs_path)}"')
return ctx.text(content)
}
exclude := database.get_dummy_exclusion_list(app.cfg.exe, app.cfg.root)
entries := util.Utility.list_files(abs_path, abs_root, exclude) or { return ctx.not_found() }
directory := util.HtmlBuilder.generate_breadcrumbs(abs_path.split(abs_root)[1])
files, meta := util.HtmlBuilder.generate_file_list(entries, abs_path)
style := app.embed.style_css
username := if ctx.user.username != '' { ctx.user.username } else { 'noone' }
return ctx.html($tmpl('template/dashboard.html'))
} }
// auth endpoints // auth endpoints
@['/']
pub fn (auth &Auth) root(mut ctx Context) veb.Result {
return ctx.redirect('/')
}
@[get; post] @[get; post]
pub fn (auth &Auth) login(mut ctx Context) veb.Result { pub fn (auth &Auth) login(mut ctx Context) veb.Result {
return ctx.text('') if ctx.req.method == .get {
style := auth.app.embed.admin_css
return ctx.html($tmpl('template/auth/login.html'))
}
token := ctx.get_cookie('veb_session') or { '' }
if token != '' {
return ctx.redirect('/')
}
username := ctx.form['username'] or { return ctx.request_error('') }
password := ctx.form['password'] or { return ctx.request_error('') }
if password.len < 8 {
return ctx.request_error('')
}
if user := database.User.verify(username, password, mut ctx.app.database) {
id := user.id or { return ctx.server_error('') }
ctx.set_cookie(http.Cookie{
name: 'veb_session'
value: jwt.create(id.str(), ctx.app.cfg.jwt_key) or { return ctx.server_error('') }
path: '/'
secure: true
http_only: true
same_site: .same_site_strict_mode
})
} else {
// todo cache login attempts per ip as well and block early.
database.Logins.create_or_update(ctx.ip(), mut ctx.app.database)
return ctx.forbidden()
}
return ctx.redirect('/')
} }
@[get; post] @[get; post]
pub fn (auth &Auth) logout(mut ctx Context) veb.Result { pub fn (auth &Auth) logout(mut ctx Context) veb.Result {
return ctx.text('') if ctx.req.method == .get {
style := auth.app.embed.admin_css
return ctx.html($tmpl('template/auth/logout.html'))
}
token := ctx.get_cookie('veb_session') or { '' }
if token == '' {
return ctx.redirect('/')
}
ctx.set_cookie(http.Cookie{
name: 'veb_session'
value: ''
path: '/'
secure: true
http_only: true
same_site: .same_site_strict_mode
max_age: -1
})
return ctx.redirect('/')
} }
@[get; post; put] @[get; post; put]
pub fn (auth &Auth) register(mut ctx Context) veb.Result { pub fn (auth &Auth) register(mut ctx Context) veb.Result {
return ctx.text('') return ctx.text('register')
}
// middleware
fn (mut app App) prepare() fn (mut Context) bool {
return fn [mut app] (mut ctx Context) bool {
ctx.app = &app
return true
}
}
pub fn session(mut ctx Context) bool {
token := ctx.get_cookie('veb_session') or { '' }
if token == '' {
return true
}
if id := jwt.decode(token, ctx.app.cfg.jwt_key) {
if user := ctx.app.get_user(id) {
ctx.user = user
}
}
return true
}
fn (mut app App) get_user(user_id string) ?database.User {
now := time.now().unix()
app.cache_lock.rlock()
if cu := app.user_cache[user_id] {
if cu.expires > int(now) {
app.cache_lock.runlock()
return cu.user
}
}
app.cache_lock.runlock()
user := database.User.by_id(user_id, mut app.database) or { return none }
app.cache_lock.lock()
app.user_cache[user_id] = CachedUser{
user: user
expires: int(now) + 300
}
app.cache_lock.unlock()
return user
} }
// utility // utility
fn (mut ctx Context) error_page(code int, short string, long string) string { fn (mut ctx Context) error_page(code int, short string, long string) string {
style := ctx.embed.error_css style := ctx.app.embed.error_css
return $tmpl('template/error.html') return $tmpl('template/error.html')
} }
pub fn (mut ctx Context) request_error(msg string) veb.Result {
ctx.res.set_status(.bad_request)
return ctx.html(ctx.error_page(400, 'Bad Request', 'This request is malformed or otherwise invalid.'))
}
pub fn (mut ctx Context) forbidden() veb.Result {
ctx.res.set_status(.forbidden)
return ctx.html(ctx.error_page(403, 'Forbidden', "Oops! You aren't allowed around here."))
}
pub fn (mut ctx Context) not_found() veb.Result { pub fn (mut ctx Context) not_found() veb.Result {
ctx.res.set_status(.not_found) ctx.res.set_status(.not_found)
return ctx.html(ctx.error_page(404, 'Not found', 'Oops! The page you are looking for does not exist.')) return ctx.html(ctx.error_page(404, 'Not found', 'Oops! The page you are looking for does not exist.'))
} }
// -- pub fn (mut ctx Context) server_error(msg string) veb.Result {
ctx.res.set_status(.internal_server_error)
fn populate() &Config { return ctx.html(ctx.error_page(500, 'Interal Server Error', 'Oops! Something went wrong here.'))
mut cfg := &Config{
root: $d('root', '.')
port: $d('port', 6767)
} }
if os.getenv('CDN_ROOT') != '' { // main
cfg.root = os.getenv('CDN_ROOT').str()
}
if os.getenv('CDN_PORT') != '' {
cfg.port = os.getenv('CDN_PORT').int()
}
return cfg fn populate() (util.Config, util.Embedded) {
dotenv.load()
executable := os.executable()
def_root := os.dir(executable)
def_port := int($d('port', 6767))
def_sqlt := $d('database', 'cdn_web.db')
def_jwt := $d('jwt', 'supersecurejwttokenkey')
// vfmt off
return util.Config{
exe: util.Utility.normalize_path(executable)
root: util.Utility.normalize_path(if os.getenv('CDN_ROOT') != '' { util.Utility.resolve_path(def_root, os.getenv('CDN_ROOT').str()) } else { def_root })
port: if os.getenv('CDN_PORT') != '' { os.getenv('CDN_PORT').int() } else { def_port }
jwt_key: if os.getenv('CDN_JWT_KEY') != '' { os.getenv('CDN_JWT_KEY').str() } else { def_jwt }
database: if os.getenv('CDN_SQL_DSN') != '' { os.getenv('CDN_SQL_DSN').str() } else { def_sqlt }
}, util.Embedded{
style_css: $embed_file('template/assets/style.css', .zlib).to_string()
error_css: $embed_file('template/assets/error.css', .zlib).to_string()
admin_css: $embed_file('template/assets/admin.css', .zlib).to_string()
}
// vfmt on
} }
fn main() { fn main() {
cfg := populate() // vfmt off
mut cfg, mut embed := populate()
mut app := &App{} mut app := &App{ cfg: cfg, embed: embed, database: database.get_database(cfg)! }
mut auth := &Auth{} mut auth := &Auth{ app: app }
app.embed = &Embedded{ // vfmt on
style_css: $embed_file('assets/style/style.css', .zlib).to_string()
error_css: $embed_file('assets/style/error.css', .zlib).to_string()
}
app.register_controller[Auth, Context]('/auth', mut auth)! app.register_controller[Auth, Context]('/auth', mut auth)!
app.enable_static_compression = true app.enable_static_compression = true
app.use(veb.encode_auto[Context]()) app.use(veb.encode_auto[Context]())
app.use(handler: app.prepare())
app.use(handler: session)
app.use(veb.MiddlewareOptions[Context]{ veb.run[App, Context](mut app, app.cfg.port)
handler: fn [app] (mut ctx Context) bool {
ctx.embed = &app.embed
return true
}
})
veb.run[App, Context](mut app, cfg.port)
} }

View File

@@ -0,0 +1,157 @@
/* General Reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Light Theme */
:root[data-theme="light"] {
--bg-primary: #ffffff;
--bg-secondary: #f5f7fb;
--bg-tertiary: #eff2f5;
--text-primary: #1a202c;
--text-secondary: #6c757d;
--border-color: #d4d7de;
--accent: #0051ba;
--accent-hover: #003e8f;
}
/* Dark Theme */
:root[data-theme="dark"] {
--bg-primary: #0d1117;
--bg-secondary: #161b22;
--bg-tertiary: #21262d;
--text-primary: #e6edf3;
--text-secondary: #8b949e;
--border-color: #30363d;
--accent: #58a6ff;
--accent-hover: #79c0ff;
}
/* Default theme */
:root {
--bg-primary: #0d1117;
--bg-secondary: #161b22;
--bg-tertiary: #21262d;
--text-primary: #e6edf3;
--text-secondary: #8b949e;
--border-color: #30363d;
--accent: #58a6ff;
--accent-hover: #79c0ff;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background-color: var(--bg-primary);
color: var(--text-primary);
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
text-align: center;
transition: background-color 0.3s ease, color 0.3s ease;
}
.container {
background-color: var(--bg-secondary);
border: 1px solid var(--border-color);
padding: 2rem 3rem;
border-radius: 0.5rem;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
width: 100%;
max-width: 400px;
}
h1 {
font-size: 2rem;
margin-bottom: 1.5rem;
color: var(--accent);
}
form {
display: flex;
flex-direction: column;
gap: 1rem;
}
label {
text-align: left;
font-size: 0.875rem;
color: var(--text-secondary);
}
input[type="text"],
input[type="password"] {
padding: 0.5rem 0.75rem;
border-radius: 0.375rem;
border: 1px solid var(--border-color);
background-color: var(--bg-tertiary);
color: var(--text-primary);
font-size: 1rem;
transition: all 0.2s ease;
}
input[type="text"]:focus,
input[type="password"]:focus {
border-color: var(--accent);
outline: none;
}
button {
padding: 0.5rem 1rem;
border-radius: 0.375rem;
border: 1px solid var(--border-color);
background-color: var(--bg-tertiary);
color: var(--text-primary);
cursor: pointer;
font-size: 1rem;
transition: all 0.2s ease;
}
button:hover {
background-color: var(--accent);
border-color: var(--accent);
color: #fff;
}
button:active {
transform: scale(0.98);
}
a.logout-link {
color: var(--accent);
text-decoration: none;
margin-top: 1rem;
display: inline-block;
font-size: 0.875rem;
}
a.logout-link:hover {
color: var(--accent-hover);
}
.theme-toggle {
margin-top: 1rem;
width: 1.75rem;
height: 1.75rem;
border: none;
background-color: var(--text-secondary);
border-radius: 6px;
cursor: pointer;
}
.theme-toggle:active {
transform: scale(0.98);
}
@media (max-width: 480px) {
.container {
padding: 1.5rem 2rem;
}
h1 {
font-size: 1.75rem;
}
}

View File

@@ -4,7 +4,6 @@
box-sizing: border-box; box-sizing: border-box;
} }
/* Light Mode (Cloudflare Dashboard Style) */
:root[data-theme="light"] { :root[data-theme="light"] {
--bg-primary: #ffffff; --bg-primary: #ffffff;
--bg-secondary: #f5f7fb; --bg-secondary: #f5f7fb;
@@ -15,9 +14,9 @@
--accent: #0051ba; --accent: #0051ba;
--accent-hover: #003e8f; --accent-hover: #003e8f;
--file-hover: #f0f2f5; --file-hover: #f0f2f5;
--icon: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMjRweCIgdmlld0JveD0iMCAtOTYwIDk2MCA5NjAiIHdpZHRoPSIyNHB4IiBmaWxsPSJpbmhlcml0Ij48cGF0aCBkPSJNNjAwLTY0MCA0ODAtNzYwbDEyMC0xMjAgMTIwIDEyMC0xMjAgMTIwWm0yMDAgMTIwLTgwLTgwIDgwLTgwIDgwIDgwLTgwIDgwWk00ODMtODBxLTg0IDAtMTU3LjUtMzJ0LTEyOC04Ni41UTE0My0yNTMgMTExLTMyNi41VDc5LTQ4NHEwLTE0NiA5My0yNTcuNVQ0MDktODgwcS0xOCA5OSAxMSAxOTMuNVQ1MjAtNTIxcTcxIDcxIDE2NS41IDEwMFQ4NzktNDEwcS0yNiAxNDQtMTM4IDIzN1Q0ODMtODBabTAtODBxODggMCAxNjMtNDR0MTE4LTEyMXEtODYtOC0xNjMtNDMuNVQ0NjMtNDY1cS02MS02MS05Ny0xMzh0LTQzLTE2M3EtNzcgNDMtMTIwLjUgMTE4LjVUMTU5LTQ4NHEwIDEzNSA5NC41IDIyOS41VDQ4My0xNjBabS0yMC0zMDVaIi8+PC9zdmc+')
} }
/* Dark Mode (GitHub Style) */
:root[data-theme="dark"] { :root[data-theme="dark"] {
--bg-primary: #0d1117; --bg-primary: #0d1117;
--bg-secondary: #161b22; --bg-secondary: #161b22;
@@ -28,6 +27,7 @@
--accent: #58a6ff; --accent: #58a6ff;
--accent-hover: #79c0ff; --accent-hover: #79c0ff;
--file-hover: #1c2128; --file-hover: #1c2128;
--icon: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMjRweCIgdmlld0JveD0iMCAtOTYwIDk2MCA5NjAiIHdpZHRoPSIyNHB4IiBmaWxsPSIjZTNlM2UzIj48cGF0aCBkPSJNNDQwLTgwMHYtMTIwaDgwdjEyMGgtODBabTAgNzYwdi0xMjBoODB2MTIwaC04MFptMzYwLTQwMHYtODBoMTIwdjgwSDgwMFptLTc2MCAwdi04MGgxMjB2ODBINDBabTcwOC0yNTItNTYtNTYgNzAtNzIgNTggNTgtNzIgNzBaTTE5OC0xNDBsLTU4LTU4IDcyLTcwIDU2IDU2LTcwIDcyWm01NjQgMC03MC03MiA1Ni01NiA3MiA3MC01OCA1OFpNMjEyLTY5MmwtNzItNzAgNTgtNTggNzAgNzItNTYgNTZabTI2OCA0NTJxLTEwMCAwLTE3MC03MHQtNzAtMTcwcTAtMTAwIDcwLTE3MHQxNzAtNzBxMTAwIDAgMTcwIDcwdDcwIDE3MHEwIDEwMC03MCAxNzB0LTE3MCA3MFptMC04MHE2NyAwIDExMy41LTQ2LjVUNjQwLTQ4MHEwLTY3LTQ2LjUtMTEzLjVUNDgwLTY0MHEtNjcgMC0xMTMuNSA0Ni41VDMyMC00ODBxMCA2NyA0Ni41IDExMy41VDQ4MC0zMjBabTAtMTYwWiIvPjwvc3ZnPg==')
} }
/* Default to dark mode */ /* Default to dark mode */
@@ -49,21 +49,21 @@ body {
color: var(--text-primary); color: var(--text-primary);
line-height: 1.6; line-height: 1.6;
transition: background-color 0.3s ease, color 0.3s ease; transition: background-color 0.3s ease, color 0.3s ease;
overflow: hidden;
} }
.container { .container {
max-width: 1200px; margin: 4vh;
margin: 0 auto;
padding: 0; padding: 0;
min-height: 100vh;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 92vh;
} }
.header { .header {
background-color: var(--bg-secondary); background-color: var(--bg-secondary);
border-bottom: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color);
padding: 1.5rem; padding: 2rem 3rem 1rem 3rem;
position: sticky; position: sticky;
top: 0; top: 0;
z-index: 10; z-index: 10;
@@ -131,6 +131,26 @@ body {
white-space: nowrap; white-space: nowrap;
} }
.theme-toggle {
width: 1.75rem;
height: 1.75rem;
padding: 0;
border: none;
background: var(--text-secondary);
-webkit-mask: var(--icon) center/60% no-repeat;
mask: var(--icon) center/60% no-repeat;
-webkit-mask-size: 60%;
mask-size: 60%;
background-repeat: no-repeat;
background-position: center;
border-radius: 6px;
cursor: pointer;
}
.theme-toggle:active {
transform: scale(0.98);
}
.btn:hover { .btn:hover {
background-color: var(--accent); background-color: var(--accent);
border-color: var(--accent); border-color: var(--accent);
@@ -142,14 +162,15 @@ body {
} }
.content { .content {
padding: 1.5rem; padding: 0 1.5rem;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center;
flex-wrap: wrap; flex-wrap: wrap;
gap: 1rem; gap: 1rem;
border-bottom: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color);
background-color: var(--bg-secondary); background-color: var(--bg-secondary);
transition: background-color 0.3s ease, border-color 0.3s ease;
height: 100%;
} }
.meta { .meta {
@@ -157,6 +178,8 @@ body {
gap: 2rem; gap: 2rem;
font-size: 0.875rem; font-size: 0.875rem;
flex-wrap: wrap; flex-wrap: wrap;
justify-content: space-between;
width: 100%;
} }
#summary { #summary {
@@ -213,117 +236,200 @@ body {
overflow-x: auto; overflow-x: auto;
} }
/* Table Layout */ .file-row a,
.file-table { .btn,
.theme-toggle {
outline: none;
-webkit-tap-highlight-color: transparent;
}
.icon svg {
fill: var(--text-secondary);
}
.file-list {
display: flex;
flex-direction: column;
gap: 0;
width: 100%; width: 100%;
border-collapse: collapse; background: transparent;
border-radius: 0.25rem;
overflow: hidden;
} }
.file-table thead { .file-row {
position: sticky; display: grid;
top: 0; grid-template-columns: 2.5rem 1fr 10.5rem 14rem;
background-color: var(--bg-secondary); align-items: center;
z-index: 5; gap: 0.75rem;
}
.file-table th {
text-align: left;
padding: 0.75rem; padding: 0.75rem;
border-bottom: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color);
color: var(--text-secondary); transition: background-color 0.15s ease, transform 0.08s ease;
font-size: 0.875rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.file-table tbody tr {
border-bottom: 1px solid var(--border-color);
transition: all 0.2s ease;
cursor: pointer; cursor: pointer;
background: transparent;
} }
.file-table tbody tr:hover { .file-row > div:first-child {
background-color: var(--file-hover); display: flex;
align-items: center;
justify-content: center;
align-self: center;
} }
.file-table td { .file-row .name {
padding: 0.75rem; align-self: center;
color: var(--text-primary); display: block;
} }
.file-table td.icon { .file-list .file-row:last-child {
border-bottom: none;
}
.file-row > div:first-child {
width: 2.5rem; width: 2.5rem;
font-size: 1.25rem; height: 2rem;
text-align: center; display: flex;
align-items: center;
justify-content: center;
font-size: 1.125rem;
} }
.file-table td.name { /* name cell */
.file-row .name {
display: flex;
align-items: center; /* vertically center the link text with the icon */
min-width: 0; /* allow ellipsis to work inside flex items */
font-weight: 500; font-weight: 500;
} color: var(--text-primary);
overflow: hidden; /* keep long names from breaking layout */
.file-table tr.directory td.name { text-overflow: ellipsis;
color: var(--accent);
font-weight: 600;
}
.file-table td.size,
.file-table td.date {
color: var(--text-secondary);
font-size: 0.875rem;
white-space: nowrap; white-space: nowrap;
} }
/* Grid Layout */ /* name link */
.grid { .file-row .name a {
display: grid; display: block; /* block-level so height:100% works reliably */
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); width: 100%;
gap: 1rem; height: 100%; /* fill the .name (including padding row gives) */
line-height: 1.2; /* control baseline — tweak if you want tighter/looser text */
text-decoration: none;
color: inherit;
padding: 0; /* avoid extra internal vertical padding */
overflow: hidden; /* ensure ellipsis works on the link text */
text-overflow: ellipsis;
white-space: nowrap;
} }
.grid-item { /* directory emphasis */
display: flex; .file-row.directory .name {
flex-direction: column;
align-items: center;
justify-content: flex-start;
padding: 1rem;
background-color: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 0.5rem;
cursor: pointer;
transition: all 0.2s ease;
text-align: center;
}
.grid-item:hover {
background-color: var(--file-hover);
border-color: var(--accent);
transform: translateY(-2px);
}
.grid-icon {
font-size: 2.5rem;
margin-bottom: 0.75rem;
}
.grid-name {
font-weight: 500;
color: var(--text-primary);
word-break: break-word;
overflow-wrap: break-word;
font-size: 0.875rem;
margin-bottom: 0.5rem;
}
.grid-item:has(.grid-name) .grid-name {
color: var(--accent); color: var(--accent);
font-weight: 600; font-weight: 600;
} }
.grid-size { /* size and date cells */
font-size: 0.75rem; .file-row .size,
.file-row .date {
color: var(--text-secondary); color: var(--text-secondary);
margin-top: auto; font-size: 0.875rem;
white-space: nowrap;
justify-self: end;
}
/* smaller size column alignment */
.file-row .size {
justify-self: end;
}
/* hover / focus */
.file-row:hover {
background-color: var(--file-hover);
}
.file-row:active {
transform: translateY(0.5px);
}
.file-list.compact .file-row {
padding: 0.5rem;
grid-template-columns: 2rem 1fr 8.5rem 12rem;
}
@media (max-width: 992px) {
.file-row {
grid-template-columns: 2.5rem 1fr 9rem 12rem;
}
}
@media (max-width: 768px) {
.file-row {
grid-template-columns: 2.5rem 1fr 9rem; /* icon | name | size */
}
.file-row .date {
display: none;
}
.file-row .size {
justify-self: end;
color: var(--text-secondary);
}
}
@media (max-width: 480px) {
.file-row {
grid-template-columns: 2.5rem 1fr;
grid-template-rows: auto auto;
gap: 0.25rem 0.5rem;
align-items: center; /* center items rather than start */
padding: 0.6rem;
}
.file-row > div:first-child {
grid-row: 1 / span 2;
align-self: center; /* was start, now center */
width: 2.5rem;
height: 2.5rem; /* slightly bigger on mobile for touch */
}
.file-row .name {
grid-column: 2;
grid-row: 1;
white-space: normal;
overflow: visible;
align-self: center;
}
@media (max-width: 480px) {
.file-row .name a {
padding-left: 4px;
padding-right: 4px;
}
}
.file-row .size {
grid-column: 2;
grid-row: 2;
justify-self: start;
color: var(--text-secondary);
font-size: 0.85rem;
}
.file-row .date {
display: none;
}
}
@media (max-width: 480px) {
.theme-toggle {
width: 1.5rem;
height: 1.5rem;
-webkit-mask-size: 56%;
mask-size: 56%;
}
}
.view-list .file-list {
display: block;
} }
.empty-state { .empty-state {
@@ -345,6 +451,7 @@ body {
} }
.listing { .listing {
width: 100%;
padding: 1rem; padding: 1rem;
} }
@@ -354,23 +461,6 @@ body {
align-items: flex-start; align-items: flex-start;
} }
.file-table td.date {
display: none;
}
.file-table th:last-child {
display: none;
}
.grid {
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
gap: 0.75rem;
}
.grid-item {
padding: 0.75rem;
}
.path-container { .path-container {
font-size: 0.9rem; font-size: 0.9rem;
margin-bottom: 0.75rem; margin-bottom: 0.75rem;
@@ -427,33 +517,6 @@ body {
font-size: 0.75rem; font-size: 0.75rem;
flex-direction: column; flex-direction: column;
} }
.file-table th,
.file-table td {
padding: 0.5rem 0.25rem;
}
.file-table td.size {
display: none;
}
.grid {
grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
gap: 0.5rem;
}
.grid-item {
padding: 0.5rem;
}
.grid-icon {
font-size: 2rem;
margin-bottom: 0.5rem;
}
.grid-name {
font-size: 0.7rem;
}
} }
/* Scrollbar Styling */ /* Scrollbar Styling */

View File

@@ -0,0 +1,25 @@
<!DOCTYPE html>
<!--suppress HtmlFormInputWithoutLabel -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>@{style}</style>
</head>
<body>
<div class="container">
<h1>Login</h1>
<form action="/auth/login" method="POST">
<input placeholder="Username" type="text" id="username" name="username" required>
<input placeholder="Password" type="password" id="password" name="password" minlength="8" required>
<button type="submit">Sign In</button>
</form>
</div>
<script>
if ((savedTheme = (localStorage.getItem('theme') || 'light')))
document.documentElement.setAttribute('data-theme', savedTheme);
</script>
</body>
</html>

View File

@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logout</title>
<style>@{style}</style>
</head>
<body>
<div class="container">
<h1>Log Out?</h1>
<form action="/auth/logout" method="POST">
<button type="submit">Logout</button>
</form>
</div>
<script>
if ((savedTheme = (localStorage.getItem('theme') || 'light')))
document.documentElement.setAttribute('data-theme', savedTheme);
</script>
</body>
</html>

View File

@@ -3,34 +3,45 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Browser</title> <title>Logged in as @{username}</title>
<link rel="icon" type="image/x-icon" href="">
<style>@{style}</style> <style>@{style}</style>
</head> </head>
<body> <body>
<div class="container"> <div class="container">
<div class="header"> <div class="header">
<div class
<div class="breadcrumbs">Folder Path</div> <div class="breadcrumbs">Folder Path</div>
<div class="path-container" id="pathContainer"> <div class="path-container">
@{directory}
</div> </div>
<div class="controls"> <div class="controls">
<div class="meta"> <div class="meta">
<div id="summary"> <div id="summary">
<span class="meta-item"><b id="dirCount">0</b> directories</span> @{meta}
<span class="meta-item"><b id="fileCount">0</b> files</span>
<span class="meta-item"><b id="totalSize">0 B</b> total</span>
</div> </div>
<button class="btn theme-toggle" onclick="toggleTheme()">🌙</button> <button class="btn theme-toggle" onclick="toggleTheme()"></button>
</div> </div>
</div> </div>
</div> </div>
<div class="content"> <div class="content">
<div class="listing" id="listing"> <div class="listing">
<div class="file-list" id="fileList"> <div class="file-list">
@{files}
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<script>
if ((savedTheme = (localStorage.getItem('theme') || 'light')))
document.documentElement.setAttribute('data-theme', savedTheme);
const toggleTheme = () =>
{
const newTheme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
}
</script>
</body> </body>
</html> </html>

1
app/src/util/http.v Normal file
View File

@@ -0,0 +1 @@
module util

227
app/src/util/structs.v Normal file
View File

@@ -0,0 +1,227 @@
// util/structs.v
module util
import os
import time
import encoding.base64
pub struct Config {
pub:
exe string
root string
port int
debug bool
jwt_key string
database string
}
pub struct Embedded {
pub mut:
style_css string
error_css string
admin_css string
}
pub struct FileEntry {
pub:
name string
abs_path string
path string
is_dir bool
size i64
modified i64
icon string
}
pub struct Utility {}
pub fn Utility.get_icon(ext string, is_dir bool) string {
icons := {
'dir': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h240l80 80h320q33 0 56.5 23.5T880-640v400q0 33-23.5 56.5T800-160H160Zm0-80h640v-400H447l-80-80H160v480Zm0 0v-480 480Z"/></svg>' //'icon-dir'
'pdf': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M240-80q-33 0-56.5-23.5T160-160v-640q0-33 23.5-56.5T240-880h320l240 240v480q0 33-23.5 56.5T720-80H240Zm280-520v-200H240v640h480v-440H520ZM240-800v200-200 640-640Z"/></svg>' // 'icon-pdf',
'txt': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M280-280h280v-80H280v80Zm0-160h400v-80H280v80Zm0-160h400v-80H280v80Zm-80 480q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm0-560v560-560Z"/></svg>'
'md': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M280-280h280v-80H280v80Zm0-160h400v-80H280v80Zm0-160h400v-80H280v80Zm-80 480q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm0-560v560-560Z"/></svg>'
'json': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>'
'xml': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>'
'jpg': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm40-80h480L570-480 450-320l-90-120-120 160Zm-40 80v-560 560Z"/></svg>'
'jpeg': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm40-80h480L570-480 450-320l-90-120-120 160Zm-40 80v-560 560Z"/></svg>'
'png': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm40-80h480L570-480 450-320l-90-120-120 160Zm-40 80v-560 560Z"/></svg>'
'gif': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm40-80h480L570-480 450-320l-90-120-120 160Zm-40 80v-560 560Z"/></svg>'
'svg': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm40-80h480L570-480 450-320l-90-120-120 160Zm-40 80v-560 560Z"/></svg>'
'zip': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M640-480v-80h80v80h-80Zm0 80h-80v-80h80v80Zm0 80v-80h80v80h-80ZM447-640l-80-80H160v480h400v-80h80v80h160v-400H640v80h-80v-80H447ZM160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h240l80 80h320q33 0 56.5 23.5T880-640v400q0 33-23.5 56.5T800-160H160Zm0-80v-480 480Z"/></svg>'
'rar': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M640-480v-80h80v80h-80Zm0 80h-80v-80h80v80Zm0 80v-80h80v80h-80ZM447-640l-80-80H160v480h400v-80h80v80h160v-400H640v80h-80v-80H447ZM160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h240l80 80h320q33 0 56.5 23.5T880-640v400q0 33-23.5 56.5T800-160H160Zm0-80v-480 480Z"/></svg>'
'7z': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M640-480v-80h80v80h-80Zm0 80h-80v-80h80v80Zm0 80v-80h80v80h-80ZM447-640l-80-80H160v480h400v-80h80v80h160v-400H640v80h-80v-80H447ZM160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h240l80 80h320q33 0 56.5 23.5T880-640v400q0 33-23.5 56.5T800-160H160Zm0-80v-480 480Z"/></svg>'
'zst': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M640-480v-80h80v80h-80Zm0 80h-80v-80h80v80Zm0 80v-80h80v80h-80ZM447-640l-80-80H160v480h400v-80h80v80h160v-400H640v80h-80v-80H447ZM160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h240l80 80h320q33 0 56.5 23.5T880-640v400q0 33-23.5 56.5T800-160H160Zm0-80v-480 480Z"/></svg>'
'gzip': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M640-480v-80h80v80h-80Zm0 80h-80v-80h80v80Zm0 80v-80h80v80h-80ZM447-640l-80-80H160v480h400v-80h80v80h160v-400H640v80h-80v-80H447ZM160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h240l80 80h320q33 0 56.5 23.5T880-640v400q0 33-23.5 56.5T800-160H160Zm0-80v-480 480Z"/></svg>'
'mp3': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M430-200q38 0 64-26t26-64v-150h120v-80H480v155q-11-8-23.5-11.5T430-380q-38 0-64 26t-26 64q0 38 26 64t64 26ZM240-80q-33 0-56.5-23.5T160-160v-640q0-33 23.5-56.5T240-880h320l240 240v480q0 33-23.5 56.5T720-80H240Zm280-520v-200H240v640h480v-440H520ZM240-800v200-200 640-640Z"/></svg>'
'mp4': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M360-240h160q17 0 28.5-11.5T560-280v-40l80 42v-164l-80 42v-40q0-17-11.5-28.5T520-480H360q-17 0-28.5 11.5T320-440v160q0 17 11.5 28.5T360-240ZM240-80q-33 0-56.5-23.5T160-160v-640q0-33 23.5-56.5T240-880h320l240 240v480q0 33-23.5 56.5T720-80H240Zm280-520v-200H240v640h480v-440H520ZM240-800v200-200 640-640Z"/></svg>'
'avi': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M360-240h160q17 0 28.5-11.5T560-280v-40l80 42v-164l-80 42v-40q0-17-11.5-28.5T520-480H360q-17 0-28.5 11.5T320-440v160q0 17 11.5 28.5T360-240ZM240-80q-33 0-56.5-23.5T160-160v-640q0-33 23.5-56.5T240-880h320l240 240v480q0 33-23.5 56.5T720-80H240Zm280-520v-200H240v640h480v-440H520ZM240-800v200-200 640-640Z"/></svg>'
'mov': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M360-240h160q17 0 28.5-11.5T560-280v-40l80 42v-164l-80 42v-40q0-17-11.5-28.5T520-480H360q-17 0-28.5 11.5T320-440v160q0 17 11.5 28.5T360-240ZM240-80q-33 0-56.5-23.5T160-160v-640q0-33 23.5-56.5T240-880h320l240 240v480q0 33-23.5 56.5T720-80H240Zm280-520v-200H240v640h480v-440H520ZM240-800v200-200 640-640Z"/></svg>'
'java': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>'
'py': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>'
'js': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>'
'ts': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>'
'v': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>'
'html': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Zm0-80h420v-140H160v140Zm500 0h140v-360H660v360ZM160-460h420v-140H160v140Z"/></svg>'
'css': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Zm0-80h420v-140H160v140Zm500 0h140v-360H660v360ZM160-460h420v-140H160v140Z"/></svg>'
'exe': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Zm0-80h640v-400H160v400Zm140-40-56-56 103-104-104-104 57-56 160 160-160 160Zm180 0v-80h240v80H480Z"/></svg>'
'unknown': '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M240-80q-33 0-56.5-23.5T160-160v-640q0-33 23.5-56.5T240-880h320l240 240v480q0 33-23.5 56.5T720-80H240Zm280-520v-200H240v640h480v-440H520ZM240-800v200-200 640-640Z"/></svg>'
}
return if is_dir { icons['dir'] } else { icons[ext] or { icons['unknown'] } }
}
pub fn Utility.svg_to_data_uri(svg string) string {
return 'data:image/svg+xml;base64,${base64.encode(svg.bytes())}'
}
pub fn Utility.format_size(bytes i64) string {
if bytes == 0 {
return '-'
}
units := ['B', 'KB', 'MB', 'GB']
mut size := f64(bytes)
mut unit_idx := 0
for size >= 1024 && unit_idx < units.len - 1 {
size /= 1024
unit_idx++
}
if size < 10 {
return '${size:.2f}${units[unit_idx]}'
}
return '${size:.0f}${units[unit_idx]}'
}
pub fn Utility.format_date(unix_time i64) string {
return time.unix(unix_time).format_ss_milli()
}
pub fn Utility.resolve_path(base string, path string) string {
if os.is_abs_path(path) {
return path
}
return os.real_path(os.join_path(base, path))
}
pub fn Utility.list_files(dir_path string, relative string, exclude []string) ![]FileEntry {
mut entries := []FileEntry{}
files := os.ls(dir_path)!
for file in files {
full_path := os.join_path(dir_path, file)
normalized := Utility.normalize_path(full_path)
if normalized in exclude {
continue
}
is_dir := os.is_dir(full_path)
file_info := os.stat(full_path)!
file_ext := full_path.split('.').last()
entries << FileEntry{
name: if is_dir { '${file}/' } else { file }
abs_path: normalized
path: Utility.normalize_path(full_path).split(relative)[1] or { 'err' }
is_dir: is_dir
size: if !is_dir { file_info.size } else { 0 }
modified: file_info.mtime
icon: Utility.get_icon(file_ext, is_dir)
}
}
entries.sort_with_compare(fn (a &FileEntry, b &FileEntry) int {
if a.is_dir != b.is_dir {
return if a.is_dir { -1 } else { 1 }
}
if a.name < b.name {
return -1
}
if a.name > b.name {
return 1
}
return 0
})
return entries
}
pub fn Utility.normalize_path(path string) string {
return path.replace('\\', '/').replace('//', '/')
}
pub struct HtmlBuilder {}
pub fn HtmlBuilder.generate_breadcrumbs(path string) string {
mut html := '<a href="/" class="breadcrumb-link">/</a>'
parts := path.trim('/').split('/')
mut accumulated := ''
for i, part in parts {
if part == '' {
continue
}
accumulated += '/${part}'
is_last := i == parts.len - 1
if is_last {
html += '<span class="breadcrumb-text">${part}</span>'
} else {
html += '<a href="${accumulated}" class="breadcrumb-link">${part}</a>'
}
if i < parts.len - 1 {
html += '<span class="breadcrumb-sep">/</span>'
} else {
html += '<span class="breadcrumb-sep">/</span>'
}
}
return html
}
pub fn HtmlBuilder.generate_file_list(entries []FileEntry, current_path string) (string, string) {
if entries.len == 0 {
return '<div class="empty-state"><p>This folder is empty</p></div>', '<span class="meta-item"><b>0</b> directories</span><span class="meta-item"><b>0</b> files</span><span class="meta-item"><b>0B</b> total</span>'
}
mut html := '<div class="file-list">'
mut dir_count := 0
mut file_count := 0
mut total_size := i64(0)
for entry in entries {
if entry.is_dir {
dir_count++
html += '<div class="file-row directory">'
html += '<div class="icon">${entry.icon}</div>'
html += '<div class="name"><a href="${entry.path}">${entry.name}</a></div>'
html += '<div class="size">${Utility.format_size(entry.size)}</div>'
html += '<div class="date">${Utility.format_date(entry.modified)}</div>'
html += '</div>'
} else {
file_count++
total_size += entry.size
html += '<div class="file-row file">'
html += '<div class="icon">${entry.icon}</div>'
html += '<div class="name"><a href="${entry.path}">${entry.name}</a></div>'
html += '<div class="size">${Utility.format_size(entry.size)}</div>'
html += '<div class="date">${Utility.format_date(entry.modified)}</div>'
html += '</div>'
}
}
html += '</div>'
return html, '<span class="meta-item"><b>${dir_count}</b> directories</span><span class="meta-item"><b>${file_count}</b> files</span><span class="meta-item"><b>${Utility.format_size(total_size)}</b> total</span>'
}

View File

@@ -1,5 +1,5 @@
Module { Module {
name: 'CDN' name: 'app'
description: '' description: ''
version: '0.0.1' version: '0.0.1'
license: 'MIT' license: 'MIT'

View File

@@ -1,15 +1,11 @@
services: services:
app: app:
build:
context: ./app
dockerfile: Dockerfile
container_name: cdn_web container_name: cdn_web
depends_on: depends_on:
- db - db
ports: ports:
- "8080:8080" - "8080:8080" // how do these get passed to my exe?, etc
environment: environment:
# env shee
DB_HOST: db DB_HOST: db
DB_USER: appuser DB_USER: appuser
DB_PASS: s3cret DB_PASS: s3cret