📚 The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
New ressources parents
Smaug6739e9676027000f
diff --git a/backend/controllers/ressources.controller.go b/backend/controllers/ressources.controller.goindex 54e31a91..9617ac2f 100644--- a/backend/controllers/ressources.controller.go+++ b/backend/controllers/ressources.controller.go@@ -25,6 +25,7 @@ type RessourceController interface {GetBackup(c *gin.Context) (int, any)UploadFile(c *gin.Context) (int, any)UploadAvatar(c *gin.Context) (int, any)+ UpdateUpload(c *gin.Context) (int, any)DeleteUpload(c *gin.Context) (int, any)}@@ -146,6 +147,7 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {Filetype: mimeType,OriginalPath: header.Filename,TransformedPath: fmt.Sprintf("%d%s", id, ext),+ ParentId: nil,AuthorId: userId,CreatedTimestamp: time.Now().UnixMilli(),}@@ -207,6 +209,57 @@ func (ctr *Controller) UploadAvatar(c *gin.Context) (int, any) {return http.StatusOK, "File uploaded successfully"}+// UpdateUpload+// @Summary Update an upload (only metadata)+// @Method PUT+// @Router /uploads/{id} [put]+// @Security Authenfification: Auth+// @Param id path string true "ID of the upload to update"+// @Param upload body models.Ressource true "Upload data"+// @Success 200 {object} Success(models.Ressource)+// @Failure 400 {object} Error+// @Failure 401 {object} Error+func (ctr *Controller) UpdateUpload(c *gin.Context) (int, any) {+ id, err := utils.GetIdParam(c, c.Param("id"))+ if err != nil {+ return http.StatusBadRequest, errors.New("invalid id format")+ }+ db_ressource, err := ctr.app.Services.Ressource.GetRessourceById(id)+ if err != nil {+ return http.StatusInternalServerError, "failed to get ressource"+ }+ if db_ressource == nil {+ return http.StatusBadRequest, errors.New("ressource not found")+ }+ err = utils.RessourceAccess(c, db_ressource.AuthorId)+ if err != nil {+ return http.StatusUnauthorized, err+ }++ var updatedRessource *models.Ressource+ if err := c.ShouldBindJSON(&updatedRessource); err != nil {+ return http.StatusBadRequest, errors.New("failed to bind JSON")+ }+ updatedRessource = &models.Ressource{+ Id: db_ressource.Id,+ Filename: updatedRessource.Filename,+ Filesize: db_ressource.Filesize,+ Filetype: db_ressource.Filetype,+ OriginalPath: db_ressource.OriginalPath,+ TransformedPath: db_ressource.TransformedPath,+ ParentId: updatedRessource.ParentId,+ AuthorId: db_ressource.AuthorId,+ CreatedTimestamp: db_ressource.CreatedTimestamp,+ }++ _, err = ctr.app.Services.Ressource.UpdateRessource(updatedRessource)+ if err != nil {+ return http.StatusInternalServerError, errors.New("failed to update ressource")+ }++ return http.StatusOK, updatedRessource+}+// DeleteUpload// @Summary Delete an upload// @Method DELETEdiff --git a/backend/migrations/000005_ressource_parent.down.sql b/backend/migrations/000005_ressource_parent.down.sqlnew file mode 100644index 00000000..e69de29bdiff --git a/backend/migrations/000005_ressource_parent.up.sql b/backend/migrations/000005_ressource_parent.up.sqlnew file mode 100644index 00000000..b2df0c92--- /dev/null+++ b/backend/migrations/000005_ressource_parent.up.sql@@ -0,0 +1,7 @@+alter table ressources+ add parent_id bigint UNSIGNED null after transformed_path;++alter table ressources+ add constraint ressources_documents_id_fk+ foreign key (parent_id) references documents (id);+diff --git a/backend/models/ressource.model.go b/backend/models/ressource.model.goindex d1c13822..67c3dc66 100644--- a/backend/models/ressource.model.go+++ b/backend/models/ressource.model.go@@ -3,12 +3,13 @@ package modelsimport "alexandrie/types"type Ressource struct {- Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`- Filename string `json:"filename" form:"filename" binding:"required,max=50"`- Filesize int64 `json:"filesize" form:"filesize" binding:"omitempty"`- Filetype string `json:"filetype" form:"filetype" binding:"omitempty"`- OriginalPath string `json:"original_path" form:"original_path" binding:"omitempty"`- TransformedPath string `json:"transformed_path" form:"transformed_path" binding:"omitempty"`- AuthorId types.Snowflake `json:"author_id" form:"author_id" binding:"omitempty"`- CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`+ Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`+ Filename string `json:"filename" form:"filename" binding:"required,max=50"`+ Filesize int64 `json:"filesize" form:"filesize" binding:"omitempty"`+ Filetype string `json:"filetype" form:"filetype" binding:"omitempty"`+ OriginalPath string `json:"original_path" form:"original_path" binding:"omitempty"`+ TransformedPath string `json:"transformed_path" form:"transformed_path" binding:"omitempty"`+ ParentId *types.Snowflake `json:"parent_id" form:"parent_id" binding:"omitempty"`+ AuthorId types.Snowflake `json:"author_id" form:"author_id" binding:"omitempty"`+ CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`}diff --git a/backend/router/routes/ressources.go b/backend/router/routes/ressources.goindex 7851d837..f3b3b1a1 100644--- a/backend/router/routes/ressources.go+++ b/backend/router/routes/ressources.go@@ -18,5 +18,6 @@ func Uploads(app *app.App, router *gin.RouterGroup) {ressources.GET(("/backup"), utils.WP(ressourcesCtrl.GetBackup))ressources.POST("", utils.WP(ressourcesCtrl.UploadFile))ressources.POST("/avatar", utils.WP(ressourcesCtrl.UploadAvatar))+ ressources.PUT("/:id", utils.WP(ressourcesCtrl.UpdateUpload))ressources.DELETE("/:id", utils.WP(ressourcesCtrl.DeleteUpload))}diff --git a/backend/services/ressource.service.go b/backend/services/ressource.service.goindex eb042ba0..d7382192 100644--- a/backend/services/ressource.service.go+++ b/backend/services/ressource.service.go@@ -4,6 +4,7 @@ import ("alexandrie/models""alexandrie/types""database/sql"+ "fmt")type RessourceService interface {@@ -11,6 +12,7 @@ type RessourceService interface {GetRessourceById(id types.Snowflake) (*models.Ressource, error)GetUserUploadsSize(userId types.Snowflake) (int64, error)CreateRessource(ressource *models.Ressource) (*models.Ressource, error)+ UpdateRessource(ressource *models.Ressource) (*models.Ressource, error)DeleteRessource(id types.Snowflake) error}@@ -28,7 +30,7 @@ func (s *Service) GetAllUploadsByUserId(userId types.Snowflake) ([]*models.Ressofor rows.Next() {var ressource models.Ressource- if err := rows.Scan(&ressource.Id, &ressource.Filename, &ressource.Filesize, &ressource.Filetype, &ressource.OriginalPath, &ressource.TransformedPath, &ressource.AuthorId, &ressource.CreatedTimestamp); err != nil {+ if err := rows.Scan(&ressource.Id, &ressource.Filename, &ressource.Filesize, &ressource.Filetype, &ressource.OriginalPath, &ressource.TransformedPath, &ressource.ParentId, &ressource.AuthorId, &ressource.CreatedTimestamp); err != nil {return nil, err}ressources = append(ressources, &ressource)@@ -38,7 +40,7 @@ func (s *Service) GetAllUploadsByUserId(userId types.Snowflake) ([]*models.Ressofunc (s *Service) GetRessourceById(id types.Snowflake) (*models.Ressource, error) {var ressource models.Ressource- err := s.db.QueryRow("SELECT * FROM ressources WHERE id = ?", id).Scan(&ressource.Id, &ressource.Filename, &ressource.Filesize, &ressource.Filetype, &ressource.OriginalPath, &ressource.TransformedPath, &ressource.AuthorId, &ressource.CreatedTimestamp)+ err := s.db.QueryRow("SELECT * FROM ressources WHERE id = ?", id).Scan(&ressource.Id, &ressource.Filename, &ressource.Filesize, &ressource.Filetype, &ressource.OriginalPath, &ressource.TransformedPath, &ressource.ParentId, &ressource.AuthorId, &ressource.CreatedTimestamp)if err != nil {return nil, err}@@ -58,13 +60,22 @@ func (s *Service) GetUserUploadsSize(userId types.Snowflake) (int64, error) {}func (s *Service) CreateRessource(ressource *models.Ressource) (*models.Ressource, error) {- _, err := s.db.Exec("INSERT INTO ressources (id, filename, file_size, file_type, original_path, transformed_path, author_id, created_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ressource.Id, ressource.Filename, ressource.Filesize, ressource.Filetype, ressource.OriginalPath, ressource.TransformedPath, ressource.AuthorId, ressource.CreatedTimestamp)+ _, err := s.db.Exec("INSERT INTO ressources (id, filename, file_size, file_type, original_path, transformed_path, parent_id, author_id, created_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ressource.Id, ressource.Filename, ressource.Filesize, ressource.Filetype, ressource.OriginalPath, ressource.TransformedPath, ressource.ParentId, ressource.AuthorId, ressource.CreatedTimestamp)if err != nil {return nil, err}return ressource, nil}+func (s *Service) UpdateRessource(ressource *models.Ressource) (*models.Ressource, error) {+ _, err := s.db.Exec("UPDATE ressources SET filename = ?, file_size = ?, file_type = ?, original_path = ?, transformed_path = ?, parent_id = ?, author_id = ?, created_timestamp = ? WHERE id = ?", ressource.Filename, ressource.Filesize, ressource.Filetype, ressource.OriginalPath, ressource.TransformedPath, ressource.ParentId, ressource.AuthorId, ressource.CreatedTimestamp, ressource.Id)+ if err != nil {+ fmt.Println(err)+ return nil, err+ }+ return ressource, nil+}+func (s *Service) DeleteRessource(id types.Snowflake) error {_, err := s.db.Exec("DELETE FROM ressources WHERE id = ?", id)return errdiff --git a/frontend/components/AppSelect.vue b/frontend/components/AppSelect.vueindex a8e22cfa..c94af9a2 100644--- a/frontend/components/AppSelect.vue+++ b/frontend/components/AppSelect.vue@@ -1,23 +1,34 @@<template><div class="category-select" :style="{ width: size || '100%' }">- <button @click="toggleDropdown">{{ selected?.label || placeholder }}</button>- <div v-if="open" class="dropdown">- <ul>- <AppSelectNode v-for="item in items" :key="item.id" :node="item" :level="0" @select="handleSelect" />- </ul>+ <div v-if="!open">+ <button @click="toggleDropdown">{{ selected?.label || placeholder }}</button>+ </div>+ <div v-else>+ <input type="text" v-model="search" placeholder="Search..." class="search-input" ref="searchInput" @blur="handleBlur" @keydown="handleKeyDown" />+ <div class="dropdown">+ <ul>+ <AppSelectNode v-for="item in filteredItems" :key="item.id" :node="item" :level="0" @select="handleSelect" />+ </ul>+ </div></div></div></template><script setup lang="ts">+import { nextTick } from 'vue';+const props = defineProps<{items: ANode[];placeholder?: string;modelValue?: string | number;size?: string;}>();+const selectedId = ref<string | number>(props.modelValue || '');const open = ref(false);+const search = ref('');+const searchInput = ref<HTMLInputElement | null>(null);+const emit = defineEmits(['update:modelValue']);const selected = computed(() => {@@ -34,15 +45,59 @@ const selected = computed(() => {return findSelected(props.items);});+const filteredItems = computed(() => {+ if (!search.value.trim()) return props.items;++ const filterRecursive = (items: ANode[]): ANode[] => {+ return items+ .map(item => {+ const matches = item.label.toLowerCase().includes(search.value.toLowerCase());+ const filteredChildren = item.childrens ? filterRecursive(item.childrens) : [];+ if (matches || filteredChildren.length > 0) {+ return { ...item, childrens: filteredChildren };+ }+ return null;+ })+ .filter(Boolean) as ANode[];+ };++ return filterRecursive(props.items);+});+function toggleDropdown() {- open.value = !open.value;+ open.value = true;+ search.value = '';+ nextTick(() => {+ searchInput.value?.focus();+ });+}+function handleKeyDown(event: KeyboardEvent) {+ if (event.key === 'Escape') {+ open.value = false;+ } else if (event.key === 'Enter') {+ // Optionnel : sélectionner si 1 seul résultat ?+ const firstItem = filteredItems.value[0];+ if (firstItem) {+ handleSelect(firstItem);+ }+ }+ // Ne PAS fermer sur Tab}-function handleSelect(node: Item) {+function handleSelect(node: ANode) {selectedId.value = node.id;emit('update:modelValue', node.id);open.value = false;}++function handleBlur(event: FocusEvent) {+ setTimeout(() => {+ const relatedTarget = (event.relatedTarget || document.activeElement) as HTMLElement;+ if (!relatedTarget?.closest('.category-select')) {+ open.value = false;+ }+ }, 100);+}</script><style scoped lang="scss">@@ -51,21 +106,27 @@ function handleSelect(node: Item) {width: 200px;}-button {+button,+.search-input {width: 100%;- padding: 6px 12px;+ padding: 8px 10px;border: 1px solid #ccc;background: white;text-align: left;border-radius: 6px;+ font-size: 15px;cursor: pointer;- padding: 8px 10px;- // ouline like input with focus or opened&:focus {outline: 2px solid #000;}}-.category-select:has(.dropdown) button {++.search-input {+ cursor: text;+}++.category-select:has(.dropdown) button,+.category-select:has(.dropdown) .search-input {outline: 2px solid #000;}diff --git a/frontend/components/AppSelectNode.vue b/frontend/components/AppSelectNode.vueindex eeec857f..8b983d0f 100644--- a/frontend/components/AppSelectNode.vue+++ b/frontend/components/AppSelectNode.vue@@ -31,6 +31,9 @@ function select() {background: none;border: none;cursor: pointer;+ font-size: 15px;+ width: 99%;+ margin: 0 auto;}.tree-node:hover {diff --git a/frontend/composables/utils.ts b/frontend/composables/utils.tsindex b7645740..fe600f82 100644--- a/frontend/composables/utils.ts+++ b/frontend/composables/utils.ts@@ -16,3 +16,8 @@ export const AppColors = ['', 'blue', 'red', 'green', 'yellow', 'purple', 'pink'export function getAppColor(index: number = 0): string {return AppColors[index % AppColors.length] || '';}++export const readableFileSize = (size: number): string => {+ const i = Math.floor(Math.log(size) / Math.log(1024));+ return `${(size / Math.pow(1024, i)).toFixed(2)} ${['B', 'kB', 'MB', 'GB', 'TB'][i]}`;+};diff --git a/frontend/pages/dashboard/cdn.vue b/frontend/pages/dashboard/cdn.vueindex fd249c88..1fe7f232 100644--- a/frontend/pages/dashboard/cdn.vue+++ b/frontend/pages/dashboard/cdn.vue@@ -1,189 +1,8 @@<template>- <div class="card-component">- <h2 style="margin: 0">CDN: File manager</h2>- <div class="dropzone" :class="{ 'drag-over': isDragOver }" @dragover.prevent @drop.prevent="handleFileDrop" @dragenter.prevent="dragEnter" @dragleave.prevent="dragLeave">- <input type="file" ref="fileInput" @change="handleFileSelect" />- <div v-if="selectedFile" class="file-info">- <span>{{ selectedFile.name }}</span>- <div class="file-size">{{ readableFileSize(selectedFile.size) }}</div>- </div>- <div v-else>Drop file here or <span class="clickable" @click="triggerFileSelect">click to select from computer</span>.</div>- </div>- <AppButton @click="submitFile" type="primary" :disabled="!selectedFile">Upload on server</AppButton>- <div v-if="isLoading" class="loading-spinner"></div>- <div v-if="fileLink" class="link-section">- <input type="text" v-model="fileLink" readonly />- <AppButton @click="copyLink" type="primary">Copy link</AppButton>- </div>- <div v-if="ressourcesStore.ressources.length" class="ressources-list">- <DataTable :headers="headers" :rows="rows">- <template #action="{ cell }">- <a :href="`${CDN}/${cell?.data.author_id}/${cell?.data.transformed_path || cell?.data.original_path}`" target="_blank"><Icon name="view" /> </a>- <Icon name="delete" @click="() => deleteRessource(cell?.data.id)" />- </template>- </DataTable>- </div>- <div v-else>No ressource found.</div>- </div>+ <NuxtPage /></template>-<script setup lang="ts">-import type { DB_Ressource } from '~/stores';--const ressourcesStore = useRessourcesStore();-ressourcesStore.fetch();-const selectedFile: Ref<File | null | undefined> = ref(null);-const isDragOver = ref(false);-const fileLink = ref('');-const fileInput: Ref<HTMLInputElement | null> = ref(null);-const isLoading = ref(false);-const triggerFileSelect = () => fileInput.value!.click();-const handleFileSelect = (event: Event) => (selectedFile.value = (event.target as HTMLInputElement | null)?.files?.[0] || null);+<script setup lang="ts">definePageMeta({ breadcrumb: 'CDN' });--const handleFileDrop = (event: DragEvent) => {- if (event.dataTransfer?.files && event.dataTransfer.files.length > 0) {- selectedFile.value = event.dataTransfer.files[0];- isDragOver.value = false;- }-};--const copyLink = () => navigator.clipboard.writeText(fileLink.value!);-const dragEnter = () => (isDragOver.value = true);-const dragLeave = () => (isDragOver.value = false);--const submitFile = async () => {- if (!selectedFile.value) return;- isLoading.value = true;-- const body = new FormData();- body.append('file', selectedFile.value);- selectedFile.value = null; // Reset selected file-- await ressourcesStore- .post(body)- .then(r => (fileLink.value = `${CDN}/${(r as DB_Ressource).author_id}/${(r as DB_Ressource).transformed_path}`))- .catch(e => useNotifications().add({ type: 'error', title: 'Error', message: e }))- .finally(() => (isLoading.value = false));-};--const readableFileSize = (size: number): string => {- const i = Math.floor(Math.log(size) / Math.log(1024));- return `${(size / Math.pow(1024, i)).toFixed(2)} ${['B', 'kB', 'MB', 'GB', 'TB'][i]}`;-};--const headers = [- { label: 'Name', key: 'name' },- { label: 'Size', key: 'size' },- { label: 'Type', key: 'type' },- { label: 'Date', key: 'date' },- { label: 'Action', key: 'action' },-];-const color = (type: string) => (type.includes('image') ? 'green' : type.includes('video') ? 'blue' : type.includes('pdf') ? 'yellow' : 'red');-const rows: any = computed(() =>- ressourcesStore.ressources.map(res => {- return {- name: { content: res.filename },- size: { content: readableFileSize(res.filesize) },- type: { content: `<tag class="${color(res.filetype)}">${res.filetype}</tag>`, type: 'html' },- date: { content: new Date(res.created_timestamp).toLocaleDateString() },- action: { type: 'slot', data: res },- };- }),-);--const deleteRessource = async (id: string) => {- if (!id) return;- await ressourcesStore- .delete(id)- .then(() => useNotifications().add({ type: 'success', title: 'Ressource deleted successfully' }))- .catch(e => useNotifications().add({ type: 'error', title: 'Error', message: e }));-};+useRessourcesStore().fetch();</script>--<style scoped lang="scss">-.dropzone {- display: flex;- align-items: center;- justify-content: center;- width: 100%;- height: 150px;- border: 2px dashed #9e9e9e;- border-radius: 4px;- font-size: 14px;- color: #9e9e9e;- position: relative;- transition: background-color $transition-duration;- background-color: var(--dropzone-bg, transparent);-- &:hover {- background-color: var(--bg-contrast);- }-- input[type='file'] {- display: none;- }-}--.drag-over {- background-color: #e3f2fd;- border-color: #2196f3;- transition: background-color $transition-duration, border-color $transition-duration;-}--.file-info {- display: flex;- flex-direction: column;- align-items: center;- color: #2196f3;- color: #2196f3;-- .file-size {- font-size: 0.8rem;- color: #757575;- margin-top: 5px;- }-}--.link-section {- margin-top: 15px;- display: flex;- gap: 10px;- width: 100%;- display: flex;- flex-direction: column;-}--.loading-spinner {- border: 5px solid #f3f3f3;- border-top: 5px solid $primary-color;- border-radius: 50%;- width: 50px;- height: 50px;- animation: spin 1s linear infinite;-}--.clickable {- color: #2196f3;- cursor: pointer;- text-decoration: underline;-}--.ressources-list {- width: 100%;-}--@keyframes spin {- 0% {- transform: rotate(0deg);- }-- 100% {- transform: rotate(360deg);- }-}--.file-info {- color: #2196f3;-}-</style>diff --git a/frontend/pages/dashboard/cdn/[id].vue b/frontend/pages/dashboard/cdn/[id].vuenew file mode 100644index 00000000..04ac712c--- /dev/null+++ b/frontend/pages/dashboard/cdn/[id].vue@@ -0,0 +1,95 @@+<template>+ <div style="padding: 24px; gap: 16px" class="card-component">+ <header>+ <h2>Update ressource <tag blue>New</tag></h2>+ Manage ressources and files on the server. You can edit metadata and delete file from the server.+ </header>+ <form @submit.prevent v-if="ressource">+ <div class="form-row">+ <div class="form-column">+ <label>ID</label>+ <input type="text" :value="ressource.id" id="id" disabled />+ </div>+ <div class="form-column">+ <label>Size</label>+ <input type="text" :value="readableFileSize(ressource.filesize)" id="size" disabled />+ </div>+ </div>+ <label>Name</label>+ <input type="text" v-model="ressource.filename" id="name" required />+ <label style="display: flex; align-items: center">Parent <AppHint text="To organize your uploads" /></label>+ <AppSelect v-model="ressource.parent_id" :items="tree" placeholder="Select a ressource parent" />+ <label>Type</label>+ <input type="text" :value="ressource.filetype" id="id" disabled />+ <label>Original path</label>+ <input type="text" :value="ressource.original_path" id="original_path" disabled />+ <label>Path</label>+ <input type="text" :value="ressource.transformed_path" id="path" disabled />+ <p>+ Ressource: <a :href="`${CDN}/${ressource.author_id}/${ressource.transformed_path || ressource.original_path}`" target="_blank">{{ `${CDN}/${ressource.author_id}/${ressource.transformed_path || ressource.original_path}` }}</a>+ </p>+ <div style="display: flex; justify-content: flex-end">+ <AppButton type="primary" class="btn primary" @click="updateCategory">Update</AppButton>+ </div>+ </form>+ </div>+</template>++<script lang="ts" setup>+const ressourcesStore = useRessourcesStore();+const route = useRoute();+const ressource = computed(() => ressourcesStore.getById(route.params.id as string));+const defaultItem: ANode = {+ id: '',+ label: 'None',+ parent_id: '',+ childrens: [],+};+const tree = computed(() => [defaultItem, ...useSidebarTree().tree.value]);++definePageMeta({ breadcrumb: 'Edit' });++const updateCategory = async () => {+ if (ressource.value)+ ressourcesStore+ .update(ressource.value)+ .then(() => {+ useNotifications().add({ type: 'success', title: 'Ressource updated' });+ useRouter().push('/dashboard');+ })+ .catch(e => useNotifications().add({ type: 'error', title: 'Error', message: e }));+};+</script>++<style scoped lang="scss">+h2 {+ font-size: 26px;+}+label {+ margin-top: 10px;+}+.card-component {+ display: block;+ margin: 2px 0;+ width: 100%;+}+input,+textarea,+select {+ width: 100%;+}+.form-row {+ display: flex;+ gap: 20px;+ flex-wrap: wrap;+}++.form-column {+ flex: 1;+ min-width: 200px;+}+a {+ color: $primary-color;+ text-decoration: underline;+}+</style>diff --git a/frontend/pages/dashboard/cdn/index.vue b/frontend/pages/dashboard/cdn/index.vuenew file mode 100644index 00000000..23147305--- /dev/null+++ b/frontend/pages/dashboard/cdn/index.vue@@ -0,0 +1,184 @@+<template>+ <div class="card-component">+ <h2 style="margin: 0">CDN: File manager</h2>+ <div class="dropzone" :class="{ 'drag-over': isDragOver }" @dragover.prevent @drop.prevent="handleFileDrop" @dragenter.prevent="dragEnter" @dragleave.prevent="dragLeave">+ <input type="file" ref="fileInput" @change="handleFileSelect" />+ <div v-if="selectedFile" class="file-info">+ <span>{{ selectedFile.name }}</span>+ <div class="file-size">{{ readableFileSize(selectedFile.size) }}</div>+ </div>+ <div v-else>Drop file here or <span class="clickable" @click="triggerFileSelect">click to select from computer</span>.</div>+ </div>+ <AppButton @click="submitFile" type="primary" :disabled="!selectedFile">Upload on server</AppButton>+ <div v-if="isLoading" class="loading-spinner"></div>+ <div v-if="fileLink" class="link-section">+ <input type="text" v-model="fileLink" readonly />+ <AppButton @click="copyLink" type="primary">Copy link</AppButton>+ </div>+ <div v-if="ressourcesStore.ressources.length" class="ressources-list">+ <DataTable :headers="headers" :rows="rows">+ <template #action="{ cell }">+ <a :href="`${CDN}/${cell?.data.author_id}/${cell?.data.transformed_path || cell?.data.original_path}`" target="_blank" style="margin-right: 10px"><Icon name="view" /> </a>+ <NuxtLink :to="`/dashboard/cdn/${cell?.data.id}`"><Icon name="edit" style="margin-right: 10px" /></NuxtLink>+ <Icon name="delete" @click="() => deleteRessource(cell?.data.id)" />+ </template>+ </DataTable>+ </div>+ <div v-else>No ressource found.</div>+ </div>+</template>+<script setup lang="ts">+import type { DB_Ressource } from '~/stores';++const ressourcesStore = useRessourcesStore();++const selectedFile: Ref<File | null | undefined> = ref(null);+const isDragOver = ref(false);+const fileLink = ref('');+const fileInput: Ref<HTMLInputElement | null> = ref(null);+const isLoading = ref(false);+const triggerFileSelect = () => fileInput.value!.click();+const handleFileSelect = (event: Event) => (selectedFile.value = (event.target as HTMLInputElement | null)?.files?.[0] || null);+definePageMeta({ breadcrumb: 'Upload' });++const handleFileDrop = (event: DragEvent) => {+ if (event.dataTransfer?.files && event.dataTransfer.files.length > 0) {+ selectedFile.value = event.dataTransfer.files[0];+ isDragOver.value = false;+ }+};++const copyLink = () => navigator.clipboard.writeText(fileLink.value!);+const dragEnter = () => (isDragOver.value = true);+const dragLeave = () => (isDragOver.value = false);++const submitFile = async () => {+ if (!selectedFile.value) return;+ isLoading.value = true;++ const body = new FormData();+ body.append('file', selectedFile.value);+ selectedFile.value = null; // Reset selected file++ await ressourcesStore+ .post(body)+ .then(r => (fileLink.value = `${CDN}/${(r as DB_Ressource).author_id}/${(r as DB_Ressource).transformed_path}`))+ .catch(e => useNotifications().add({ type: 'error', title: 'Error', message: e }))+ .finally(() => (isLoading.value = false));+};++const headers = [+ { label: 'Name', key: 'name' },+ { label: 'Size', key: 'size' },+ { label: 'Type', key: 'type' },+ { label: 'Date', key: 'date' },+ { label: 'Action', key: 'action' },+];+const color = (type: string) => (type.includes('image') ? 'green' : type.includes('video') ? 'blue' : type.includes('pdf') ? 'yellow' : 'red');+const rows: any = computed(() =>+ ressourcesStore.ressources.map(res => {+ return {+ name: { content: res.filename },+ size: { content: readableFileSize(res.filesize) },+ type: { content: `<tag class="${color(res.filetype)}">${res.filetype}</tag>`, type: 'html' },+ date: { content: new Date(res.created_timestamp).toLocaleDateString() },+ action: { type: 'slot', data: res },+ };+ }),+);++const deleteRessource = async (id: string) => {+ if (!id) return;+ await ressourcesStore+ .delete(id)+ .then(() => useNotifications().add({ type: 'success', title: 'Ressource deleted successfully' }))+ .catch(e => useNotifications().add({ type: 'error', title: 'Error', message: e }));+};+</script>++<style scoped lang="scss">+.dropzone {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 100%;+ height: 150px;+ border: 2px dashed #9e9e9e;+ border-radius: 4px;+ font-size: 14px;+ color: #9e9e9e;+ position: relative;+ transition: background-color $transition-duration;+ background-color: var(--dropzone-bg, transparent);++ &:hover {+ background-color: var(--bg-contrast);+ }++ input[type='file'] {+ display: none;+ }+}++.drag-over {+ background-color: #e3f2fd;+ border-color: #2196f3;+ transition: background-color $transition-duration, border-color $transition-duration;+}++.file-info {+ display: flex;+ flex-direction: column;+ align-items: center;+ color: #2196f3;+ color: #2196f3;++ .file-size {+ font-size: 0.8rem;+ color: #757575;+ margin-top: 5px;+ }+}++.link-section {+ margin-top: 15px;+ display: flex;+ gap: 10px;+ width: 100%;+ display: flex;+ flex-direction: column;+}++.loading-spinner {+ border: 5px solid #f3f3f3;+ border-top: 5px solid $primary-color;+ border-radius: 50%;+ width: 50px;+ height: 50px;+ animation: spin 1s linear infinite;+}++.clickable {+ color: #2196f3;+ cursor: pointer;+ text-decoration: underline;+}++.ressources-list {+ width: 100%;+}++@keyframes spin {+ 0% {+ transform: rotate(0deg);+ }++ 100% {+ transform: rotate(360deg);+ }+}++.file-info {+ color: #2196f3;+}+</style>diff --git a/frontend/stores/db_strustures.d.ts b/frontend/stores/db_strustures.d.tsindex 202f46c3..ecb13a87 100644--- a/frontend/stores/db_strustures.d.ts+++ b/frontend/stores/db_strustures.d.ts@@ -59,6 +59,7 @@ export interface DB_Ressource {filetype: string;original_path: string;transformed_path: string;+ parent_id?: string;author_id: string;created_timestamp: string;}diff --git a/frontend/stores/ressources.store.ts b/frontend/stores/ressources.store.tsindex d87f6085..8c0bc46c 100644--- a/frontend/stores/ressources.store.ts+++ b/frontend/stores/ressources.store.ts@@ -7,6 +7,7 @@ export const useRessourcesStore = defineStore('ressources', {}),getters: {getAll: state => state.ressources,+ getById: state => (id: string) => state.ressources.find(c => c.id == id),},actions: {fetch: function () {@@ -36,6 +37,16 @@ export const useRessourcesStore = defineStore('ressources', {} else reject(request.message);});},+ update(ressource: DB_Ressource): Promise<DB_Ressource | string> {+ return new Promise(async (resolve, reject) => {+ const request = await makeRequest(`ressources/${ressource.id}`, 'PUT', ressource);+ if (request.status == 'success') {+ const index = this.ressources.findIndex(c => c.id == ressource.id);+ if (index != -1) this.ressources[index] = ressource as DB_Ressource;+ resolve(request.result as DB_Ressource);+ } else reject(request.message);+ });+ },delete(id: string) {return new Promise(async (resolve, reject) => {const request = await makeRequest(`ressources/${id}`, 'DELETE', {});