Skip to content

A self-hosted media server and file management system

feat: category privacy toggle and fix logout redirect

aminnausin48aa7a67bb3d
diff --git a/app/Http/Controllers/Api/V1/CategoryController.php b/app/Http/Controllers/Api/V1/CategoryController.php
index c0df3214..8e4635e2 100755
--- a/app/Http/Controllers/Api/V1/CategoryController.php
+++ b/app/Http/Controllers/Api/V1/CategoryController.php
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
+use App\Http\Requests\CategoryPrivacyUpdateRequest;
use App\Http\Requests\CategoryUpdateRequest;
use App\Http\Resources\CategoryResource;
use App\Models\Category;
@@ -17,16 +18,19 @@ class CategoryController extends Controller {
* Display a listing of the resource.
*/
public function index() {
- if (! Auth::user()) {
- $this->unauthorized();
- }
try {
$categories = Category::orderBy('name');
-
- if (Auth::user()->id !== 1) {
+ $userId = Auth::id();
+ if (Auth::id() !== 1) {
$categories->where('is_private', false);
}
+ if (!$userId) {
+ return $this->success(
+ [new CategoryResource($categories->with(['folders.series'])->first())]
+ );
+ }
+
return $this->success(
CategoryResource::collection(
$categories->with(['folders.series'])->get()
@@ -76,4 +80,29 @@ class CategoryController extends Controller {
return $this->error($request, 'Unable to edit category. Error: ' . $th->getMessage(), 500);
}
}
+
+ /**
+ * Update the specified resource in storage.
+ *
+ * @param int $category_id
+ */
+ public function updatePrivacy(CategoryPrivacyUpdateRequest $request, Category $category) {
+ if (Auth::id() !== 1) {
+ $this->unauthorized();
+ }
+
+ try {
+ $validated = $request->validated();
+ $validated['editor_id'] = Auth::id();
+
+ $category->is_private = $validated['is_private'] ?? $category->is_private;
+ $category->editor_id = $validated['editor_id'];
+
+ $category->save();
+
+ return $this->success($validated);
+ } catch (\Throwable $th) {
+ return $this->error($request, 'Unable to edit category permissions. Error: ' . $th->getMessage(), 500);
+ }
+ }
}
diff --git a/app/Http/Requests/CategoryPrivacyUpdateRequest.php b/app/Http/Requests/CategoryPrivacyUpdateRequest.php
new file mode 100644
index 00000000..80a33df3
--- /dev/null
+++ b/app/Http/Requests/CategoryPrivacyUpdateRequest.php
@@ -0,0 +1,27 @@
+<?php
+
+namespace App\Http\Requests;
+
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Support\Facades\Auth;
+
+class CategoryPrivacyUpdateRequest extends FormRequest {
+ /**
+ * Determine if the user is authorized to make this request.
+ */
+ public function authorize(): bool {
+ return Auth::check() && Auth::user()->id === 1;
+ }
+
+ /**
+ * Get the validation rules that apply to the request.
+ * Gets category and potentially folder id from query strings
+ *
+ * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
+ */
+ public function rules(): array {
+ return [
+ 'is_private' => 'boolean|required',
+ ];
+ }
+}
diff --git a/app/Http/Resources/CategoryResource.php b/app/Http/Resources/CategoryResource.php
index 70228ec2..f9f02328 100755
--- a/app/Http/Resources/CategoryResource.php
+++ b/app/Http/Resources/CategoryResource.php
@@ -4,6 +4,7 @@ namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
+use Illuminate\Support\Facades\Auth;
class CategoryResource extends JsonResource {
/**
@@ -36,6 +37,7 @@ class CategoryResource extends JsonResource {
'total_size' => $totalSize ?? 0,
'created_at' => $this->created_at,
'last_scan' => $this->last_scan,
+ 'is_private' => Auth::user() && Auth::id() === 1 ? $this->is_private : false,
];
}
}
diff --git a/resources/js/components/cards/CategoryCard.vue b/resources/js/components/cards/CategoryCard.vue
index 8e4e624a..9e6fb1cc 100644
--- a/resources/js/components/cards/CategoryCard.vue
+++ b/resources/js/components/cards/CategoryCard.vue
@@ -2,7 +2,7 @@
import { type CategoryResource, type FolderResource } from '@/types/resources';
import { formatFileSize, handleStorageURL, toFormattedDate } from '@/service/util';
-import { startScanFilesTask, startVerifyFilesTask } from '@/service/siteAPI';
+import { startScanFilesTask, startVerifyFilesTask, toggleCategoryPrivacy } from '@/service/siteAPI';
import { computed, ref, useTemplateRef, watch } from 'vue';
import { useQueryClient } from '@tanstack/vue-query';
import { updateCategory } from '@/service/mediaAPI.ts';
@@ -16,6 +16,7 @@ import Popover from '@/components/pinesUI/Popover.vue';
import ProiconsMoreVertical from '~icons/proicons/more-vertical';
import ProiconsArrowSync from '~icons/proicons/arrow-sync';
+import ProiconsLockOpen from '~icons/proicons/lock-open';
import CircumFolderOn from '~icons/circum/folder-on';
import ProiconsDelete from '~icons/proicons/delete';
import ProiconsLock from '~icons/proicons/lock';
@@ -75,6 +76,29 @@ const handleStartScan = async (verifyOnly: boolean = false) => {
}
};
+const handleTogglePrivacy = async (id: number, currentValue: boolean) => {
+ if (processing.value || !props.data?.id || currentValue !== props.data.is_private) return;
+
+ try {
+ processing.value = true;
+
+ const res = await toggleCategoryPrivacy(id, !currentValue);
+
+ if (res?.status !== 403) toast.success(`Library set to ${currentValue ? 'Public' : 'Private'}.`);
+ else {
+ toast.error('You do not have permission to set the privacy of libraries.');
+ }
+
+ await queryClient.invalidateQueries({ queryKey: ['categories'] });
+
+ processing.value = false;
+ } catch (error) {
+ toast('Failure', { type: 'danger', description: `Unable to set privacy.` });
+ console.error(error);
+ processing.value = false;
+ }
+};
+
watch(
() => props.data,
() => {
@@ -109,7 +133,7 @@ watch(
<ProiconsMoreVertical class="h-4 w-4" />
</template>
<template #content>
- <div class="space-y-4">
+ <div class="space-y-4" v-if="data">
<div class="space-y-2">
<h4 class="font-medium leading-none">Manage Library</h4>
<p class="text-sm text-muted-foreground">Set Library Properties.</p>
@@ -135,21 +159,26 @@ watch(
/>
</div>
- <ButtonText class="h-8 dark:!bg-neutral-950" :title="'Scan for Folder Changes'" @click="handleStartScan(false)">
- <template #text> Scan Folders </template>
+ <ButtonText class="h-8 dark:!bg-neutral-950" :title="'Scan for Changes'" @click="handleStartScan(false)">
+ <template #text> Scan Files </template>
<template #icon> <ProiconsArrowSync class="h-4 w-4" /></template>
</ButtonText>
<ButtonText class="h-8 dark:!bg-neutral-950" :title="'Verify File Metadata'" @click="handleStartScan(true)">
- <template #text> Verify Folders </template>
+ <template #text> Verify Files </template>
<template #icon> <ProiconsArrowSync class="h-4 w-4" /></template>
</ButtonText>
<ButtonText class="h-8 dark:!bg-neutral-950" :title="'Manage all Folders in Library'" :to="`/dashboard/libraries/${data?.id}`" target="">
<template #text> Manage Folders </template>
<template #icon> <CircumFolderOn class="h-4 w-4" /></template>
</ButtonText>
- <ButtonText class="h-8 dark:!bg-neutral-950 disabled:opacity-60" :title="'Set User Access Permissions'" disabled>
- <template #text> Manage Access </template>
- <template #icon> <ProiconsLock class="h-4 w-4" /></template>
+ <ButtonText
+ class="h-8 dark:!bg-neutral-950 disabled:opacity-60"
+ :title="'Toggle Privacy'"
+ @click="handleTogglePrivacy(data.id, data.is_private ?? false)"
+ :disabled="processing"
+ >
+ <template #text> {{ data.is_private ? 'Set to Public' : 'Set to Private' }} </template>
+ <template #icon> <ProiconsLock v-if="data.is_private" class="h-4 w-4" /> <ProiconsLockOpen v-else class="h-4 w-4" /></template>
</ButtonText>
<ButtonText
class="h-8 text-rose-600 dark:!bg-rose-700 disabled:opacity-60"
diff --git a/resources/js/components/dashboard/DashboardLibraries.vue b/resources/js/components/dashboard/DashboardLibraries.vue
index ae763a0d..9abc5ab5 100644
--- a/resources/js/components/dashboard/DashboardLibraries.vue
+++ b/resources/js/components/dashboard/DashboardLibraries.vue
@@ -16,7 +16,7 @@ import ModalBase from '@/components/pinesUI/ModalBase.vue';
import TableBase from '@/components/table/TableBase.vue';
import useModal from '@/composables/useModal';
-import ProiconsArrowSync from '~icons/proicons/arrow-sync';
+import ProiconsSearch from '~icons/proicons/search';
import ProiconsAdd from '~icons/proicons/add';
const sortingOptions = ref([
@@ -102,13 +102,13 @@ onMounted(() => {
<section v-else id="content-libraries" class="flex gap-8 flex-col">
<div class="flex items-center gap-2 justify-between flex-wrap">
<div class="flex flex-wrap items-center gap-2 [&>*]:h-fit [&>*]:xs:h-8">
- <ButtonText title="Add New Library" @click="toast.add('Success', { type: 'success', description: 'Submitted Scan Request!', life: 3000 })" disabled>
+ <ButtonText title="Add New Library" disabled>
<template #text>New Library</template>
<template #icon><ProiconsAdd /></template>
</ButtonText>
- <ButtonText @click="handleStartScan">
- <template #text>Scan For Changes</template>
- <template #icon><ProiconsArrowSync /></template>
+ <ButtonText @click="handleStartScan" :title="'Index Files'">
+ <template #text>Look For Changes</template>
+ <template #icon><ProiconsSearch /></template>
</ButtonText>
</div>
<p class="capitalize text-sm font-medium">Count: {{ stateLibraries?.length }}</p>
diff --git a/resources/js/components/inputs/ButtonText.vue b/resources/js/components/inputs/ButtonText.vue
index 1f38582a..f944f74d 100755
--- a/resources/js/components/inputs/ButtonText.vue
+++ b/resources/js/components/inputs/ButtonText.vue
@@ -10,7 +10,7 @@ const props = withDefaults(
target?: string;
}>(),
{
- title: 'Button',
+ title: '',
type: 'button',
variant: 'default',
target: '_blank',
diff --git a/resources/js/router/index.ts b/resources/js/router/index.ts
index 460f193b..3ac55af9 100644
--- a/resources/js/router/index.ts
+++ b/resources/js/router/index.ts
@@ -25,13 +25,19 @@ const router = createRouter({
async beforeRouteEnter(to, from, next) {
// To return to root folder of current category -> let nextPath = `/${stateDirectory.value.name}`;
- const { data: response } = await getCategories();
+ try {
+ const { data: response } = await getCategories();
+
+ if (response?.data[0]?.name) {
+ let nextPath = `/${response?.data[0]?.name}`;
- if (response?.data[0]?.name) {
- let nextPath = `/${response?.data[0]?.name}`;
+ next(nextPath);
+ return;
+ }
+ } catch (error) {
+ console.log(error);
- next(nextPath);
- return;
+ toast.error('Error getting default library.');
}
next('/setup');
@@ -56,33 +62,33 @@ const router = createRouter({
{
path: '/logout',
name: 'logout',
- component: {
- async beforeRouteEnter(to, from, next) {
- try {
- const { clearAuthState } = useAuthStore();
- const meta = from.meta as { title?: string; protected?: boolean };
-
- let nextPath = from.fullPath;
- let nextTitle = meta?.title ?? toTitleCase(`${from.name?.toString()}`);
- await logout();
- clearAuthState();
-
- if (meta?.protected || from.name === 'logout') {
- nextPath = '/';
- nextTitle = 'Home';
- }
-
- document.title = nextTitle;
- next(nextPath);
- } catch (error) {
- toast.add('Error', { type: 'danger', description: `Unable to logout.` });
- console.log(error);
+ beforeEnter: async (to, from, next) => {
+ try {
+ const { clearAuthState } = useAuthStore();
+ const meta = from.meta as { title?: string; protected?: boolean };
+
+ let nextPath = from.fullPath;
+ let nextTitle = meta?.title ?? toTitleCase(`${from.name?.toString()}`);
+ await logout();
+ clearAuthState();
+
+ if (meta?.protected || from.name === 'logout') {
+ nextPath = '/';
+ nextTitle = 'Home';
+ }
- next('/');
+ document.title = nextTitle;
+ next(nextPath);
+ } catch (error) {
+ toast.error(`Unable to logout.`);
+ console.log(error);
- document.title = 'Home'; // Update Page Title
- }
- },
+ document.title = 'Home'; // Update Page Title
+ next('/');
+ }
+ },
+ component: {
+ render: () => 'div',
},
},
{
diff --git a/resources/js/service/siteAPI.ts b/resources/js/service/siteAPI.ts
index da5cf051..e785e011 100644
--- a/resources/js/service/siteAPI.ts
+++ b/resources/js/service/siteAPI.ts
@@ -35,6 +35,10 @@ export function getTaskStats() {
return API.get('/tasks/stats');
}
+export function toggleCategoryPrivacy(category: number, value: boolean) {
+ return API.post(`/categories/privacy/${category}`, { is_private: value });
+}
+
export function startGenericTast(url: string) {
return API.post(`/tasks/${url}`);
}
diff --git a/resources/js/types/resources.ts b/resources/js/types/resources.ts
index a0e96be8..07679280 100644
--- a/resources/js/types/resources.ts
+++ b/resources/js/types/resources.ts
@@ -20,6 +20,7 @@ export interface CategoryResource {
default_folder_id?: number;
created_at?: string;
last_scan: number;
+ is_private?: boolean;
}
export interface FolderResource {
id: number;
diff --git a/routes/api.php b/routes/api.php
index 1cbf2cc1..2707fe7f 100755
--- a/routes/api.php
+++ b/routes/api.php
@@ -39,12 +39,13 @@ Route::group(['middleware' => ['auth:sanctum']], function () {
Route::resource('/metadata', MetadataController::class)->only(['show', 'store', 'update']);
Route::resource('/tags', TagController::class)->only(['index', 'store']);
Route::resource('/analytics', AnalyticsController::class)->only(['index']);
- Route::resource('/categories', CategoryController::class)->only(['index', 'update']);
+ Route::resource('/categories', CategoryController::class)->only(['update']);
Route::resource('/users', UserController::class)->only(['index', 'destroy']);
Route::resource('/sub-tasks', SubTaskController::class)->only(['show', 'destroy']);
Route::resource('/tasks', TaskController::class)->only(['index', 'destroy']);
Route::post('/sub-tasks/{task}', [SubTaskController::class, 'show']);
+ Route::post('/categories/privacy/{category}', [CategoryController::class, 'updatePrivacy']);
Route::prefix('tasks')->group(function () {
Route::get('/stats', [TaskController::class, 'stats']);
@@ -73,7 +74,7 @@ Route::get('/videos', [VideoController::class, 'getFrom']);
Route::resource('/videos', VideoController::class)->only(['show', 'update']);
Route::resource('/folders', FolderController::class)->only(['show']);
-Route::resource('/categories', CategoryController::class)->only(['show']);
+Route::resource('/categories', CategoryController::class)->only(['index', 'show']);
Route::resource('/playback', PlaybackController::class)->only(['show', 'store']);
// healthcheck