Merge pull request 'vorgang-via-url' (#9) from vorgang-via-url into development

Reviewed-on: #9
This commit was merged in pull request #9.
This commit is contained in:
2025-06-19 16:20:41 +02:00
12 changed files with 149 additions and 184 deletions

View File

@@ -8,3 +8,5 @@ import config from '$lib/config';
export const client = new Client(config.minio); export const client = new Client(config.minio);
export const BUCKET = 'tatort'; export const BUCKET = 'tatort';
export const TOKENFILENAME = '__perm__';
export const CONFIGFILENAME = 'config.json';

View File

@@ -1,6 +1,5 @@
import { BUCKET, client } from '$lib/minio'; import { BUCKET, client } from '$lib/minio';
export const checkIfExactDirectoryExists = (dir: string): Promise<boolean> => { export const checkIfExactDirectoryExists = (dir: string): Promise<boolean> => {
return new Promise<boolean>((resolve, reject) => { return new Promise<boolean>((resolve, reject) => {
const prefix = dir.endsWith('/') ? dir : `${dir}/`; const prefix = dir.endsWith('/') ? dir : `${dir}/`;
@@ -18,4 +17,11 @@ export const checkIfExactDirectoryExists = (dir: string): Promise<boolean> => {
stream.on('end', () => resolve(false)); stream.on('end', () => resolve(false));
}); });
} };
export const getContentofTextObject = async (bucket: string, objPath: string) => {
const res = await client.getObject(bucket, objPath);
const text = await new Response(res).text();
return text;
};

View File

@@ -1,17 +1,49 @@
import { fail, redirect } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { BUCKET, client } from '$lib/minio'; import { BUCKET, client, CONFIGFILENAME, TOKENFILENAME } from '$lib/minio';
import { checkIfExactDirectoryExists } from './s3ClientService'; import { checkIfExactDirectoryExists, getContentofTextObject } from './s3ClientService';
/** /**
* Checks if Vorgang exists and token is valid. * Get Vorgang and corresponend list of tatorte
* @param request * @param caseId
* @returns redirect to /list/caseId or error * @returns
*/ */
export const redirectIfVorgangExists = async (request: Request) => { export const getVorgangByCaseId = async (caseId: string) => {
const data = await request.formData(); const prefix = `${caseId}/`;
const caseId = data.get('case-id');
const caseToken = data.get('case-token');
const stream = client.listObjectsV2(BUCKET, prefix, false, '');
const list = [];
for await (const chunk of stream) {
const splittedNameParts = chunk.name.split('/');
const prefix = splittedNameParts[0];
const name = splittedNameParts[1];
if (name === CONFIGFILENAME || name === TOKENFILENAME) continue;
list.push({ ...chunk, name: name, prefix: prefix, show_button: true });
}
return list;
};
export const getListOfVorgänge = async () => {
const stream = client.listObjectsV2(BUCKET, '', false, '');
const list = [];
for await (const chunk of stream) {
const objPath = `${chunk.prefix}${TOKENFILENAME}`;
const token = await getContentofTextObject(BUCKET, objPath);
const cleanedChunkPrefix = chunk.prefix.replace(/\/$/, '');
list.push({ name: cleanedChunkPrefix, token: token });
}
return list;
};
/**
* Checks if Vorgang exists
* @param request
* @returns fail or true
*/
export const checkIfVorgangExists = async (caseId: string) => {
if (!caseId) { if (!caseId) {
return fail(400, { return fail(400, {
success: false, success: false,
@@ -28,9 +60,24 @@ export const redirectIfVorgangExists = async (request: Request) => {
}); });
} }
const isTokenValid = await hasValidToken(caseId, caseToken); return true;
};
if (!isTokenValid) { export const hasValidToken = async (caseId: string, caseToken: string) => {
const objPath = `${caseId}/${TOKENFILENAME}`;
try {
if (!caseToken) {
return fail(400, {
success: false,
caseId,
error: { message: 'Bitte Zugangscode eingeben!' }
});
}
const token = await getContentofTextObject(BUCKET, objPath);
if (!token || token !== caseToken) {
return fail(400, { return fail(400, {
success: false, success: false,
caseId, caseId,
@@ -38,56 +85,7 @@ export const redirectIfVorgangExists = async (request: Request) => {
}); });
} }
redirect(303, `/list/${caseId}`); return true;
};
export const getVorgangByCaseId = ({ params }) => {
const prefix = params.vorgang ? `${params.vorgang}/` : '';
const stream = client.listObjectsV2(BUCKET, prefix, false, '');
const result = new ReadableStream({
start(controller) {
stream.on('data', (data) => {
if (prefix === '') {
if (data.prefix)
controller.enqueue(`${JSON.stringify({ ...data, name: data.prefix.slice(0, -1) })}\n`);
return;
}
const name = data.name.slice(prefix.length);
if (name === 'config.json') return;
// zugangscode datei
if (name === '__perm__') return;
controller.enqueue(`${JSON.stringify({ ...data, name, prefix })}\n`);
});
stream.on('end', () => {
controller.close();
});
},
cancel() {
stream.destroy();
}
});
return new Response(result, {
headers: {
'content-type': 'text/event-stream'
}
});
};
const hasValidToken = async (caseId: string, caseToken: string) => {
const tokenFileName = '__perm__';
const objPath = `${caseId}/${tokenFileName}`;
try {
if (!caseToken) return false;
const res = await client.getObject('tatort', objPath);
const savedToken = await new Response(res).text();
return savedToken === caseToken ? true : false;
} catch (error) { } catch (error) {
if (error.name == 'S3Error') { if (error.name == 'S3Error') {
console.log(error); console.log(error);

View File

@@ -0,0 +1,10 @@
import { getListOfVorgänge } from '$lib/server/vorgangService';
import type { PageServerLoad } from '../../(token-based)/view/$types';
export const load: PageServerLoad = async () => {
const caseList = await getListOfVorgänge();
return {
caseList
};
};

View File

@@ -1,34 +1,11 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte';
import Trash from '$lib/icons/Trash.svelte'; import Trash from '$lib/icons/Trash.svelte';
import Folder from '$lib/icons/Folder.svelte'; import Folder from '$lib/icons/Folder.svelte';
import type { PageData } from '../$types';
/** export let data: PageData;
* @type any[]
*/
let list: any[] = [];
//$: list;
onMount(async () => { const caseList = data.caseList;
const response = await fetch('/api/list');
const stream = await response.body;
if (!stream) return;
const reader = stream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) return;
const objs = new TextDecoder()
.decode(value)
.split('\n')
.filter((i) => i.length > 0)
.map((i) => JSON.parse(i));
list = list.concat(objs);
}
});
async function delete_item(ev: Event) { async function delete_item(ev: Event) {
let delete_item = window.confirm('Bist du sicher?'); let delete_item = window.confirm('Bist du sicher?');
@@ -67,9 +44,9 @@
</div> </div>
<div class="mx-auto flex justify-center max-w-7xl h-full"> <div class="mx-auto flex justify-center max-w-7xl h-full">
<ul role="list" class="divide-y divide-gray-100"> <ul role="list" class="divide-y divide-gray-100">
{#each list as item} {#each caseList as item}
<li> <li>
<a href="/list/{item.name}" class="flex justify-between gap-x-6 py-5"> <a href="/list/{item.name}?token={item.token}" class="flex justify-between gap-x-6 py-5">
<div class="flex gap-x-4"> <div class="flex gap-x-4">
<!-- Ordner --> <!-- Ordner -->
<Folder /> <Folder />

View File

@@ -0,0 +1,28 @@
import { checkIfVorgangExists } from '$lib/server/vorgangService';
import { hasValidToken } from '$lib/server/vorgangService';
import { getVorgangByCaseId } from '$lib/server/vorgangService';
import type { PageServerLoad } from '../../view/$types';
export const load: PageServerLoad = async ({ params, url }) => {
const caseId = params.vorgang;
const caseToken = url.searchParams.get('token');
const isVorgangValid = await checkIfVorgangExists(caseId);
if (isVorgangValid !== true) {
return {
error: 'Vorgang wurde nicht gefunden.'
};
}
const isTokenValid = await hasValidToken(caseId, caseToken);
if (isTokenValid !== true) {
return {
error: 'Zugriffscode ist ungültig.'
};
}
const crimesList = await getVorgangByCaseId(caseId);
return {
crimesList
};
};

View File

@@ -1,5 +1,4 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte';
import shortenFileSize from '$lib/helper/shortenFileSize'; import shortenFileSize from '$lib/helper/shortenFileSize';
import { page } from '$app/stores'; import { page } from '$app/stores';
@@ -27,8 +26,7 @@
// add other properties as needed // add other properties as needed
} }
let list: ListItem[] = []; const crimesList: ListItem[] = data.crimesList;
$: list;
let open = false; let open = false;
$: open; $: open;
@@ -40,38 +38,12 @@
let rename_input; let rename_input;
$: rename_input; $: rename_input;
onMount(async () => {
const response = await fetch('/api/list/' + $page.params.vorgang);
const stream = response.body;
if (!stream) return;
const reader = stream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) return;
const objs = new TextDecoder()
.decode(value)
.split('\n')
.filter((i) => i.length > 0)
.map((i) => JSON.parse(i));
list = list.concat(objs);
list = list.map((item) => {
item.show_button = true;
return item;
});
}
});
function uploadSuccessful() { function uploadSuccessful() {
open = false; open = false;
} }
function defocus_element(i: number) { function defocus_element(i: number) {
let item = list[i]; let item = crimesList[i];
let text_field_id = `label__${item.name}`; let text_field_id = `label__${item.name}`;
let text_field = document.getElementById(text_field_id); let text_field = document.getElementById(text_field_id);
@@ -81,12 +53,12 @@
} }
// reshow button // reshow button
list[i].show_button = true; crimesList[i].show_button = true;
return; return;
} }
async function handle_input(ev: KeyboardEvent, i: number) { async function handle_input(ev: KeyboardEvent, i: number) {
let item = list[i]; let item = crimesList[i];
if (ev.key == 'Escape') { if (ev.key == 'Escape') {
let text_field_id = `label__${item.name}`; let text_field_id = `label__${item.name}`;
@@ -163,7 +135,7 @@
</div> </div>
<div class="mx-auto flex justify-center max-w-7xl h-full"> <div class="mx-auto flex justify-center max-w-7xl h-full">
<ul class="divide-y divide-gray-100"> <ul class="divide-y divide-gray-100">
{#each list as item, i} {#each crimesList as item, i}
<li> <li>
<a <a
href="/view/{$page.params.vorgang}/{item.name}" href="/view/{$page.params.vorgang}/{item.name}"
@@ -191,20 +163,6 @@
}}>{item.name}</span }}>{item.name}</span
> >
<!--<input
class="text-sm font-semibold leading-6 text-gray-900 inline-block min-w-1"
type="text"
name=""
on:keydown|stopPropagation={// event needed to identify ID
// TO-DO: check if event is needed or if index is sufficient
async (ev) => {
handle_input(ev, i);
}}
bind:value={item.name}
id="label__{item.name}"
/>-->
<!-- disabled={item.show_button} -->
<!-- https://iconduck.com/icons/192863/edit-rename -->
{#if item.show_button} {#if item.show_button}
<button <button
@@ -306,6 +264,12 @@
</Modal> </Modal>
</div> </div>
{#if data.error}
<div class="max-w-xl mx-auto bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mt-4">
<strong class="font-bold">Fehler: </strong>
<span class="block sm:inline">{data.error}</span>
</div>
{/if}
<style> <style>
ul { ul {
min-width: 24rem; min-width: 24rem;

View File

@@ -1,6 +1,12 @@
import { redirectIfVorgangExists } from '$lib/server/vorgangService'; import { redirect } from '@sveltejs/kit';
/** @type {import('./$types').Actions} */ /** @type {import('./$types').Actions} */
export const actions = { export const actions = {
default: async ({request}: {request: Request}) => redirectIfVorgangExists(request) default: async ({request}: {request: Request}) => {
const data = await request.formData();
const caseId = data.get('case-id');
const caseToken = data.get('case-token');
if( caseId && caseToken) throw redirect(303, `/list/${caseId}?token=${caseToken}`);
}
} }

View File

@@ -2,7 +2,6 @@
import BaseInputField from '$lib/components/BaseInputField.svelte'; import BaseInputField from '$lib/components/BaseInputField.svelte';
import Button from '$lib/components/Button.svelte'; import Button from '$lib/components/Button.svelte';
import ArrowRight from '$lib/icons/Arrow-right.svelte'; import ArrowRight from '$lib/icons/Arrow-right.svelte';
import Exclamation from '$lib/icons/Exclamation.svelte';
export let form; export let form;
</script> </script>

View File

@@ -1,9 +1,20 @@
import { loginUser, logoutUser } from '$lib/server/authService'; import { loginUser, logoutUser } from '$lib/server/authService';
import { redirectIfVorgangExists } from '$lib/server/vorgangService.js'; import { checkIfVorgangExists, hasValidToken } from '$lib/server/vorgangService.js';
import { redirect } from '@sveltejs/kit';
export const actions = { export const actions = {
login: ({ request, cookies }) => loginUser({request, cookies}), login: ({ request, cookies }) => loginUser({ request, cookies }),
logout: (event) => logoutUser(event), logout: (event) => logoutUser(event),
redirectToVorgang: ({request}) => redirectIfVorgangExists(request) getVorgangById: async ({ request }) => {
const data = await request.formData();
const caseId = data.get('case-id');
const caseToken = data.get('case-token');
const isVorgangValid = await checkIfVorgangExists(caseId);
if (isVorgangValid !== true) return isVorgangValid;
const isTokenValid = await hasValidToken(caseId, caseToken);
if ( isTokenValid !== true) return isTokenValid;
throw redirect(303, `/list/${caseId}?token=${caseToken}`);
}
} as const; } as const;

View File

@@ -24,7 +24,7 @@
<div class="w-full max-w-sm mx-auto"> <div class="w-full max-w-sm mx-auto">
<div class="relative mt-5 bg-gray-50 rounded-xl shadow-xl p-3 pt-1"> <div class="relative mt-5 bg-gray-50 rounded-xl shadow-xl p-3 pt-1">
<div class="mt-10"> <div class="mt-10">
<form action="?/redirectToVorgang" method="POST"> <form action="?/getVorgangById" method="POST">
<BaseInputField <BaseInputField
id="case-id" id="case-id"
name="case-id" name="case-id"

View File

@@ -1,41 +1,5 @@
import { client } from '$lib/minio'; import { client } from '$lib/minio';
/** @type {import('./$types').RequestHandler} */
export async function GET({ params }) {
const prefix = params.vorgang ? `${params.vorgang}/` : '';
const stream = client.listObjectsV2('tatort', prefix, false, '');
const result = new ReadableStream({
start(controller) {
stream.on('data', (data) => {
if (prefix === '') {
if (data.prefix)
controller.enqueue(`${JSON.stringify({ ...data, name: data.prefix.slice(0, -1) })}\n`);
return;
}
const name = data.name.slice(prefix.length);
if (name === 'config.json') return;
// zugangscode datei
if (name === '__perm__') return;
controller.enqueue(`${JSON.stringify({ ...data, name, prefix })}\n`);
});
stream.on('end', () => {
controller.close();
});
},
cancel() {
stream.destroy();
}
});
return new Response(result, {
headers: {
'content-type': 'text/event-stream'
}
});
}
export async function DELETE({ params }) { export async function DELETE({ params }) {
const vorgang = params.vorgang; const vorgang = params.vorgang;