A self-hosted media server and file management system
Vue ffmpegfile-serverjellyfinlaravelmediamedia-playermedia-servermediabrowsermediaservermusicmusic-librarymusic-playermusicplayerself-hostedvuejs
setup more websocket events
aminnausinc565f839bb48
diff --git a/app/Events/TaskEnded.php b/app/Events/TaskEnded.phpindex 4134a0bd..b744d790 100644--- a/app/Events/TaskEnded.php+++ b/app/Events/TaskEnded.php@@ -2,6 +2,7 @@namespace App\Events;+use App\Enums\TaskStatus;use App\Http\Resources\TasksResource;use App\Models\Task;use Illuminate\Broadcasting\InteractsWithSockets;@@ -12,10 +13,11 @@ use Illuminate\Contracts\Broadcasting\ShouldBroadcast;use Illuminate\Foundation\Events\Dispatchable;use Illuminate\Queue\SerializesModels;+use function Illuminate\Log\log;+class TaskEnded implements ShouldBroadcast {use Dispatchable, InteractsWithSockets, SerializesModels;- public TasksResource $resource;/*** Create a new event instance.@@ -31,14 +33,24 @@ class TaskEnded implements ShouldBroadcast {*/public function broadcastOn(): array {try {- $this->resource = new TasksResource($this->task);// code...return [- new PrivateChannel("tasks.{$this->task->user_id}"),+ new PrivateChannel("tasks.{$this->task->id}"),+ new PrivateChannel("dashboard.tasks"),];} catch (\Throwable $th) {dump($th->getMessage());}}++ /**+ *+ * Get the data to broadcast.+ *+ * @return array+ */+ public function broadcastWith(): array {+ return ['task' => new TasksResource($this->task)];+ }}diff --git a/resources/js/components/dashboard/DashboardLibraries.vue b/resources/js/components/dashboard/DashboardLibraries.vueindex 8963b52c..458181fa 100644--- a/resources/js/components/dashboard/DashboardLibraries.vue+++ b/resources/js/components/dashboard/DashboardLibraries.vue@@ -1,8 +1,11 @@<script setup lang="ts">import type { CategoryResource } from '@/types/resources';-import { computed, onMounted, ref, watch } from 'vue';+import { computed, onMounted, ref, watch, type Ref } from 'vue';+import { startIndexFilesTask } from '@/service/siteAPI';+import { useDashboardStore } from '@/stores/DashboardStore';import { useGetCategories } from '@/service/queries';+import { storeToRefs } from 'pinia';import { toast } from '@/service/toaster/toastService';import CategoryCard from '@/components/cards/CategoryCard.vue';@@ -13,14 +16,7 @@ import useModal from '@/composables/useModal';import ProiconsArrowSync from '~icons/proicons/arrow-sync';import ProiconsAdd from '~icons/proicons/add';-import { startIndexFilesTask } from '@/service/siteAPI';--const cachedID = ref<null | number>(null);-const confirmModal = useModal({ title: 'Delete Category?', submitText: 'Confim' });-const { data: rawCategories, isLoading } = useGetCategories();-const categories = ref<CategoryResource[]>([]);-const searchQuery = ref('');const sortingOptions = ref([{title: 'Title',@@ -39,9 +35,15 @@ const sortingOptions = ref([},]);+const { stateLibraries, isLoadingLibraries } = storeToRefs(useDashboardStore());++const cachedID = ref<null | number>(null);+const searchQuery = ref('');+const confirmModal = useModal({ title: 'Delete Category?', submitText: 'Confim' });+const filteredCategories = computed(() => {let tempList = searchQuery.value- ? categories.value.filter((category: CategoryResource) => {+ ? stateLibraries.value.filter((category: CategoryResource) => {{try {let strRepresentation = [category.name, category.folders_count, category.folders[0]?.name ?? '', category.created_at].join(' ').toLowerCase();@@ -52,7 +54,7 @@ const filteredCategories = computed(() => {}}})- : categories.value;+ : stateLibraries.value;return tempList;});@@ -61,16 +63,11 @@ const handleDelete = (id: number) => {confirmModal.toggleModal(true);};-const submitDelete = async () => {- if (cachedID.value) {- // let request = await deleteRecord(cachedID.value);- // if (request) toast.add({ type: 'success', title: 'Success', description: 'Record Deleted Successfully!', life: 3000 });- // else toast.add({ type: 'warning', title: 'Error', description: 'Unable to delete record. Please try again.', life: 3000 });- }-};+const submitDelete = async () => {};const handleSort = async (column = 'date', dir = 1) => {- let tempList = categories.value.sort((categoryA: CategoryResource, categoryB: CategoryResource) => {+ let tempList = [...stateLibraries.value];+ tempList.sort((categoryA: CategoryResource, categoryB: CategoryResource) => {if (column === 'created_at') {let dateA = new Date(categoryA?.created_at ?? '');let dateB = new Date(categoryB?.created_at ?? '');@@ -81,14 +78,10 @@ const handleSort = async (column = 'date', dir = 1) => {if (valueA && valueB && typeof valueA === 'number' && typeof valueB === 'number') return (valueA - valueB) * dir;return `${valueA}`?.localeCompare(`${valueB}`) * dir;});- categories.value = tempList;+ stateLibraries.value = tempList;return tempList;};-const handleSearch = (query: string) => {- searchQuery.value = query;-};-const handleStartScan = async () => {try {const result = await startIndexFilesTask();@@ -99,13 +92,9 @@ const handleStartScan = async () => {}};-watch(rawCategories, (v) => {- categories.value = v?.data ?? [];-});--onMounted(() => {- if (rawCategories.value?.data) categories.value = rawCategories.value.data;-});+// onMounted(() => {+// if (rawCategories.value?.data) stateLibraries.value = rawCategories.value.data;+// });</script><template><section id="content-libraries" class="flex gap-8 flex-col">@@ -120,18 +109,22 @@ onMounted(() => {<template #icon><ProiconsArrowSync /></template></ButtonText></div>- <p class="capitalize text-sm font-medium">Count: {{ categories?.length }}</p>+ <p class="capitalize text-sm font-medium">Count: {{ stateLibraries?.length }}</p></div><TableBase:use-grid="'grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 2xl:grid-cols-4 3xl:grid-cols-5 gap-3'":use-pagination="true"- :data="[...filteredCategories]"+ :data="filteredCategories":row="CategoryCard":click-action="handleDelete"- :loading="isLoading"+ :loading="isLoadingLibraries":sort-action="handleSort":sorting-options="sortingOptions"- @search="handleSearch"+ @search="+ (query: string) => {+ searchQuery = query;+ }+ "/></section><ModalBase :modalData="confirmModal" :action="submitDelete">diff --git a/resources/js/components/dashboard/DashboardUsers.vue b/resources/js/components/dashboard/DashboardUsers.vueindex 32aac070..6e76647f 100644--- a/resources/js/components/dashboard/DashboardUsers.vue+++ b/resources/js/components/dashboard/DashboardUsers.vue@@ -13,6 +13,8 @@ import useModal from '@/composables/useModal';import ProiconsArrowSync from '~icons/proicons/arrow-sync';import ProiconsAdd from '~icons/proicons/add';+import { storeToRefs } from 'pinia';+import { useDashboardStore } from '@/stores/DashboardStore';const confirmModal = useModal({ title: 'Remove User?', submitText: 'Confim' });@@ -36,12 +38,13 @@ const sortingOptions = ref([]);const activeSessions = ref(0);-const users = ref<UserResource[]>([]);+const { stateUsers, isLoadingUsers } = storeToRefs(useDashboardStore());+const cachedID = ref<number | null>(null);const filteredUsers = computed(() => {let tempList = searchQuery.value- ? users.value.filter((user: UserResource) => {+ ? stateUsers.value.filter((user: UserResource) => {{try {let strRepresentation = [user.name, user.email, user.created_at].join(' ').toLowerCase();@@ -52,12 +55,12 @@ const filteredUsers = computed(() => {}}})- : users.value;+ : stateUsers.value;return tempList;});const handleSort = async (column = 'date', dir = 1) => {- let tempList = users.value.sort((userA: UserResource, userB: UserResource) => {+ let tempList = [...stateUsers.value].sort((userA: UserResource, userB: UserResource) => {if (column === 'created_at' || column === 'last_active') {let dateA = new Date(userA?.[column] ?? '');let dateB = new Date(userB?.[column] ?? '');@@ -68,7 +71,7 @@ const handleSort = async (column = 'date', dir = 1) => {if (valueA && valueB && typeof valueA === 'number' && typeof valueB === 'number') return (valueA - valueB) * dir;return `${valueA}`?.localeCompare(`${valueB}`) * dir;});- users.value = tempList;+ stateUsers.value = tempList;return tempList;};@@ -98,9 +101,9 @@ const loadData = async () => {const { data: rawActiveSessions } = await getActiveSessions();activeSessions.value = parseInt(rawActiveSessions) ?? 0;- const { data: rawUsers } = await getUsers();+ // const { data: rawUsers } = await getUsers();- users.value = rawUsers?.data?.length > 0 ? rawUsers.data : [];+ // stateUsers.value = rawUsers?.data?.length > 0 ? rawUsers.data : [];};onMounted(() => {@@ -130,15 +133,15 @@ onMounted(() => {</ButtonText></div><div class="capitalize text-sm font-medium text-neutral-600 dark:text-neutral-300 flex flex-col gap-1 w-fit text-end">- <p class="w-fit">Users: {{ users.length }}</p>+ <p class="w-fit">Users: {{ stateUsers.length }}</p><p class="w-fit">Active: {{ activeSessions }}</p></div></div><TableBase:use-pagination="true"- :data="[...filteredUsers]"+ :data="filteredUsers":row="UserCard"- :loading="false"+ :loading="isLoadingUsers":clickAction="handleDelete":sort-action="handleSort":sorting-options="sortingOptions"diff --git a/resources/js/components/pinesUI/InputMultiChip.vue b/resources/js/components/pinesUI/InputMultiChip.vueindex b2d92713..39ab8c7d 100644--- a/resources/js/components/pinesUI/InputMultiChip.vue+++ b/resources/js/components/pinesUI/InputMultiChip.vue@@ -169,7 +169,14 @@ watch(@keydown="select.selectKeydown($event)"class="relative">- <OnClickOutside @trigger="select.toggleSelect(false)" class="relative">+ <OnClickOutside+ @trigger="+ () => {+ console.log('???');+ }+ "+ class="relative"+ ><buttonref="selectButton"@click="select.toggleSelect()"@@ -185,13 +192,7 @@ watch(><span class="truncate">{{ placeholder }}</span><span class="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none">- <svg- xmlns="http://www.w3.org/2000/svg"- viewBox="0 0 20 20"- fill="currentColor"- aria-hidden="true"- class="w-5 h-5 text-gray-400"- >+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="w-5 h-5 text-gray-400"><pathfill-rule="evenodd"d="M10 3a.75.75 0 01.55.24l3.25 3.5a.75.75 0 11-1.1 1.02L10 4.852 7.3 7.76a.75.75 0 01-1.1-1.02l3.25-3.5A.75.75 0 0110 3zm-3.76 9.2a.75.75 0 011.06.04l2.7 2.908 2.7-2.908a.75.75 0 111.1 1.02l-3.25 3.5a.75.75 0 01-1.1 0l-3.25-3.5a.75.75 0 01.04-1.06z"@@ -201,11 +202,7 @@ watch(</span></button>- <Transition- enter-active-class="transition ease-out duration-50"- enter-from-class="opacity-0 -translate-y-1"- enter-to-class="opacity-100"- >+ <Transition enter-active-class="transition ease-out duration-50" enter-from-class="opacity-0 -translate-y-1" enter-to-class="opacity-100"><ulv-show="select.selectOpen"ref="selectableItemsList"@@ -233,9 +230,7 @@ watch(</ButtonIcon></li><template- v-for="(item, index) in select.selectableItems.filter(- (selectable) => !select.selectedItems?.find((selected) => selectable.name === selected.name),- )"+ v-for="(item, index) in select.selectableItems.filter((selectable) => !select.selectedItems?.find((selected) => selectable.name === selected.name))":key="item.value"><li@@ -243,8 +238,7 @@ watch(:id="index + '-' + select.selectId":data-disabled="item.disabled ? item.disabled : ''":class="{- 'bg-neutral-100 dark:bg-neutral-900/70 text-gray-900 dark:text-neutral-100':- select.selectableItemActive === item,+ 'bg-neutral-100 dark:bg-neutral-900/70 text-gray-900 dark:text-neutral-100': select.selectableItemActive === item,'text-gray-700 dark:text-neutral-300': !select.selectableItemActive === item,}"@mousemove="@@ -263,13 +257,7 @@ watch(</Transition></OnClickOutside><span v-if="select.selectedItems?.length > 0" class="flex flex-wrap gap-1 pt-2 pb-1">- <ChipTag- v-for="(chip, index) in select.selectedItems"- v-bind:key="index"- :label="chip.name"- :removeable="true"- @clickAction="handleRemoveChip(chip.name)"- />+ <ChipTag v-for="(chip, index) in select.selectedItems" v-bind:key="index" :label="chip.name" :removeable="true" @clickAction="handleRemoveChip(chip.name)" /></span></div></template>diff --git a/resources/js/components/table/TableBase.vue b/resources/js/components/table/TableBase.vueindex 7be8e204..90f4bab6 100755--- a/resources/js/components/table/TableBase.vue+++ b/resources/js/components/table/TableBase.vue@@ -57,7 +57,7 @@ const handleSortChange = (sortKey?: { title?: string; value?: string; disabled?:props.sortAction(lastSortKey.value, sortAscending.value ? 1 : -1);};-watch(props.data, tableData.handlePageReset, { immediate: true });+watch(() => props.data, tableData.handlePageReset, { immediate: true });onMounted(() => {if (props.useToolbar && props.sortAction) props.sortAction(lastSortKey.value, props.startAscending ? 1 : -1);diff --git a/resources/js/service/authAPI.ts b/resources/js/service/authAPI.tsindex 5f240d72..9bbbf9b2 100644--- a/resources/js/service/authAPI.ts+++ b/resources/js/service/authAPI.ts@@ -37,7 +37,7 @@ export const authenticate = async (token: string | null) => {try {return await API.get('/auth', {headers: {- Authorization: `bearer ${token}`,+ // Authorization: `bearer ${token}`, //This is the only place i use bearer but the entire spa app uses cookies},});} catch (error) {diff --git a/resources/js/service/queries.ts b/resources/js/service/queries.tsindex 20a784b1..f6dc00d6 100644--- a/resources/js/service/queries.ts+++ b/resources/js/service/queries.ts@@ -1,11 +1,11 @@import type { PulseResponse, SiteAnalyticsResponse } from '@/types/types.ts';import type { Ref } from 'vue';-import { getSiteAnalytics, getPulse } from '@/service/siteAPI.ts';+import { getSiteAnalytics, getPulse, getUsers } from '@/service/siteAPI.ts';import { useQuery } from '@tanstack/vue-query';import mediaAPI, { getCategories } from '@/service/mediaAPI.ts';-import type { CategoryResource } from '@/types/resources';+import type { CategoryResource, UserResource } from '@/types/resources';export const useGetVideoTags = () => {return useQuery({@@ -58,6 +58,16 @@ export const useGetCategories = () => {});};+export const useGetUsers = () => {+ return useQuery<{ data: UserResource[] }>({+ queryKey: ['users'],+ queryFn: async () => {+ const { data: response } = await getUsers();+ return response;+ },+ });+};+// export const useGetChatRoomMessagesQuery = (chat_id: number | null) => {// return useInfiniteQuery({// queryKey: ['chatroom-messages', chat_id],diff --git a/resources/js/service/taskService.ts b/resources/js/service/taskService.tsindex 76642a64..58084beb 100644--- a/resources/js/service/taskService.ts+++ b/resources/js/service/taskService.ts@@ -1,5 +1,6 @@-import { startIndexFilesTask, startScanFilesTask, startSyncFilesTask, startVerifyFilesTask } from './siteAPI';-import { toast } from './toaster/toastService';+import { startIndexFilesTask, startScanFilesTask, startSyncFilesTask, startVerifyFilesTask } from '@/service/siteAPI';+import { subscribeToTask } from '@/service/wsService';+import { toast } from '@/service/toaster/toastService';export async function handleStartTask(job: 'index' | 'sync' | 'verify' | 'scan') {try {@@ -12,7 +13,9 @@ export async function handleStartTask(job: 'index' | 'sync' | 'verify' | 'scan')? await startVerifyFilesTask(): await startScanFilesTask();- toast.add('Success', { type: 'success', description: `Submitted ${job} Request!` });+ const task: { task_id: number; message: string } = result.data;+ subscribeToTask(task.task_id);+ toast.add('Success', { type: 'success', description: task?.message ?? `Submitted ${job} Request!` });} catch (error) {toast('Failure', { type: 'danger', description: `Unable to submit ${job} request.` });}diff --git a/resources/js/service/toaster/toastService.ts b/resources/js/service/toaster/toastService.tsindex 1c10d16e..c6844b53 100644--- a/resources/js/service/toaster/toastService.ts+++ b/resources/js/service/toaster/toastService.ts@@ -76,6 +76,19 @@ class Observer {add = (message: string, options?: ToastOptions) => {return this.create(message, { ...options });};++ success = (message: string, options?: ToastOptions) => {+ return this.create(message, { type: 'success', ...options });+ };+ error = (message: string, options?: ToastOptions) => {+ return this.create(message, { type: 'danger', ...options });+ };+ info = (message: string, options?: ToastOptions) => {+ return this.create(message, { type: 'info', ...options });+ };+ warning = (message: string, options?: ToastOptions) => {+ return this.create(message, { type: 'warning', ...options });+ };}export const ToastState = new Observer();@@ -88,5 +101,9 @@ function toastFunction(message: string, options?: ToastOptions) {export const toast = Object.assign(toastFunction, {add: ToastState.add,+ success: ToastState.success,+ error: ToastState.error,+ info: ToastState.info,+ warning: ToastState.warning,dismiss: ToastState.dismiss,});diff --git a/resources/js/service/wsService.ts b/resources/js/service/wsService.tsnew file mode 100644index 00000000..72899a96--- /dev/null+++ b/resources/js/service/wsService.ts@@ -0,0 +1,58 @@+import { toast } from './toaster/toastService';++export function subscribeToTask(taskId: number) {+ if (isNaN(taskId) || taskId <= 0) return;++ window.Echo.private(`tasks.${taskId}`).listen('TaskEnded', (event: any) => {+ console.log(event);+ toast.add(`"${event?.task?.name}" ${event?.task?.status}.`, { type: event?.task?.status_key > 0 ? 'success' : 'danger' });++ window.Echo.leave(`tasks.${taskId}`);+ });+}++export function subscribeToNotifications() {}++export function subscribeToDaskboardTasks() {+ window.Echo.private(`dashboard.tasks`).listen('TaskUpdated', (event: any) => {+ // console.log(event);+ // Update StateTasks??+ });+}++/**+ * WS Layout+ *+ * Running Tasks:+ *+ * when starting a task, connect to tasks.(taskID)+ *+ * when task is finished => toast notification with state and then close the connection+ *+ * no need to authenticate with user id in channel name because task access is set by user permissions and task status is not private to one task.+ *+ * Auth is done through user permissions in backend (id == 1)+ *+ * Dashboard tasks page:+ *+ * On Mount, connect to dashboard.tasks+ * On UnMount, leave dashboard.tasks+ *+ * listen to TaskUpdated Event and update stateTask where task.id matches the updated data.+ *+ * Auth is done through user permissions in backend (id == 1)+ *+ * Dashboard Libraries Page:+ *+ * On Mount, connect to dashboard.libraries+ * On UnMount, leave dashboard.libraries+ *+ * listen to LibraryUpdated Event and update stateLibraries where library.id matches the updated data.+ *+ * I guess event runs when library edited instead of loading data again and when index files creates files or folders+ *+ * Auth is done through user permissions in backend (id == 1)+ *+ *+ *+ */diff --git a/resources/js/stores/DashboardStore.ts b/resources/js/stores/DashboardStore.tsnew file mode 100644index 00000000..8de4e7a7--- /dev/null+++ b/resources/js/stores/DashboardStore.ts@@ -0,0 +1,36 @@+import { type CategoryResource, type TaskResource, type UserResource } from '@/types/resources';++import { ref, watch, type Ref } from 'vue';+import { useGetCategories, useGetUsers } from '@/service/queries';+import { defineStore } from 'pinia';++export const useDashboardStore = defineStore('Dashboard', () => {+ const { data: rawCategories, isLoading: isLoadingLibraries } = useGetCategories();+ const { data: rawUsers, isLoading: isLoadingUsers } = useGetUsers();++ const stateLibraries = ref<CategoryResource[]>([]);+ const stateTasks = ref<TaskResource[]>([]);+ const stateUsers = ref<UserResource[]>([]);++ watch(rawCategories, (v) => {+ stateLibraries.value = v?.data ?? [];+ });++ watch(rawUsers, (v) => {+ stateUsers.value = v?.data ?? [];+ });++ return {+ stateLibraries,+ stateTasks,+ stateUsers,+ isLoadingLibraries,+ isLoadingUsers,+ } as {+ stateLibraries: Ref<CategoryResource[]>;+ stateTasks: Ref<TaskResource[]>;+ stateUsers: Ref<UserResource[]>;+ isLoadingLibraries: boolean;+ isLoadingUsers: boolean;+ };+});diff --git a/routes/channels.php b/routes/channels.phpindex d44f6a3b..627618af 100644--- a/routes/channels.php+++ b/routes/channels.php@@ -3,7 +3,20 @@use Illuminate\Support\Facades\Broadcast;Broadcast::channel('tasks.{id}', function ($user, $id) {+ return (int) $user->id === 1;+});++Broadcast::channel('notifications.{id}', function ($user, $id) {return (int) $user->id === (int) $id;});-Broadcast::channel('dashboard', function () {});+Broadcast::channel('dashboard.tasks', function ($user) {+ return (int) $user->id === 1;+});++Broadcast::channel('dashboard.libraries', function ($user) {+ return (int) $user->id === 1;+});++Broadcast::channel('dashboard', function () {+});