A self-hosted media server and file management system
Vue ffmpegfile-serverjellyfinlaravelmediamedia-playermedia-servermediabrowsermediaservermusicmusic-librarymusic-playermusicplayerself-hostedvuejs
feat: live user counts using plausible
aminnausina8c5773ad6b4
diff --git a/.env.example b/.env.exampleindex 3b78babb..bfbe55d1 100755--- a/.env.example+++ b/.env.example@@ -99,3 +99,5 @@ VITE_REVERB_SCHEME="${REVERB_SCHEME}"TRUSTED_PROXIES=*PLAUSIBLE_URL=+PLAUSIBLE_SITE_ID="${APP_HOST}"+PLAUSIBLE_API_TOKEN=diff --git a/app/Http/Controllers/Api/V1/UserController.php b/app/Http/Controllers/Api/V1/UserController.phpindex 42510771..99699719 100644--- a/app/Http/Controllers/Api/V1/UserController.php+++ b/app/Http/Controllers/Api/V1/UserController.php@@ -7,7 +7,9 @@ use App\Http\Resources\UserResource;use App\Models\User;use App\Traits\HttpResponses;use Illuminate\Support\Facades\Auth;+use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Log;class UserController extends Controller {use HttpResponses;@@ -56,12 +58,31 @@ class UserController extends Controller {}try {- return- DB::table('sessions')- ->whereNotNull('user_id')- ->count();+ if (! config('services.plausible.token') || ! env('PLAUSIBLE_URL')) {+ return+ DB::table('sessions')+ ->whereNotNull('user_id')+ ->count();+ }++ $cacheKey = 'plausible:realtime:' . now()->format('Hi');++ return Cache::remember($cacheKey, now()->addSeconds(10), function () {+ $response = app('plausible.client')->get('/api/v1/stats/realtime/visitors', [+ 'headers' => ['Authorization' => 'Bearer ' . config('services.plausible.token')],+ 'query' => ['site_id' => config('services.plausible.site_id')],+ ]);++ if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {+ return json_decode($response->getBody(), true);+ }++ Log::error('Plausible API error: ' . $response->getBody());++ return $this->error(0, 'Plausible API error', 500);+ });} catch (\Throwable $th) {- return $this->error(null, 'Unable to get count of logged in of users. Error: ' . $th->getMessage(), 500);+ return $this->error(0, 'Unable to get count of logged in of users. Error: ' . $th->getMessage(), 500);}}}diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.phpindex 381042a9..c76a45c9 100755--- a/app/Providers/AppServiceProvider.php+++ b/app/Providers/AppServiceProvider.php@@ -3,6 +3,7 @@namespace App\Providers;use App\Models\User;+use GuzzleHttp\Client;use Illuminate\Support\Facades\Gate;use Illuminate\Support\ServiceProvider;use Laravel\Pulse\Facades\Pulse;@@ -13,7 +14,15 @@ class AppServiceProvider extends ServiceProvider {* Register any application services.*/public function register(): void {- //+ if (config('services.plausible.token') && config('services.plausible.url')) {+ $this->app->singleton('plausible.client', function () {+ return new Client([+ 'base_uri' => config('services.plausible.domain'),+ 'timeout' => 5, // Seconds+ 'http_errors' => false,+ ]);+ });+ }}/**diff --git a/config/services.php b/config/services.phpindex c35a78e0..9920a6af 100755--- a/config/services.php+++ b/config/services.php@@ -36,6 +36,10 @@ return [],'plausible' => ['url' => env('PLAUSIBLE_URL', ''),+ 'domain' => 'https://' . env('PLAUSIBLE_URL'),+ 'site_id' => env('PLAUSIBLE_SITE_ID'),+ 'token' => env('PLAUSIBLE_API_TOKEN'),+ 'disabled' => true,],];diff --git a/resources/js/components/dashboard/DashboardUsers.vue b/resources/js/components/dashboard/DashboardUsers.vueindex 0e0ec835..05aa6576 100644--- a/resources/js/components/dashboard/DashboardUsers.vue+++ b/resources/js/components/dashboard/DashboardUsers.vue@@ -1,8 +1,12 @@<script setup lang="ts">import type { UserResource } from '@/types/resources';-import { deleteUser, getActiveSessions, getUsers } from '@/service/siteAPI';import { computed, onMounted, ref } from 'vue';+import { useDashboardStore } from '@/stores/DashboardStore';+import { useQueryClient } from '@tanstack/vue-query';+import { storeToRefs } from 'pinia';+import { deleteUser } from '@/service/siteAPI';+import { sortObject } from '@/service/util';import { toast } from '@/service/toaster/toastService';import ButtonText from '@/components/inputs/ButtonText.vue';@@ -13,11 +17,11 @@ 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' });+const queryClient = useQueryClient();+const cachedID = ref<number | null>(null);const searchQuery = ref('');const sortingOptions = ref([{@@ -37,10 +41,7 @@ const sortingOptions = ref([},]);-const activeSessions = ref(0);-const { stateUsers, isLoadingUsers } = storeToRefs(useDashboardStore());--const cachedID = ref<number | null>(null);+const { stateUsers, isLoadingUsers, stateActiveSessions } = storeToRefs(useDashboardStore());const filteredUsers = computed(() => {let tempList = searchQuery.value@@ -58,18 +59,12 @@ const filteredUsers = computed(() => {return tempList;});-const handleSort = async (column = 'date', dir = 1) => {- 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] ?? '');- return (dateB.getTime() - dateA.getTime()) * dir;- }- let valueA = userA[column as keyof UserResource];- let valueB = userB[column as keyof UserResource];- if (valueA && valueB && typeof valueA === 'number' && typeof valueB === 'number') return (valueA - valueB) * dir;- return `${valueA}`?.localeCompare(`${valueB}`) * dir;- });+const handleSort = async (column: keyof UserResource = 'created_at', dir: -1 | 1 = 1) => {+ let tempList = [...stateUsers.value]+ .map((user) => {+ return { ...user, last_active: user.last_active || 0 };+ })+ .sort(sortObject<UserResource>(column as keyof UserResource, dir, ['created_at', 'last_active']));stateUsers.value = tempList;return tempList;};@@ -97,12 +92,8 @@ const submitDelete = async () => {};const loadData = async () => {- const { data: rawActiveSessions } = await getActiveSessions();- activeSessions.value = !isNaN(parseInt(rawActiveSessions)) ? parseInt(rawActiveSessions) : 0;-- // const { data: rawUsers } = await getUsers();-- // stateUsers.value = rawUsers?.data?.length > 0 ? rawUsers.data : [];+ await queryClient.invalidateQueries({ queryKey: ['activeSessions'] });+ await queryClient.invalidateQueries({ queryKey: ['users'] });};onMounted(() => {@@ -133,7 +124,7 @@ onMounted(() => {</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: {{ stateUsers.length }}</p>- <p class="w-fit">Active: {{ activeSessions ?? 0 }}</p>+ <p class="w-fit">Active: {{ stateActiveSessions ?? 0 }}</p></div></div><TableBasediff --git a/resources/js/service/queries.ts b/resources/js/service/queries.tsindex dbae769c..149ab14c 100644--- a/resources/js/service/queries.ts+++ b/resources/js/service/queries.ts@@ -2,7 +2,7 @@ import type { CategoryResource, FolderResource, TaskResource, UserResource } froimport type { PulseResponse, TaskStatsResponse } from '@/types/types.ts';import type { Ref } from 'vue';-import { getSiteAnalytics, getPulse, getUsers, getTasks, getTaskStats } from '@/service/siteAPI.ts';+import { getSiteAnalytics, getPulse, getUsers, getTasks, getTaskStats, getActiveSessions } from '@/service/siteAPI.ts';import { useAuthStore } from '@/stores/AuthStore';import { storeToRefs } from 'pinia';import { useQuery } from '@tanstack/vue-query';@@ -105,6 +105,16 @@ export const useGetTaskStats = () => {});};+export const useGetActiveSessions = () => {+ return useQuery<{ data: number }>({+ queryKey: ['activeSessions'],+ queryFn: async () => {+ const { data: response } = await getActiveSessions();+ return response;+ },+ });+};+// export const useGetChatRoomMessagesQuery = (chat_id: number | null) => {// return useInfiniteQuery({// queryKey: ['chatroom-messages', chat_id],diff --git a/resources/js/service/util.ts b/resources/js/service/util.tsindex 3f4991a6..d9a4b277 100644--- a/resources/js/service/util.ts+++ b/resources/js/service/util.ts@@ -1,3 +1,5 @@+import type { SortDir } from '@/types/types';+export function toTitleCase(str: string) {return str?.toLowerCase().replace(/(?:^|\s)\w/g, function (match) {return match.toUpperCase();@@ -216,8 +218,6 @@ export function isInputLikeElement(element: EventTarget | null, key: string): boreturn inputLikeTags.includes((element as HTMLElement).tagName);}-type SortDir = 1 | -1;-export function sortObject<T>(column: keyof T, direction: SortDir = 1, dateColumns: string[] = ['date', 'date_released']) {return (a: T, b: T): number => {let valueA = a[column];diff --git a/resources/js/stores/DashboardStore.ts b/resources/js/stores/DashboardStore.tsindex 4df0c946..86b5de9f 100644--- a/resources/js/stores/DashboardStore.ts+++ b/resources/js/stores/DashboardStore.ts@@ -1,7 +1,7 @@import { type CategoryResource, type FolderResource, type TaskResource, type UserResource } from '@/types/resources';import type { TaskStatsResponse } from '@/types/types';-import { useGetCategories, useGetLibraryFolders, useGetTasks, useGetTaskStats, useGetUsers } from '@/service/queries';+import { useGetActiveSessions, useGetCategories, useGetLibraryFolders, useGetTasks, useGetTaskStats, useGetUsers } from '@/service/queries';import { ref, watch, type Ref } from 'vue';import { formatFileSize } from '@/service/util';import { defineStore } from 'pinia';@@ -17,11 +17,13 @@ export const useDashboardStore = defineStore('Dashboard', () => {const { data: rawUsers, isLoading: isLoadingUsers } = useGetUsers();const { data: rawTasks, isLoading: isLoadingTasks } = useGetTasks();const { data: rawTaskStats, isLoading: isLoadingTaskStats } = useGetTaskStats();+ const { data: rawActiveSessions, isLoading: isLoadingActiveSessions } = useGetActiveSessions();const stateLibraries = ref<CategoryResource[]>([]);const stateLibraryFolders = ref<FolderResource[]>([]);const stateTasks = ref<TaskResource[]>([]);const stateUsers = ref<UserResource[]>([]);+ const stateActiveSessions = ref<number>(0);const stateTaskStats = ref<TaskStatsResponse>();const stateTotalLibrariesSize = ref();@@ -53,6 +55,11 @@ export const useDashboardStore = defineStore('Dashboard', () => {stateLibraryFolders.value = v.data ?? [];});+ watch(rawActiveSessions, (v: any) => {+ if (isNaN(parseInt(v))) return;+ stateActiveSessions.value = v || 0;+ });+watch(() => route?.params?.id,(URL_ID) => {@@ -84,6 +91,7 @@ export const useDashboardStore = defineStore('Dashboard', () => {stateUsers,stateTaskStats,stateTotalLibrariesSize,+ stateActiveSessions,isLoadingLibraries,isLoadingLibraryFolders,stateLibraryId,@@ -98,6 +106,7 @@ export const useDashboardStore = defineStore('Dashboard', () => {stateUsers: Ref<UserResource[]>;stateTaskStats: Ref<TaskStatsResponse>;stateTotalLibrariesSize: Ref<string>;+ stateActiveSessions: Ref<number>;isLoadingLibraries: Ref<boolean>;isLoadingLibraryFolders: Ref<boolean>;stateLibraryId: Ref<number>;diff --git a/resources/js/types/types.ts b/resources/js/types/types.tsindex b3adf651..464aead3 100644--- a/resources/js/types/types.ts+++ b/resources/js/types/types.ts@@ -241,3 +241,5 @@ export declare type Broadcaster = {presence: any;};};++export declare type SortDir = 1 | -1;diff --git a/resources/js/views/DashboardView.vue b/resources/js/views/DashboardView.vueindex 50d9437d..b84567fa 100644--- a/resources/js/views/DashboardView.vue+++ b/resources/js/views/DashboardView.vue@@ -27,10 +27,11 @@ import ProiconsGraph from '~icons/proicons/graph';import CircumServer from '~icons/circum/server';import LucideUsers from '~icons/lucide/users';-const { stateTaskStats, stateTotalLibrariesSize, stateLibraryId } = storeToRefs(useDashboardStore()) as {+const { stateTaskStats, stateTotalLibrariesSize, stateLibraryId, stateActiveSessions } = storeToRefs(useDashboardStore()) as {stateTaskStats: Ref<TaskStatsResponse>;stateTotalLibrariesSize: Ref<string>;stateLibraryId: Ref<number>;+ stateActiveSessions: Ref<Number>;};const { pageTitle, selectedSideBar } = storeToRefs(useAppStore());const { cycleSideBar } = useAppStore();@@ -70,7 +71,7 @@ const dashboardTabs = computed<{name: 'users',description: '',- info: { value: 'Logged In: ?' },+ info: { value: `Logged In: ${stateActiveSessions?.value ?? '?'}` },icon: LucideUsers,},{diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.phpindex 4702dcfa..fde5908b 100755--- a/resources/views/layouts/app.blade.php+++ b/resources/views/layouts/app.blade.php@@ -7,7 +7,7 @@<meta name="description" content="A self hosted web media server to keep everything in one place."><title>{{ config('app.name', 'Media Server') }}</title>- <script defer data-domain="{{ config('app.host') }}" src="{{ config('services.plausible.url') }}"></script>+ <script defer data-domain="{{ config('app.host') }}" src="{{ config('services.plausible.disabled') ? '' : config('services.plausible.url') }}"></script><script>window.plausible = window.plausible || function() {(window.plausible.q = window.plausible.q || []).push(arguments)