A self-hosted media server and file management system
Vue ffmpegfile-serverjellyfinlaravelmediamedia-playermedia-servermediabrowsermediaservermusicmusic-librarymusic-playermusicplayerself-hostedvuejs
echo only when needed
aminnausinfebc93e7b1bc
diff --git a/resources/js/components/dashboard/DashboardTasks.vue b/resources/js/components/dashboard/DashboardTasks.vueindex 7dc86486..1d8a9e29 100644--- a/resources/js/components/dashboard/DashboardTasks.vue+++ b/resources/js/components/dashboard/DashboardTasks.vue@@ -8,6 +8,7 @@ import { subscribeToDaskboardTasks } from '@/service/wsService';import { useDashboardStore } from '@/stores/DashboardStore';import { handleStartTask } from '@/service/taskService';import { useQueryClient } from '@tanstack/vue-query';+import { useAppStore } from '@/stores/AppStore';import { storeToRefs } from 'pinia';import { toast } from '@/service/toaster/toastService';@@ -63,9 +64,14 @@ const sortingOptions = [},];-const { stateTasks, stateTaskStats } = storeToRefs(useDashboardStore()) as { stateTasks: Ref<TaskResource[]>; stateTaskStats: Ref<TaskStatsResponse> };+const { stateTasks, stateTaskStats, isLoadingTasks } = storeToRefs(useDashboardStore()) as {+ stateTasks: Ref<TaskResource[]>;+ stateTaskStats: Ref<TaskStatsResponse>;+ isLoadingTasks: Ref<boolean>;+};+const { createEcho, disconnectEcho } = useAppStore();-const liveUpdate = subscribeToDaskboardTasks();+const liveUpdate = ref<any>(null);const queryClient = useQueryClient();const taskPopover = useTemplateRef('taskPopover');@@ -192,11 +198,14 @@ onMounted(() => {// For showing and hiding charts with a v-if instead of css for performance reasonswindow.addEventListener('resize', updateScreenSize);loadData();+ createEcho();+ if (window.Echo) liveUpdate.value = subscribeToDaskboardTasks();});-onUnmounted(() => {+onUnmounted(async () => {window.removeEventListener('resize', updateScreenSize);- if (liveUpdate) liveUpdate.unsubscribe();+ if (liveUpdate.value) liveUpdate.value?.unsubscribe().then(() => disconnectEcho());+ else disconnectEcho();});</script>@@ -292,7 +301,7 @@ onUnmounted(() => {:data="[...filteredTasks]":row="TaskCard":row-attributes="{ isScreenSmall, isScreenLarge }"- :loading="false"+ :loading="isLoadingTasks":clickAction="handleDelete":sort-action="handleSort":sorting-options="sortingOptions"diff --git a/resources/js/echo.js b/resources/js/echo.jsdeleted file mode 100644index 44c1b925..00000000--- a/resources/js/echo.js+++ /dev/null@@ -1,38 +0,0 @@-import Echo from 'laravel-echo';--import Pusher from 'pusher-js';-window.Pusher = Pusher;--window.Echo = new Echo({- broadcaster: 'reverb',- // authorizer: (channel, options) => {- // return {- // authorize: (socketId, callback) => {- // axios- // .post('/api/broadcasting/auth', {- // socket_id: socketId,- // channel_name: channel.name,- // })- // .then((response) => {- // callback(false, response.data);- // })- // .catch((error) => {- // callback(true, error.response);- // });- // },- // };- // },- key: import.meta.env.VITE_REVERB_APP_KEY,- wsHost: import.meta.env.VITE_REVERB_HOST,- wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,- wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,- forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',- enabledTransports: ['ws', 'wss'],-});--window.addEventListener('popstate', () => {- if (window.Echo.connector && window.Echo.connector.socket) {- window.Echo.connector.socket.disconnect();- window.Echo.connector.socket.connect();- }-});diff --git a/resources/js/echo.ts b/resources/js/echo.tsnew file mode 100644index 00000000..9b67f53a--- /dev/null+++ b/resources/js/echo.ts@@ -0,0 +1,44 @@+import Pusher from 'pusher-js';+import Echo from 'laravel-echo';++window.Pusher = Pusher;++export let echoInstance = null;++export const EchoConfig: {+ broadcaster: 'reverb';+ key: any;+ wsHost: any;+ wsPort: any;+ wssPort: any;+ forceTLS: boolean;+ enabledTransports: string[];+} = {+ broadcaster: 'reverb',+ key: import.meta.env.VITE_REVERB_APP_KEY,+ wsHost: import.meta.env.VITE_REVERB_HOST,+ wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,+ wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,+ forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',+ enabledTransports: ['ws', 'wss'],+};++// window.Echo = new Echo(EchoConfig);++// authorizer: (channel, options) => {+// return {+// authorize: (socketId, callback) => {+// axios+// .post('/api/broadcasting/auth', {+// socket_id: socketId,+// channel_name: channel.name,+// })+// .then((response) => {+// callback(false, response.data);+// })+// .catch((error) => {+// callback(true, error.response);+// });+// },+// };+// },diff --git a/resources/js/global.d.ts b/resources/js/global.d.tsindex af0d9f0a..d704106a 100644--- a/resources/js/global.d.ts+++ b/resources/js/global.d.ts@@ -1,10 +1,12 @@-import Echo from 'laravel-echo';+import type { Broadcaster } from '@/types/types';+import Pusher from 'pusher-js';+import Echo from 'laravel-echo';declare global {interface Window {axios: AxiosStatic;Pusher: typeof Pusher;- Echo: Echo<'reverb'>;+ Echo: Echo<keyof Broadcaster> | null;}}diff --git a/resources/js/service/taskService.ts b/resources/js/service/taskService.tsindex 58084beb..be4ea6b2 100644--- a/resources/js/service/taskService.ts+++ b/resources/js/service/taskService.ts@@ -1,6 +1,7 @@import { startIndexFilesTask, startScanFilesTask, startSyncFilesTask, startVerifyFilesTask } from '@/service/siteAPI';import { subscribeToTask } from '@/service/wsService';import { toast } from '@/service/toaster/toastService';+import { useAppStore } from '@/stores/AppStore';export async function handleStartTask(job: 'index' | 'sync' | 'verify' | 'scan') {try {@@ -14,6 +15,10 @@ export async function handleStartTask(job: 'index' | 'sync' | 'verify' | 'scan'): await startScanFilesTask();const task: { task_id: number; message: string } = result.data;+ const { createEcho } = useAppStore();++ createEcho();+subscribeToTask(task.task_id);toast.add('Success', { type: 'success', description: task?.message ?? `Submitted ${job} Request!` });} catch (error) {diff --git a/resources/js/service/wsService.ts b/resources/js/service/wsService.tsindex 61870ca4..6286f328 100644--- a/resources/js/service/wsService.ts+++ b/resources/js/service/wsService.ts@@ -1,5 +1,6 @@import { useDashboardStore } from '@/stores/DashboardStore';import { toast } from '@/service/toaster/toastService';+import { useAppStore } from '@/stores/AppStore';/*** Subscribes to a specific task ID and shows a notification once it ends.@@ -7,27 +8,59 @@ import { toast } from '@/service/toaster/toastService';* @param taskId The specific Task ID*/export function subscribeToTask(taskId: number) {- if (isNaN(taskId) || taskId <= 0) return;+ if (isNaN(taskId) || taskId <= 0 || window.Echo == null) return;++ window.Echo.private(`tasks.${taskId}`).listen('TaskEnded', async (event: any) => {+ if (!window.Echo || window.Echo?.connector?.pusher?.connection?.state !== 'connected') return;- window.Echo.private(`tasks.${taskId}`).listen('TaskEnded', (event: any) => {toast.add(`"${event?.task?.name}" ${event?.task?.status}.`, { type: event?.task?.status_key > 0 ? 'success' : 'danger' });window.Echo.leave(`tasks.${taskId}`);++ setTimeout(() => {+ if (Object.keys(window.Echo?.connector?.channels).length === 0) {+ const { disconnectEcho } = useAppStore();+ disconnectEcho();+ }+ }, 1000);});- return { unsubscribe: () => window.Echo.leave(`tasks.${taskId}`) };++ return {+ unsubscribe: async () => {+ unsubscribeFromChannel(`tasks.${taskId}`, true);+ },+ };}export function subscribeToDaskboardTasks() {+ if (window.Echo == null) return;+window.Echo.private(`dashboard.tasks`).listen('TaskUpdated', (event: any) => {- // console.log(event);- // Update StateTasks??+ if (!window.Echo || window.Echo?.connector?.pusher?.connection?.state !== 'connected') return;if (!event.task) return;const { updateSingleTask } = useDashboardStore();updateSingleTask(event.task);});- return { unsubscribe: () => window.Echo.leave('dashboard.tasks') };+ return {+ unsubscribe: async () => {+ unsubscribeFromChannel('dashboard.tasks');+ },+ };+}++function unsubscribeFromChannel(channel: string, closeOnEmpty: boolean = false) {+ console.log('unsub', channel);++ if (!window.Echo || window.Echo?.connector?.pusher?.connection?.state !== 'connected') return;++ window.Echo.leave(channel);++ if (closeOnEmpty && Object.keys(window.Echo.connector?.channels).length === 0) {+ const { disconnectEcho } = useAppStore();+ disconnectEcho();+ }}/**diff --git a/resources/js/stores/AppStore.ts b/resources/js/stores/AppStore.tsindex 53f61e58..7cb2cd63 100644--- a/resources/js/stores/AppStore.ts+++ b/resources/js/stores/AppStore.ts@@ -1,10 +1,14 @@+import { type ContextMenu as ContextMenuType, type ContextMenuItem, type Broadcaster } from '@/types/types';import { nextTick, ref, useTemplateRef } from 'vue';import { defineStore } from 'pinia';-import { type ContextMenu as ContextMenuType, type ContextMenuItem } from '@/types/types';+import { EchoConfig } from '@/echo.ts';import ContextMenu from '@/components/pinesUI/ContextMenu.vue';+import Echo from 'laravel-echo';export const useAppStore = defineStore('App', () => {+ const ws = ref<Echo<keyof Broadcaster> | null>(null);+const pageTitle = ref('');const lightMode = ref<null | boolean>(null);const ambientMode = ref<null | boolean>(null);@@ -94,6 +98,21 @@ export const useAppStore = defineStore('App', () => {if (contextMenu.value) contextMenu.value.contextMenuToggle(event);};+ const createEcho = () => {+ if (!ws.value) {+ ws.value = new Echo(EchoConfig);+ window.Echo = ws.value;+ }+ return ws;+ };+ const disconnectEcho = () => {+ if (ws.value) {+ ws.value.disconnect();+ ws.value = null;+ window.Echo = null;+ }+ };+return {initDarkMode,toggleDarkMode,@@ -115,5 +134,8 @@ export const useAppStore = defineStore('App', () => {contextMenuItemStyle,contextMenuEvent,setContextMenu,+ createEcho,+ disconnectEcho,+ ws,};});diff --git a/resources/js/stores/DashboardStore.ts b/resources/js/stores/DashboardStore.tsindex 4fa094ff..c1dda424 100644--- a/resources/js/stores/DashboardStore.ts+++ b/resources/js/stores/DashboardStore.ts@@ -1,11 +1,10 @@import { type CategoryResource, type FolderResource, type TaskResource, type UserResource } from '@/types/resources';+import type { TaskStatsResponse } from '@/types/types';-import { ref, watch, type Ref } from 'vue';import { useGetCategories, useGetTasks, useGetTaskStats, useGetUsers } from '@/service/queries';-import { defineStore, storeToRefs } from 'pinia';-import type { TaskStatsResponse } from '@/types/types';+import { ref, watch, type Ref } from 'vue';import { formatFileSize } from '@/service/util';-import { useAuthStore } from './AuthStore';+import { defineStore } from 'pinia';export const useDashboardStore = defineStore('Dashboard', () => {const { data: rawCategories, isLoading: isLoadingLibraries } = useGetCategories();diff --git a/resources/js/types/types.ts b/resources/js/types/types.tsindex 4d66b503..c0b403a8 100644--- a/resources/js/types/types.ts+++ b/resources/js/types/types.ts@@ -1,5 +1,20 @@+import type { NullConnector, PusherConnector, SocketIoConnector } from 'laravel-echo/dist/connector';import type { Component } from 'vue';+import type {+ NullChannel,+ NullEncryptedPrivateChannel,+ NullPresenceChannel,+ NullPrivateChannel,+ PusherChannel,+ PusherEncryptedPrivateChannel,+ PusherPresenceChannel,+ PusherPrivateChannel,+ SocketIoChannel,+ SocketIoPresenceChannel,+ SocketIoPrivateChannel,+} from 'laravel-echo/dist/channel';+export interface HttpResponse {success?: 'true' | 'false';status?: string;@@ -160,3 +175,41 @@ export interface ContextMenu {itemStyle?: string;items?: ContextMenuItem[];}++export declare type Broadcaster = {+ reverb: {+ connector: PusherConnector;+ public: PusherChannel;+ private: PusherPrivateChannel;+ encrypted: PusherEncryptedPrivateChannel;+ presence: PusherPresenceChannel;+ };+ pusher: {+ connector: PusherConnector;+ public: PusherChannel;+ private: PusherPrivateChannel;+ encrypted: PusherEncryptedPrivateChannel;+ presence: PusherPresenceChannel;+ };+ 'socket.io': {+ connector: SocketIoConnector;+ public: SocketIoChannel;+ private: SocketIoPrivateChannel;+ encrypted: never;+ presence: SocketIoPresenceChannel;+ };+ null: {+ connector: NullConnector;+ public: NullChannel;+ private: NullPrivateChannel;+ encrypted: NullEncryptedPrivateChannel;+ presence: NullPresenceChannel;+ };+ function: {+ connector: any;+ public: any;+ private: any;+ encrypted: any;+ presence: any;+ };+};