Skip to content

A self-hosted media server and file management system

Queues and usage

aminnausin4dccfbecab5f
diff --git a/app/Http/Controllers/Api/V1/AnalyticsController.php b/app/Http/Controllers/Api/V1/AnalyticsController.php
new file mode 100644
index 00000000..245ef9f1
--- /dev/null
+++ b/app/Http/Controllers/Api/V1/AnalyticsController.php
@@ -0,0 +1,75 @@
+<?php
+
+namespace App\Http\Controllers\Api\V1;
+
+use Carbon\Carbon;
+use App\Http\Controllers\Controller;
+use App\Models\Category;
+use App\Models\Folder;
+use App\Models\Record;
+use App\Models\Tag;
+use App\Models\User;
+use App\Models\Video;
+use App\Traits\HasPeriod;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+
+class AnalyticsController extends Controller {
+ use HasPeriod;
+
+ public function index(Request $request) {
+ $this->period = $request->query('period', '1_hour');
+ $interval = $this->periodAsInterval();
+ $startDate = Carbon::now()->sub($interval);
+
+ try {
+ if (! Auth::user()->id == 1) {
+ return Response('Forbidden', 403);
+ }
+
+ $currentCounts = [
+ 'categories' => Category::count(),
+ 'folders' => Folder::count(),
+ 'videos' => Video::count(),
+ 'users' => User::count(),
+ 'tags' => Tag::count(),
+ 'views' => Record::count(),
+ ];
+
+ $previousCounts = [
+ 'categories' => Category::where('created_at', '<', $startDate)->count(),
+ 'folders' => Folder::where('created_at', '<', $startDate)->count(),
+ 'videos' => Video::where('created_at', '<', $startDate)->count(),
+ 'users' => User::where('created_at', '<', $startDate)->count(),
+ 'tags' => Tag::where('created_at', '<', $startDate)->count(),
+ 'views' => Record::where('created_at', '<', $startDate)->count(),
+ ];
+
+ $changes = [];
+ foreach ($currentCounts as $key => $currentCount) {
+ $previousCount = $previousCounts[$key];
+ $changePercentage = $previousCount > 0 ? (($currentCount - $previousCount) / $previousCount) * 100 : 0;
+ $changes[] = [
+ 'title' => $key,
+ 'count' => $currentCount,
+ 'change' => $currentCount - $previousCounts[$key],
+ 'change_pct' => round($changePercentage, 2),
+ 'prev' => $previousCount
+ ];
+ }
+
+ return ['changes' => $changes, 'period' => $this->periodForHumans()];
+
+ // return [
+ // ['title' => 'categories', 'count' => Category::count()],
+ // ['title' => 'folders', 'count' => Folder::count()],
+ // ['title' => 'videos', 'count' => Video::count()],
+ // ['title' => 'users', 'count' => User::count()],
+ // ['title' => 'tags', 'count' => Tag::count()],
+ // ['title' => 'views', 'count' => Record::count()],
+ // ];
+ } catch (\Throwable $th) {
+ return $this->error(null, 'Unable to get analytics. Error: ' . $th->getMessage(), 500);
+ }
+ }
+}
diff --git a/app/Http/Controllers/Api/V1/SiteController.php b/app/Http/Controllers/Api/V1/SiteController.php
deleted file mode 100644
index 619348a8..00000000
--- a/app/Http/Controllers/Api/V1/SiteController.php
+++ /dev/null
@@ -1,33 +0,0 @@
-<?php
-
-namespace App\Http\Controllers\Api\V1;
-
-use App\Http\Controllers\Controller;
-use App\Models\Category;
-use App\Models\Folder;
-use App\Models\Record;
-use App\Models\Tag;
-use App\Models\User;
-use App\Models\Video;
-use Illuminate\Support\Facades\Auth;
-
-class SiteController extends Controller {
- public function index() {
- try {
- if (! Auth::user()->id == 1) {
- return Response('Forbidden', 403);
- }
-
- return [
- ['title' => 'categories', 'count' => Category::count()],
- ['title' => 'folders', 'count' => Folder::count()],
- ['title' => 'videos', 'count' => Video::count()],
- ['title' => 'users', 'count' => User::count()],
- ['title' => 'tags', 'count' => Tag::count()],
- ['title' => 'views', 'count' => Record::count()],
- ];
- } catch (\Throwable $th) {
- return $this->error(null, 'Unable to get stats. Error: ' . $th->getMessage(), 500);
- }
- }
-}
diff --git a/app/Services/PulseAPI.php b/app/Services/PulseAPI.php
index d65ce1f2..e00a176b 100644
--- a/app/Services/PulseAPI.php
+++ b/app/Services/PulseAPI.php
@@ -3,8 +3,6 @@
namespace App\Services;
use App\Http\Resources\Pulse\CacheResource;
-use Illuminate\Support\Collection;
-use Robertogallea\PulseApi\Enum\PulseResourcesEnum;
use App\Http\Resources\Pulse\ExceptionsResource;
use App\Http\Resources\Pulse\QueueResource;
use App\Http\Resources\Pulse\ServersResource;
@@ -13,6 +11,8 @@ use App\Http\Resources\Pulse\SlowOutgoingRequestsResource;
use App\Http\Resources\Pulse\SlowQueriesResource;
use App\Http\Resources\Pulse\SlowRequestsResource;
use App\Http\Resources\Pulse\UsageResource;
+use Illuminate\Support\Collection;
+use Robertogallea\PulseApi\Enum\PulseResourcesEnum;
class PulseAPI {
public static function getDefaultResources(): Collection {
diff --git a/app/Traits/HasPeriod.php b/app/Traits/HasPeriod.php
new file mode 100644
index 00000000..f598e911
--- /dev/null
+++ b/app/Traits/HasPeriod.php
@@ -0,0 +1,66 @@
+<?php
+
+namespace App\Traits;
+
+use Carbon\CarbonInterval;
+
+trait HasPeriod {
+ /**
+ * The usage period.
+ *
+ * @var '1_hour'|'6_hours'|'24_hours'|'7_days'|null| any valid text
+ */
+ public ?string $period = '1_hour';
+
+ /**
+ * The period as an Interval instance.
+ */
+ public function periodAsInterval(): CarbonInterval {
+ if (!$this->period || !preg_match('/(\d+)_(hours?|days?|weeks?|months?|years?)/', $this->period, $matches)) {
+ return CarbonInterval::hours(24);
+ }
+ // Extract the value and unit from the period string
+ [$fullMatch, $value, $unit] = $matches;
+
+ // Dynamically create the CarbonInterval based on the unit
+ switch ($unit) {
+ case 'hour':
+ case 'hours':
+ return CarbonInterval::hours($value);
+ case 'day':
+ case 'days':
+ return CarbonInterval::hours($value * 24);
+ case 'week':
+ case 'weeks':
+ return CarbonInterval::hours($value * 24 * 7);
+ case 'month':
+ case 'months':
+ return CarbonInterval::hours($value * 24 * 30);
+ case 'year':
+ case 'years':
+ return CarbonInterval::hours($value * 24 * 365);
+ default:
+ return CarbonInterval::hours(1);
+ }
+ // return CarbonInterval::createFromDateString($this->period);
+ // return CarbonInterval::hours(match ($this->period) {
+ // '6_hours' => 6,
+ // '24_hours' => 24,
+ // '7_days' => 168,
+ // default => 1,
+ // });
+ }
+
+ /**
+ * The human friendly representation of the selected period.
+ */
+ public function periodForHumans(): string {
+ return match ($this->period) {
+ '6_hours' => '6 hours',
+ '24_hours' => '24 hours',
+ '7_days' => '7 days',
+ '1_hour' => 'hour',
+ default => str_replace($this->period, '_', ' '),
+ };
+ }
+}
diff --git a/config/pulse-api.php b/config/pulse-api.php
index ab8452b2..53bc886c 100644
--- a/config/pulse-api.php
+++ b/config/pulse-api.php
@@ -37,7 +37,7 @@ return [
|
*/
- 'include_config' => env('PULSE_API_INCLUDE_CONFIG', false),
+ 'include_config' => env('PULSE_API_INCLUDE_CONFIG', true),
/*
|--------------------------------------------------------------------------
diff --git a/database/migrations/2024_12_19_011334_add_created_at_to_categories_videos_folders.php b/database/migrations/2024_12_19_011334_add_created_at_to_categories_videos_folders.php
index 74477c60..adf3b491 100644
--- a/database/migrations/2024_12_19_011334_add_created_at_to_categories_videos_folders.php
+++ b/database/migrations/2024_12_19_011334_add_created_at_to_categories_videos_folders.php
@@ -13,6 +13,7 @@ return new class extends Migration {
public function up() {
Schema::table('categories', function (Blueprint $table) {
$table->timestamp('created_at')->useCurrent()->nullable();
+ $table->unsignedBigInteger('last_scan')->default(0);
});
Schema::table('videos', function (Blueprint $table) {
@@ -21,6 +22,7 @@ return new class extends Migration {
Schema::table('folders', function (Blueprint $table) {
$table->timestamp('created_at')->useCurrent()->nullable();
+ $table->unsignedBigInteger('last_scan')->default(0);
});
}
@@ -32,6 +34,7 @@ return new class extends Migration {
public function down() {
Schema::table('categories', function (Blueprint $table) {
$table->dropColumn('created_at');
+ $table->dropColumn('last_scan');
});
Schema::table('videos', function (Blueprint $table) {
@@ -40,6 +43,7 @@ return new class extends Migration {
Schema::table('folders', function (Blueprint $table) {
$table->dropColumn('created_at');
+ $table->dropColumn('last_scan');
});
}
};
diff --git a/resources/js/components/cards/DashboardCard.vue b/resources/js/components/cards/DashboardCard.vue
new file mode 100644
index 00000000..cd123c65
--- /dev/null
+++ b/resources/js/components/cards/DashboardCard.vue
@@ -0,0 +1,53 @@
+<script setup lang="ts">
+const props = withDefaults(
+ defineProps<{
+ cols?: number | string;
+ rows?: number;
+ class?: string;
+ name?: string;
+ title?: string;
+ details?: string | null;
+ }>(),
+ {
+ cols: 'full',
+ rows: 1,
+ name: '',
+ title: '',
+ details: null,
+ },
+);
+</script>
+<template>
+ <div
+ :class="`flex col-span-${cols} row-span-${rows} flex-col gap-2 p-4 overflow-clip rounded-xl shadow-lg dark:bg-primary-dark-800/70 bg-white ring-1 ring-gray-900/5 w-full ${props.class}`"
+ >
+ <header class="flex flex-wrap justify-between items-center gap-4 mb-3 @md:mb-6">
+ <div class="flex-1 basis-0 flex-grow-[10000] max-w-full">
+ <div class="flex overflow-hidden gap-2 items-start">
+ <div class="[&>svg]:flex-shrink-0 [&>svg]:w-6 [&>svg]:h-6 [&>svg]:stroke-gray-400 [&>svg]:dark:stroke-gray-600">
+ <slot name="icon"></slot>
+ </div>
+ <hgroup class="flex flex-wrap items-baseline gap-x-2 overflow-hidden">
+ <!-- <h2 class="text-base font-bold text-gray-600 dark:text-gray-300 truncate" @if($attributes->
+ has('x-bind:title')) x-bind:title="{{ $attributes->get('x-bind:title') }}" @else :title="{{ title }}" @endif> -->
+ <h2 class="text-base font-bold text-gray-600 dark:text-gray-300 truncate" :title="props.title">
+ {{ props.name }}
+ </h2>
+ <p v-if="props.details" class="text-gray-400 dark:text-gray-600 font-medium truncate">
+ <small class="text-xs">{{ props.details }}</small>
+ </p>
+ </hgroup>
+ </div>
+ </div>
+ <!-- @if ($actions ?? false) -->
+ <div class="flex flex-grow">
+ <div class="w-full flex items-center gap-4">
+ <!-- {{ $actions }} -->
+ <slot name="actions"></slot>
+ </div>
+ </div>
+ <!-- @endif -->
+ </header>
+ <slot name="slot"></slot>
+ </div>
+</template>
diff --git a/resources/js/components/dashboard/DashboardAnalytics.vue b/resources/js/components/dashboard/DashboardAnalytics.vue
new file mode 100644
index 00000000..7f657515
--- /dev/null
+++ b/resources/js/components/dashboard/DashboardAnalytics.vue
@@ -0,0 +1,86 @@
+<script setup lang="ts">
+import type { PulseResponse } from '@/types/types';
+
+import { useGetPulse, useGetSiteAnalytics } from '@/service/queries';
+import { ref, watch } from 'vue';
+
+import PulseServers from '@/components/pulseCards/PulseServers.vue';
+
+import LucideChartNoAxesCombined from '~icons/lucide/chart-no-axes-combined';
+import PulseQueues from '../pulseCards/PulseQueues.vue';
+import DashboardCard from '../cards/DashboardCard.vue';
+import { periodForHumans } from '@/service/util';
+
+const validPeriods: { key: string; value: string }[] = [
+ { key: '1h', value: '1_hour' },
+ { key: '6h', value: '6_hours' },
+ { key: '24h', value: '24_hours' },
+ { key: '7d', value: '7_days' },
+ { key: '30d', value: '30_days' },
+];
+
+const period = ref<string>('1_hour');
+
+const { data: stats, isLoading } = useGetSiteAnalytics(period);
+
+const { data: rawPulseData, isLoading: pulseLoading } = useGetPulse({ period });
+
+const pulseData = ref<PulseResponse>();
+const setPeriod = (newPeriod: string) => {
+ period.value = newPeriod;
+};
+
+watch(
+ () => rawPulseData.value,
+ () => {
+ if (rawPulseData?.value?.data) {
+ pulseData.value = rawPulseData.value.data;
+ }
+ },
+);
+</script>
+<template>
+ <section class="flex flex-wrap gap-4 flex-col">
+ <section class="flex justify-between flex-wrap gap-2">
+ <h4>Website Analytics</h4>
+ <div class="flex items-center flex-wrap gap-2">
+ <h5>Time Period</h5>
+ <button
+ v-for="(validPeriod, index) in validPeriods"
+ :key="index"
+ @click="setPeriod(validPeriod.value)"
+ :class="`font-semibold sm:text-lg ${period === validPeriod.value ? 'text-gray-700 dark:text-gray-300' : 'text-gray-300 dark:text-gray-600'} hover:text-gray-400 dark:hover:text-gray-500`"
+ >
+ {{ validPeriod.key }}
+ </button>
+ </div>
+ </section>
+ <PulseServers :pulseData="pulseData" :isLoading="pulseLoading" />
+ <span class="mx-auto grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-6 w-full">
+ <!-- <StatsCard v-for="stat in stats" :title="`Total ${stat.title}`" :forceCount="stat.count" class="col-span-1 row-span-1 w-full" /> -->
+ <DashboardCard
+ cols="2"
+ :rows="4"
+ :title="'Data changes over time'"
+ :name="'Data Changes'"
+ :details="`past ${periodForHumans(period)}`"
+ >
+ <template #icon>
+ <LucideChartNoAxesCombined class="w-6 h-6 text-gray-400 dark:text-gray-600" />
+ </template>
+ <template #slot>
+ <span v-for="(stat, index) in stats?.changes" :key="index" class="flex gap-2 capitalize items-center flex-wrap">
+ <h3 class="text-sm dark:text-slate-400 text-slate-500 w-full text-nowrap">{{ stat.title }}</h3>
+ <span>
+ <h3 class="text-lg">{{ stat.count ?? 0 }}</h3>
+ </span>
+ <h4 :class="`text-sm ${stat.change >= 0 ? 'text-green-600' : 'text-red-500'} ml-auto`">
+ {{ `${stat.change === 0 ? 'no change' : `${stat.change >= 0 ? '+' : '-'}${stat.change}`}` }}
+ </h4>
+ </span>
+ </template>
+ </DashboardCard>
+ <PulseQueues :pulseData="pulseData" :isLoading="pulseLoading" :period="period" :cols="4" :rows="2" />
+ </span>
+ </section>
+</template>
diff --git a/resources/js/components/dashboard/DashboardContent.vue b/resources/js/components/dashboard/DashboardContent.vue
new file mode 100644
index 00000000..76173e7c
--- /dev/null
+++ b/resources/js/components/dashboard/DashboardContent.vue
@@ -0,0 +1,52 @@
+<script setup lang="ts">
+import type { CategoryResource } from '@/types/resources';
+
+import { onMounted, ref } from 'vue';
+import { getCategories } from '@/service/mediaAPI';
+
+import ButtonText from '@/components/inputs/ButtonText.vue';
+import ButtonIcon from '@/components/inputs/ButtonIcon.vue';
+
+import ProiconsAddCircle from '~icons/proicons/add-circle';
+import CircumEdit from '~icons/circum/edit';
+
+const categories = ref<CategoryResource[]>([]);
+
+onMounted(async () => {
+ const { data: rawCategories } = await getCategories();
+
+ categories.value = rawCategories?.data;
+});
+</script>
+<template>
+ <section>
+ <span class="flex items-center justify-between">
+ <ButtonText title="Add New Category">
+ <template #text>
+ <div class="flex justify-between items-center gap-2">
+ <p class="text-nowrap">Add New Category</p>
+ <ProiconsAddCircle height="24" width="24" />
+ </div>
+ </template>
+ </ButtonText>
+ <p class="text-slate-400 uppercase">Categories: {{ categories.length }}</p>
+ </span>
+ <div class="flex flex-wrap w-full pt-4">
+ <div
+ v-for="(category, index) in categories"
+ :key="index"
+ class="flex flex-col gap-2 p-4 overflow-clip rounded-xl shadow-lg dark:bg-primary-dark-800/70 bg-white ring-1 ring-gray-900/5 w-1/3"
+ >
+ <h3 class="capitalize text-lg flex items-end justify-between">
+ {{ category.name }}
+ <ButtonIcon class="w-6 h-6 !p-1">
+ <template #icon>
+ <CircumEdit class="w-full h-full" />
+ </template>
+ </ButtonIcon>
+ </h3>
+ <p class="text-slate-400">Folders: {{ category.folders_count }}</p>
+ </div>
+ </div>
+ </section>
+</template>
diff --git a/resources/js/components/panels/NavBar.vue b/resources/js/components/panels/NavBar.vue
index 96de4909..fad4c944 100755
--- a/resources/js/components/panels/NavBar.vue
+++ b/resources/js/components/panels/NavBar.vue
@@ -85,7 +85,7 @@ watch(userData, handleAuthEvent, { immediate: false });
</NavButton>
<NavButton
v-if="$route.name === 'home'"
- @click="cycleSideBar('folders')"
+ @click="cycleSideBar('folders', '#list-card')"
:label="'folders'"
:active="selectedSideBar === 'folders'"
:class="`ring-1 ring-gray-900/5`"
@@ -96,7 +96,7 @@ watch(userData, handleAuthEvent, { immediate: false });
</NavButton>
<NavButton
v-if="username && $route.name === 'home'"
- @click="cycleSideBar('history')"
+ @click="cycleSideBar('history', '#list-card')"
:label="'history'"
:active="selectedSideBar === 'history'"
:class="`ring-1 ring-gray-900/5`"
@@ -107,7 +107,7 @@ watch(userData, handleAuthEvent, { immediate: false });
</NavButton>
<NavButton
v-if="username && $route.name === 'dashboard'"
- @click="cycleSideBar('dashboard')"
+ @click="cycleSideBar('dashboard', '#left-card')"
:label="'dashboard'"
:active="selectedSideBar === 'dashboard'"
:class="`ring-1 ring-gray-900/5`"
diff --git a/resources/js/components/pulse/PulseCard.vue b/resources/js/components/pulse/PulseCard.vue
index 4e7d4a3b..6807f6e4 100644
--- a/resources/js/components/pulse/PulseCard.vue
+++ b/resources/js/components/pulse/PulseCard.vue
@@ -1,5 +1,8 @@
<script setup lang="ts">
-const props = defineProps<{ cols?: number; rows?: number }>();
+const props = withDefaults(defineProps<{ cols?: number; rows?: number }>(), {
+ cols: 6,
+ rows: 1,
+});
</script>
<template>
<!-- @props(['cols' => 6, 'rows' => 1]) -->
diff --git a/resources/js/components/pulse/PulseScroll.vue b/resources/js/components/pulse/PulseScroll.vue
index 98bb5145..9b4c17d1 100644
--- a/resources/js/components/pulse/PulseScroll.vue
+++ b/resources/js/components/pulse/PulseScroll.vue
@@ -1,29 +1,42 @@
@props(['expand' => false])
-<div
- x-data="{
- init() {
- $nextTick(() => this.scroll())
- },
- scroll() {
- const { content, fade } = this.$refs
+<script setup lang="ts">
+import { nextTick, onMounted, ref } from 'vue';
- if (! fade) {
- return
- }
+const props = withDefaults(defineProps<{ expand?: boolean; loading: boolean }>(), { expand: false });
+const fade = ref<HTMLDivElement>();
+const content = ref<HTMLDivElement>();
- const distanceToBottom = content.scrollHeight - (content.scrollTop + content.clientHeight)
+function scroll() {
+ if (!fade.value) return;
+ if (!content.value) return;
- if (distanceToBottom >= 24) {
- fade.style.transform = `scaleY(1)`
- } else {
- fade.style.transform = `scaleY(${distanceToBottom / 24})`
- }
- }
- }"
- {{ $attributes->merge(['class' => '@container/scroll-wrapper flex-grow flex w-full overflow-hidden' . ($expand ? '' : ' basis-56'), ':class' => "loading && 'opacity-25 animate-pulse'"]) }}
->
- <div x-ref="content" class="flex-grow basis-full overflow-y-auto scrollbar:w-1.5 scrollbar:h-1.5 scrollbar:bg-transparent scrollbar-track:bg-gray-100 scrollbar-thumb:rounded scrollbar-thumb:bg-gray-300 scrollbar-track:rounded dark:scrollbar-track:bg-gray-500/10 dark:scrollbar-thumb:bg-gray-500/50 supports-scrollbars" @scroll.debounce.5ms="scroll">
- {{ $slot }}
- <div x-ref="fade" class="h-6 origin-bottom fixed bottom-0 left-0 right-0 bg-gradient-to-t from-white dark:from-gray-900 pointer-events-none" wire:ignore></div>
+ const distanceToBottom = content.value.scrollHeight - (content.value.scrollTop + content.value.clientHeight);
+
+ if (distanceToBottom >= 24) {
+ fade.value.style.transform = `scaleY(1)`;
+ } else {
+ fade.value.style.transform = `scaleY(${distanceToBottom / 24})`;
+ }
+}
+onMounted(async () => {
+ await nextTick();
+
+ scroll();
+});
+</script>
+<template>
+ <div :class="`flex-grow flex w-full overflow-hidden ${props.expand ? '' : ' basis-56'} ${loading && 'opacity-25 animate-pulse'}`">
+ <div
+ ref="content"
+ @scroll="scroll"
+ class="flex-grow basis-full overflow-y-auto scrollbar:w-1.5 scrollbar:h-1.5 scrollbar:bg-transparent scrollbar-track:bg-gray-100 scrollbar-thumb:rounded scrollbar-thumb:bg-gray-300 scrollbar-track:rounded dark:scrollbar-track:bg-gray-500/10 dark:scrollbar-thumb:bg-gray-500/50 supports-scrollbars"
+ >
+ <slot name="slot"></slot>
+ <div
+ ref="fade"
+ class="h-6 origin-bottom fixed bottom-0 left-0 right-0 bg-gradient-to-t from-white dark:from-gray-900 pointer-events-none"
+ wire:ignore
+ ></div>
+ </div>
</div>
-</div>
+</template>
diff --git a/resources/js/components/pulseCards/PulseQueues.vue b/resources/js/components/pulseCards/PulseQueues.vue
index 69b40067..1a9ee061 100644
--- a/resources/js/components/pulseCards/PulseQueues.vue
+++ b/resources/js/components/pulseCards/PulseQueues.vue
@@ -1,14 +1,199 @@
-@use('Illuminate\Support\Str')
-<x-pulse::card :cols="$cols" :rows="$rows" :class="$class">
- <x-pulse::card-header
+<script setup lang="ts">
+import type { PulseQueueResponse, PulseResponse, PulseServerResponse } from '@/types/types';
+
+import { periodForHumans, pulseFormatDate } from '@/service/util';
+import { ref, watch } from 'vue';
+
+import IconQueueList from '../icons/IconQueueList.vue';
+import DashboardCard from '../cards/DashboardCard.vue';
+import PulseNoResults from '../pulse/PulseNoResults.vue';
+import PulseScroll from '../pulse/PulseScroll.vue';
+import PulseLineChart from '../charts/PulseLineChart.vue';
+
+const props = withDefaults(
+ defineProps<{
+ cols?: number | string;
+ rows?: number;
+ class?: string;
+ pulseData?: PulseResponse;
+ isLoading?: boolean;
+ period: string;
+ }>(),
+ {
+ cols: 2,
+ rows: 4,
+ },
+);
+
+const queues = ref<{ [key: string]: PulseQueueResponse }>();
+
+function scale(data: { [key: string]: any }) {
+ console.log(Object.values(data).map((value) => value * (1 / (props.pulseData?.queues?.config.sample_rate ?? 1))));
+
+ return Object.values(data).map((value) => value * (1 / (props.pulseData?.queues?.config.sample_rate ?? 1)));
+}
+
+function getMaxReading(readings: { [key: string]: { [key: string]: string | null } }): number {
+ // Flatten the nested object structure and convert values to numbers
+ const flattenedValues = Object.values(readings).flatMap((queue) => Object.values(queue));
+ const numberValues = flattenedValues.map((value) => (value !== null && !isNaN(Number(value)) ? Number(value) : -Infinity));
+ return Math.max(...numberValues);
+}
+
+watch(
+ () => props.pulseData,
+ () => {
+ if (props.pulseData?.queues) {
+ queues.value = props.pulseData.queues.queues;
+ }
+ },
+);
+// Alpine.data(
+// 'queueChart',
+// (config: {
+// readings: { queued: any; processing: any; released: any; processed: any; failed: any };
+// sampleRate: number;
+// queue: string | number;
+// }) => ({
+// init() {
+// let chart = new Chart(this.$refs.canvas, {
+// type: 'line',
+// data: {
+// labels: this.labels(config.readings),
+// datasets: [
+// {
+// label: 'Queued',
+// borderColor: 'rgba(107,114,128,0.5)',
+// data: this.scale(config.readings.queued),
+// order: 4,
+// },
+// {
+// label: 'Processing',
+// borderColor: 'rgba(147,51,234,0.5)',
+// data: this.scale(config.readings.processing),
+// order: 3,
+// },
+// {
+// label: 'Released',
+// borderColor: '#eab308',
+// data: this.scale(config.readings.released),
+// order: 2,
+// },
+// {
+// label: 'Processed',
+// borderColor: '#9333ea',
+// data: this.scale(config.readings.processed),
+// order: 1,
+// },
+// {
+// label: 'Failed',
+// borderColor: '#e11d48',
+// data: this.scale(config.readings.failed),
+// order: 0,
+// },
+// ],
+// },
+// options: {
+// maintainAspectRatio: false,
+// layout: {
+// autoPadding: false,
+// padding: {
+// top: 1,
+// },
+// },
+// datasets: {
+// line: {
+// borderWidth: 2,
+// borderCapStyle: 'round',
+// pointHitRadius: 10,
+// pointStyle: false,
+// tension: 0.2,
+// spanGaps: false,
+// segment: {
+// borderColor: (ctx: { p0: { raw: number }; p1: { raw: number } }) =>
+// ctx.p0.raw === 0 && ctx.p1.raw === 0 ? 'transparent' : undefined,
+// },
+// },
+// },
+// scales: {
+// x: {
+// display: false,
+// },
+// y: {
+// display: false,
+// min: 0,
+// max: this.highest(config.readings),
+// },
+// },
+// plugins: {
+// legend: {
+// display: false,
+// },
+// tooltip: {
+// mode: 'index',
+// position: 'nearest',
+// intersect: false,
+// callbacks: {
+// beforeBody: (context: any[]) =>
+// context
+// .map(
+// (item: { dataset: { label: any }; formattedValue: any }) =>
+// `${item.dataset.label}: ${config.sampleRate < 1 ? '~' : ''}${item.formattedValue}`,
+// )
+// .join(', '),
+// label: () => null,
+// },
+// },
+// },
+// },
+// });
+
+// Livewire.on('queues-chart-update', ({ queues }) => {
+// if (chart === undefined) {
+// return;
+// }
+
+// if (queues[config.queue] === undefined && chart) {
+// chart.destroy();
+// chart = undefined;
+// return;
+// }
+
+// chart.data.labels = this.labels(queues[config.queue]);
+// chart.options.scales.y.max = this.highest(queues[config.queue]);
+// chart.data.datasets[0].data = this.scale(queues[config.queue].queued);
+// chart.data.datasets[1].data = this.scale(queues[config.queue].processing);
+// chart.data.datasets[2].data = this.scale(queues[config.queue].released);
+// chart.data.datasets[3].data = this.scale(queues[config.queue].processed);
+// chart.data.datasets[4].data = this.scale(queues[config.queue].failed);
+// chart.update();
+// });
+// },
+// labels(readings: { queued: {} }) {
+// return Object.keys(readings.queued).map(formatDate);
+// },
+// scale(data: { [s: string]: unknown } | ArrayLike<unknown>) {
+// return Object.values(data).map((value) => value * (1 / config.sampleRate));
+// },
+// highest(readings: { [s: string]: unknown } | ArrayLike<unknown>) {
+// return Math.max(...Object.values(readings).map((dataset) => Math.max(...Object.values(dataset)))) * (1 / config.sampleRate);
+// },
+// }),
+// );
+</script>
+<template>
+ <DashboardCard
+ :cols="cols"
+ :rows="rows"
+ :class="props.class"
name="Queues"
- x-bind:title="`Time: {{ number_format($time) }}ms; Run at: ${formatDate('{{ $runAt }}')};`"
- details="past {{ $this->periodForHumans() }}"
+ title="`Time: {{ number_format($time) }}ms; Run at: ${formatDate('{{ $runAt }}')};`"
+ :details="`past ${periodForHumans(period)}`"
>
- <x-slot:icon>
- <x-pulse::icons.queue-list />
- </x-slot:icon>
- <x-slot:actions>
+ <template #icon>
+ <IconQueueList />
+ </template>
+ <template #actions>
<div class="flex flex-wrap gap-4">
<div class="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400 font-medium">
<div class="h-0.5 w-3 rounded-full bg-[rgba(107,114,128,0.5)]"></div>
@@ -31,179 +216,137 @@
Failed
</div>
</div>
- </x-slot:actions>
- </x-pulse::card-header>
-
- <x-pulse::scroll :expand="$expand" wire:poll.5s="">
- @if ($queues->isEmpty())
- <x-pulse::no-results />
- @else
- <div class="grid gap-3 mx-px mb-px">
- @foreach ($queues as $queue => $readings)
- <div wire:key="{{ $queue }}">
- <h3 class="font-bold text-gray-700 dark:text-gray-300">
- @if ($showConnection)
- {{ $queue }}
- @else
- {{ Str::after($queue, ':') }}
- @endif
- </h3>
- @php
- $highest = $readings->flatten()->max();
- @endphp
+ </template>
- <div class="mt-3 relative">
- <div class="absolute -left-px -top-2 max-w-fit h-4 flex items-center px-1 text-xs leading-none text-white font-bold bg-purple-500 rounded after:[--triangle-size:4px] after:border-l-purple-500 after:absolute after:right-[calc(-1*var(--triangle-size))] after:top-[calc(50%-var(--triangle-size))] after:border-t-[length:var(--triangle-size)] after:border-b-[length:var(--triangle-size)] after:border-l-[length:var(--triangle-size)] after:border-transparent">
- @if ($config['sample_rate'] < 1)
- <span title="Sample rate: {{ $config['sample_rate'] }}, Raw value: {{ number_format($highest) }}">~{{ number_format($highest * (1 / $config['sample_rate'])) }}</span>
- @else
- {{ number_format($highest) }}
- @endif
- </div>
+ <template #slot>
+ <PulseScroll :expand="true" :loading="isLoading ?? true">
+ <template #slot>
+ <PulseNoResults v-if="!queues || (Object.keys(queues)?.length ?? 0) == 0" />
+ <div v-else-if="queues" class="grid gap-3 mx-px mb-px">
+ <div v-for="queue in Object.keys(queues)" :key="queue">
+ <h3 class="font-bold text-gray-700 dark:text-gray-300">
+ <template v-if="pulseData?.queues?.showConnection">
+ {{ queue }}
+ </template>
+ <template v-else>
+ {{ queue.substring(queue.indexOf(':') + 1) }}
+ </template>
+ </h3>
+ <div class="mt-3 relative">
+ <div
+ class="absolute -left-px -top-2 max-w-fit h-4 flex items-center px-1 text-xs leading-none text-white font-bold bg-purple-500 rounded after:[--triangle-size:4px] after:border-l-purple-500 after:absolute after:right-[calc(-1*var(--triangle-size))] after:top-[calc(50%-var(--triangle-size))] after:border-t-[length:var(--triangle-size)] after:border-b-[length:var(--triangle-size)] after:border-l-[length:var(--triangle-size)] after:border-transparent"
+ >
+ <span
+ v-if="pulseData?.queues?.config.sample_rate && pulseData.queues.config.sample_rate < 1"
+ :title="`Sample rate: ${pulseData.queues.config.sample_rate}, Raw value: ${Intl.NumberFormat().format(getMaxReading(queues[queue]))}`"
+ >~{{
+ Intl.NumberFormat().format(
+ getMaxReading(queues[queue]) * (1 / pulseData.queues.config.sample_rate),
+ )
+ }}</span
+ >
+ <template v-else>
+ {{ Intl.NumberFormat().format(getMaxReading(queues[queue])) }}
+ </template>
+ </div>
- <div
- wire:ignore
- class="h-14"
- x-data="queueChart({
- queue: '{{ $queue }}',
- readings: @js($readings),
- sampleRate: {{ $config['sample_rate'] }},
- })"
- >
- <canvas x-ref="canvas" class="ring-1 ring-gray-900/5 dark:ring-gray-100/10 bg-gray-50 dark:bg-gray-800 rounded-md shadow-sm"></canvas>
+ <div class="h-14">
+ <PulseLineChart
+ :chart-data="{
+ labels: Object.keys(queues[queue].queued).map((v) => pulseFormatDate(v)),
+ datasets: [
+ {
+ label: 'Queued',
+ borderColor: 'rgba(107,114,128,0.5)',
+ data: scale(queues[queue].queued),
+ order: 4,
+ },
+ {
+ label: 'Processing',
+ borderColor: 'rgba(147,51,234,0.5)',
+ data: scale(queues[queue].processing),
+ order: 3,
+ },
+ {
+ label: 'Released',
+ borderColor: '#eab308',
+ data: scale(queues[queue].released),
+ order: 2,
+ },
+ {
+ label: 'Processed',
+ borderColor: '#9333ea',
+ data: scale(queues[queue].processed),
+ order: 1,
+ },
+ {
+ label: 'Failed',
+ borderColor: '#e11d48',
+ data: scale(queues[queue].failed),
+ order: 0,
+ },
+ ],
+ }"
+ :chart-options="{
+ maintainAspectRatio: false,
+ layout: {
+ autoPadding: false,
+ padding: {
+ top: 1,
+ },
+ },
+ datasets: {
+ line: {
+ borderWidth: 2,
+ borderCapStyle: 'round',
+ pointHitRadius: 10,
+ pointStyle: false,
+ tension: 0.2,
+ spanGaps: false,
+ segment: {
+ borderColor: (ctx: any) =>
+ ctx.p0.raw === 0 && ctx.p1.raw === 0 ? 'transparent' : undefined,
+ },
+ },
+ },
+ scales: {
+ x: {
+ display: false,
+ },
+ y: {
+ display: false,
+ min: 0,
+ max: getMaxReading(queues[queue]),
+ },
+ },
+ plugins: {
+ legend: {
+ display: false,
+ },
+ tooltip: {
+ mode: 'index',
+ position: 'nearest',
+ intersect: false,
+ callbacks: {
+ beforeBody: (context: any[]) => {
+ return context
+ .map((item) => {
+ return `${item.dataset.label}: ${(pulseData?.queues?.config.sample_rate ?? 2) < 1 ? '~' : ''}${item.formattedValue}`;
+ })
+ .join(', ');
+ },
+ label: () => null,
+ },
+ },
+ },
+ }"
+ />
+ </div>
</div>
</div>
</div>
- @endforeach
- </div>
- @endif
- </x-pulse::scroll>
-</x-pulse::card>
-
-@script
-<script>
-Alpine.data('queueChart', (config) => ({
- init() {
- let chart = new Chart(
- this.$refs.canvas,
- {
- type: 'line',
- data: {
- labels: this.labels(config.readings),
- datasets: [
- {
- label: 'Queued',
- borderColor: 'rgba(107,114,128,0.5)',
- data: this.scale(config.readings.queued),
- order: 4,
- },
- {
- label: 'Processing',
- borderColor: 'rgba(147,51,234,0.5)',
- data: this.scale(config.readings.processing),
- order: 3,
- },
- {
- label: 'Released',
- borderColor: '#eab308',
- data: this.scale(config.readings.released),
- order: 2,
- },
- {
- label: 'Processed',
- borderColor: '#9333ea',
- data: this.scale(config.readings.processed),
- order: 1,
- },
- {
- label: 'Failed',
- borderColor: '#e11d48',
- data: this.scale(config.readings.failed),
- order: 0,
- },
- ],
- },
- options: {
- maintainAspectRatio: false,
- layout: {
- autoPadding: false,
- padding: {
- top: 1,
- },
- },
- datasets: {
- line: {
- borderWidth: 2,
- borderCapStyle: 'round',
- pointHitRadius: 10,
- pointStyle: false,
- tension: 0.2,
- spanGaps: false,
- segment: {
- borderColor: (ctx) => ctx.p0.raw === 0 && ctx.p1.raw === 0 ? 'transparent' : undefined,
- }
- }
- },
- scales: {
- x: {
- display: false,
- },
- y: {
- display: false,
- min: 0,
- max: this.highest(config.readings),
- },
- },
- plugins: {
- legend: {
- display: false,
- },
- tooltip: {
- mode: 'index',
- position: 'nearest',
- intersect: false,
- callbacks: {
- beforeBody: (context) => context
- .map(item => `${item.dataset.label}: ${config.sampleRate < 1 ? '~' : ''}${item.formattedValue}`)
- .join(', '),
- label: () => null,
- },
- },
- },
- },
- }
- )
-
- Livewire.on('queues-chart-update', ({ queues }) => {
- if (chart === undefined) {
- return
- }
-
- if (queues[config.queue] === undefined && chart) {
- chart.destroy()
- chart = undefined
- return
- }
-
- chart.data.labels = this.labels(queues[config.queue])
- chart.options.scales.y.max = this.highest(queues[config.queue])
- chart.data.datasets[0].data = this.scale(queues[config.queue].queued)
- chart.data.datasets[1].data = this.scale(queues[config.queue].processing)
- chart.data.datasets[2].data = this.scale(queues[config.queue].released)
- chart.data.datasets[3].data = this.scale(queues[config.queue].processed)
- chart.data.datasets[4].data = this.scale(queues[config.queue].failed)
- chart.update()
- })
- },
- labels(readings) {
- return Object.keys(readings.queued).map(formatDate)
- },
- scale(data) {
- return Object.values(data).map(value => value * (1 / config.sampleRate ))
- },
- highest(readings) {
- return Math.max(...Object.values(readings).map(dataset => Math.max(...Object.values(dataset)))) * (1 / config.sampleRate)
- }
-}))
-</script>
-@endscript
+ </template>
+ </PulseScroll>
+ </template>
+ </DashboardCard>
+</template>
diff --git a/resources/js/components/pulseCards/PulseServers.vue b/resources/js/components/pulseCards/PulseServers.vue
index 75f09305..701a47ff 100644
--- a/resources/js/components/pulseCards/PulseServers.vue
+++ b/resources/js/components/pulseCards/PulseServers.vue
@@ -1,7 +1,6 @@
<script setup lang="ts">
import type { PulseResponse, PulseServerResponse } from '@/types/types.ts';
-import { useGetPulse } from '@/service/queries';
import { toTimeSpan } from '@/service/util';
import { ref, watch } from 'vue';
@@ -10,16 +9,13 @@ import IconServer from '../icons/IconServer.vue';
import PulseLineChart from '../charts/PulseLineChart.vue';
import PulseDoughnutChart from '../charts/PulseDoughnutChart.vue';
-const { data, isLoading } = useGetPulse({ type: 'servers', period: '24_hours' });
-
-const pulseData = ref<PulseResponse>();
-const servers = ref<{ [key: string]: PulseServerResponse }>();
-
const props = withDefaults(
defineProps<{
cols?: number | string;
rows?: number;
class?: string;
+ pulseData?: PulseResponse;
+ isLoading?: boolean;
}>(),
{
cols: 'full',
@@ -27,6 +23,8 @@ const props = withDefaults(
},
);
+const servers = ref<{ [key: string]: PulseServerResponse }>();
+
function friendlySize(mb: number, precision: number = 0) {
if (!mb && mb !== 0) return '';
if (mb >= 1024 * 1024) {
@@ -39,13 +37,10 @@ function friendlySize(mb: number, precision: number = 0) {
}
watch(
- () => data.value,
+ () => props.pulseData,
() => {
- if (data?.value?.data) {
- pulseData.value = data.value.data;
- }
- if (data?.value?.data?.servers) {
- servers.value = data.value.data.servers.servers;
+ if (props.pulseData?.servers) {
+ servers.value = props.pulseData.servers.servers;
}
},
);
diff --git a/resources/js/layouts/LayoutBase.vue b/resources/js/layouts/LayoutBase.vue
index 2d8fa21b..6aace798 100755
--- a/resources/js/layouts/LayoutBase.vue
+++ b/resources/js/layouts/LayoutBase.vue
@@ -8,7 +8,7 @@ import { storeToRefs } from 'pinia';
import { ref } from 'vue';
const appStore = useAppStore();
-const { selectedSideBar, scrollLock } = storeToRefs(appStore);
+const { selectedSideBar, sideBarTarget, scrollLock } = storeToRefs(appStore);
const scrollBody = ref(null);
// const scrollLocked = useScrollLock(scrollBody);
@@ -25,8 +25,7 @@ const scrollBody = ref(null);
>
<section
id="left-card"
- :class="{ invisible: !selectedSideBar }"
- class="col-span-1 h-fit order-2 lg:order-1 bg-primary-900 dark:bg-primary-dark-900 dark:text-[#e2e0e2] shadow-xl rounded-2xl space-y-2 scroll-mt-6 z-20 ring-1 ring-gray-900/5"
+ :class="`col-span-1 h-fit order-2 lg:order-1 bg-primary-900 dark:bg-primary-dark-900 dark:text-[#e2e0e2] shadow-xl rounded-2xl space-y-2 scroll-mt-6 z-20 ring-gray-900/5 ${selectedSideBar && sideBarTarget === '#left-card' ? 'ring-1' : 'invisible'}`"
>
<slot name="leftSidebar"></slot>
</section>
@@ -40,8 +39,7 @@ const scrollBody = ref(null);
</section>
<section
id="list-card"
- :class="{ invisible: !selectedSideBar }"
- class="col-span-1 h-fit order-3 bg-primary-900 dark:bg-primary-dark-900 dark:text-[#e2e0e2] shadow-xl rounded-2xl space-y-2 scroll-mt-6 z-20 ring-1 ring-gray-900/5"
+ :class="`col-span-1 h-fit order-3 bg-primary-900 dark:bg-primary-dark-900 dark:text-[#e2e0e2] shadow-xl rounded-2xl space-y-2 scroll-mt-6 z-20 ring-1 ring-gray-900/5 ${selectedSideBar && sideBarTarget === '#list-card' ? 'ring-1' : 'invisible'}`"
>
<!-- w-full h-fit lg:w-1/6 lg:max-w-72 sm:min-w-32 shrink-0 -->
<!-- class="bg-primary-900 dark:bg-primary-dark-900 dark:text-[#e2e0e2] shadow-xl p-3 rounded-2xl w-full h-fit lg:w-1/6 lg:max-w-72 sm:min-w-32 shrink-0 space-y-2 scroll-mt-6 z-20 ring-1 ring-gray-900/5" -->
diff --git a/resources/js/service/queries.ts b/resources/js/service/queries.ts
index 15fad0c1..729150a5 100644
--- a/resources/js/service/queries.ts
+++ b/resources/js/service/queries.ts
@@ -1,7 +1,7 @@
-import type { PulseResponse } from '@/types/types.ts';
+import type { PulseResponse, SiteAnalyticsResponse } from '@/types/types.ts';
import type { Ref } from 'vue';
-import { getPulse } from '@/service/siteAPI.ts';
+import { getSiteAnalytics, getPulse } from '@/service/siteAPI.ts';
import { useQuery } from '@tanstack/vue-query';
import mediaAPI from '@/service/mediaAPI.ts';
@@ -26,16 +26,27 @@ export const useVideoPlayback = (idRef: Ref<number, number>) => {
});
};
-export const useGetPulse = (req?: { type?: string; period?: '' | '1_hour' | '6_hours' | '24_hours' | '7_days' }) => {
+export const useGetPulse = (req: { type?: string; period: Ref<string> }) => {
return useQuery<{ data: PulseResponse }>({
- queryKey: ['pulse'],
+ queryKey: ['pulse', req.period],
queryFn: async () => {
- const { data: response } = await getPulse(req);
+ const { data: response } = await getPulse({ type: req.type, period: req.period.value });
return response;
},
});
};
+export const useGetSiteAnalytics = (period: Ref<string>) => {
+ return useQuery({
+ queryKey: ['siteAnalytics', period],
+ queryFn: async () => {
+ const { data: response } = await getSiteAnalytics(period.value);
+ return response;
+ },
+ // enabled: !!period,
+ });
+};
+
// export const useGetChatRoomMessagesQuery = (chat_id: number | null) => {
// return useInfiniteQuery({
// queryKey: ['chatroom-messages', chat_id],
diff --git a/resources/js/service/siteAPI.ts b/resources/js/service/siteAPI.ts
index 89a28651..d658805f 100644
--- a/resources/js/service/siteAPI.ts
+++ b/resources/js/service/siteAPI.ts
@@ -7,10 +7,10 @@
*/
import { API } from './api';
-export function getStats() {
- return API.get(`/site/`);
+export function getSiteAnalytics(period?: string) {
+ return API.get(`/analytics${period ? `?period=${period}` : ''}`);
}
-export function getPulse(req?: { type?: string; period?: '' | '1_hour' | '6_hours' | '24_hours' | '7_days' }) {
+export function getPulse(req?: { type?: string; period?: string }) {
return API.get(`/pulse${req?.type ? `/${req?.type}` : ''}${req?.period ? `?period=${req?.period}` : ''}`);
}
diff --git a/resources/js/service/util.ts b/resources/js/service/util.ts
index 59ff770a..1ca8eaf8 100644
--- a/resources/js/service/util.ts
+++ b/resources/js/service/util.ts
@@ -59,3 +59,29 @@ export function toCalendarFormattedDate(date: string) {
return rawDate.toLocaleDateString('en-CA', { month: 'long', day: '2-digit', year: 'numeric' }).replaceAll('.', '');
}
+
+export function pulseFormatDate(value: string = '') {
+ if (value.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/) === null) {
+ throw new Error(`Unknown date format [${value}].`);
+ }
+
+ const [date, time] = value.split(' ');
+ const [year, month, day] = date.split('-').map(Number);
+ const [hour, minute, second] = time.split(':').map(Number);
+
+ return new Date(Date.UTC(year, month - 1, day, hour, minute, second, 0)).toLocaleString(undefined, {
+ year: '2-digit',
+ day: '2-digit',
+ month: '2-digit',
+ hourCycle: 'h24',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ timeZoneName: 'short',
+ });
+}
+
+export function periodForHumans(period: string) {
+ if (period === '1_hour') return 'hour';
+ return period.replace('_', ' ');
+}
diff --git a/resources/js/stores/AppStore.ts b/resources/js/stores/AppStore.ts
index 1f85b4b5..a149b179 100644
--- a/resources/js/stores/AppStore.ts
+++ b/resources/js/stores/AppStore.ts
@@ -1,5 +1,5 @@
+import { nextTick, ref } from 'vue';
import { defineStore } from 'pinia';
-import { ref } from 'vue';
export const useAppStore = defineStore('App', () => {
const pageTitle = ref('');
@@ -7,6 +7,7 @@ export const useAppStore = defineStore('App', () => {
const ambientMode = ref<null | boolean>(null);
const playbackHeatmap = ref<null | boolean>(null);
const selectedSideBar = ref('');
+ const sideBarTarget = ref('');
const scrollLock = ref(false);
function toggleDarkMode() {
@@ -51,13 +52,19 @@ export const useAppStore = defineStore('App', () => {
localStorage.setItem('playbackHeatmap', booleanToString(playbackHeatmap.value));
}
- function cycleSideBar(target = '') {
+ async function cycleSideBar(target = '', scrollTarget: '' | '#left-card' | '#list-card' | 'root' = '') {
+ sideBarTarget.value = scrollTarget;
+
if (selectedSideBar.value === target) {
selectedSideBar.value = '';
document.getElementById('root')?.scrollIntoView({ behavior: 'smooth' });
return;
}
selectedSideBar.value = target;
+ if (scrollTarget) {
+ await nextTick();
+ document.getElementById(scrollTarget)?.scrollIntoView({ behavior: 'smooth' });
+ }
}
function setScrollLock(state = false) {
@@ -80,6 +87,7 @@ export const useAppStore = defineStore('App', () => {
playbackHeatmap,
cycleSideBar,
selectedSideBar,
+ sideBarTarget,
pageTitle,
scrollLock,
setScrollLock,
diff --git a/resources/js/types/types.ts b/resources/js/types/types.ts
index 20cedc94..a8e7ea57 100644
--- a/resources/js/types/types.ts
+++ b/resources/js/types/types.ts
@@ -6,19 +6,43 @@ export interface HttpResponse {
}
export interface PulseResponse {
- cache?: any;
+ cache: {
+ allTime: number;
+ allRunAt: string;
+ allCacheInteractions: {
+ hits: number;
+ misses: number;
+ };
+ keyTime: number;
+ keyRunAt: string;
+ cacheKeyInteractions: [];
+ };
exceptions?: any;
- queues?: any;
+ queues?: {
+ queues: { [key: string]: PulseQueueResponse };
+ showConnection: boolean;
+ time: number;
+ runAt: string;
+ config: {
+ enabled: boolean;
+ sample_rate: number;
+ ignore: any[];
+ };
+ };
servers?: {
servers: { [key: string]: PulseServerResponse };
- runAt: string;
time: number;
+ runAt: string;
};
slow_jobs?: any;
slow_outgoing_requests?: any;
slow_queries?: any;
slow_requests?: any;
- usage?: any;
+ usage: {
+ userRequestCounts: PulseUsageResponse[];
+ time: number;
+ runAt: string;
+ };
}
export interface PulseServerResponse {
@@ -35,6 +59,32 @@ export interface PulseServerResponse {
time: number;
}
+export interface PulseQueueResponse {
+ [key: string]: { [key: string]: string | null };
+ // queued: { [key: string]: string | null };
+ // processing: { [key: string]: string | null };
+ // processed: { [key: string]: string | null };
+ // released: { [key: string]: string | null };
+ // failed: { [key: string]: string | null };
+}
+
+export interface PulseUsageResponse {
+ key: number;
+ user: {
+ name: string;
+ extra: string;
+ };
+ count: number;
+}
+
+export interface SiteAnalyticsResponse {
+ title: string;
+ count: number;
+ change: number;
+ change_pct: number;
+ prev: number;
+}
+
export interface ChartData {
labels: string[];
}
diff --git a/resources/js/views/DashboardView.vue b/resources/js/views/DashboardView.vue
index dbeb4ce9..45cd4bc0 100644
--- a/resources/js/views/DashboardView.vue
+++ b/resources/js/views/DashboardView.vue
@@ -1,24 +1,14 @@
<script setup lang="ts">
-import type { CategoryResource } from '@/types/resources';
-
-import { nextTick, onMounted, ref, watch } from 'vue';
-import { getCategories } from '@/service/mediaAPI';
+import { onMounted, ref } from 'vue';
import { useAppStore } from '@/stores/AppStore';
import { storeToRefs } from 'pinia';
-import { getStats } from '@/service/siteAPI';
-import PulseServers from '@/components/pulseCards/PulseServers.vue';
-import ButtonText from '@/components/inputs/ButtonText.vue';
-import ButtonIcon from '@/components/inputs/ButtonIcon.vue';
+import DashboardAnalytics from '@/components/dashboard/DashboardAnalytics.vue';
+import DashboardContent from '@/components/dashboard/DashboardContent.vue';
import LayoutBase from '@/layouts/LayoutBase.vue';
import ModalBase from '@/components/pinesUI/ModalBase.vue';
-import StatsCard from '@/components/cards/StatsCard.vue';
import useModal from '@/composables/useModal';
-import LucideChartNoAxesCombined from '~icons/lucide/chart-no-axes-combined?width=24px&height=24px';
-import ProiconsAddCircle from '~icons/proicons/add-circle?width=24px&height=24px';
-import CircumEdit from '~icons/circum/edit';
-
const dashboardPages = [
{ title: 'overview', timeControls: true },
{ title: 'content', timeControls: false },
@@ -27,110 +17,29 @@ const dashboardPages = [
{ title: 'jobs', timeControls: false },
];
-const cancelModal = useModal({ title: 'Cancel Job?', submitText: 'Confim' });
-const appStore = useAppStore();
-const stats = ref<{ title: string; count: number }[]>([]);
-const categories = ref<CategoryResource[]>([]);
const dashboardPage = ref('overview');
-const { pageTitle, selectedSideBar } = storeToRefs(appStore);
-
+const cancelModal = useModal({ title: 'Cancel Job?', submitText: 'Confim' });
+const AppStore = useAppStore();
+const { cycleSideBar } = AppStore;
+const { pageTitle, selectedSideBar } = storeToRefs(AppStore);
const handleCancel = () => {
// cachedID.value = id;
cancelModal.toggleModal(true);
};
-const setPeriod = (period: string) => {
- let query = new URLSearchParams(window.location.search);
- if (period === '1_hour') {
- query.delete('period');
- } else {
- query.set('period', period);
- }
-
- // window.location = `${location.pathname}?${query}`;
-};
-
-async function cycleSideBar(state: string) {
- if (!state) return;
- await nextTick();
- document.querySelector('#left-card')?.scrollIntoView({ behavior: 'smooth' });
-}
-
onMounted(async () => {
pageTitle.value = 'Dashboard';
- selectedSideBar.value = 'dashboard';
-
- const { data } = await getStats();
- stats.value = data;
-
- const { data: rawCategories } = await getCategories();
-
- categories.value = rawCategories?.data;
+ cycleSideBar('dashboard', '#left-card');
});
-watch(() => selectedSideBar.value, cycleSideBar, { immediate: false });
</script>
<template>
<LayoutBase>
<template v-slot:content>
<section id="content-dashboard" class="min-h-[80vh]">
- <section class="flex flex-wrap gap-4 flex-col" v-if="dashboardPage == 'overview'">
- <PulseServers />
- <span class="mx-auto grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-6 w-full">
- <StatsCard
- v-for="stat in stats"
- :title="`Total ${stat.title}`"
- :forceCount="stat.count"
- class="col-span-1 row-span-1 w-full"
- />
- <div
- :class="`flex col-span-2 row-span-4 flex-col gap-2 p-4 overflow-clip rounded-xl shadow-lg dark:bg-primary-dark-800/70 bg-white ring-1 ring-gray-900/5 w-full`"
- >
- <span class="flex items-center gap-2 w-full">
- <LucideChartNoAxesCombined class="h-6 w-6"></LucideChartNoAxesCombined>
- <p class="max-w-full text-nowrap">Totals</p>
- </span>
- <span v-for="(stat, index) in stats" :key="index" class="flex gap-2 capitalize items-center flex-wrap">
- <h3 class="text-sm dark:text-slate-400 text-slate-500 w-full text-nowrap">Total {{ stat.title }}</h3>
- <span>
- <h3 class="text-lg">{{ stat.count ?? 0 }}</h3>
- </span>
- <h4 class="text-sm text-green-600 ml-auto">+40%</h4>
- </span>
- </div>
- </span>
- </section>
- <section v-if="dashboardPage == 'content'">
- <span class="flex items-center justify-between">
- <ButtonText title="Add New Category">
- <template #text>
- <div class="flex justify-between items-center gap-2">
- <p class="text-nowrap">Add New Category</p>
- <ProiconsAddCircle height="24" width="24" />
- </div>
- </template>
- </ButtonText>
- <p class="text-slate-400 uppercase">Categories: {{ categories.length }}</p>
- </span>
- <div class="flex flex-wrap w-full pt-4">
- <div
- v-for="(category, index) in categories"
- :key="index"
- class="flex flex-col gap-2 p-4 overflow-clip rounded-xl shadow-lg dark:bg-primary-dark-800/70 bg-white ring-1 ring-gray-900/5 w-1/3"
- >
- <h3 class="capitalize text-lg flex items-end justify-between">
- {{ category.name }}
- <ButtonIcon class="w-6 h-6 !p-1">
- <template #icon>
- <CircumEdit class="w-full h-full" />
- </template>
- </ButtonIcon>
- </h3>
- <p class="text-slate-400">Folders: {{ category.folders_count }}</p>
- </div>
- </div>
- </section>
+ <DashboardAnalytics v-if="dashboardPage == 'overview'" />
+ <DashboardContent v-if="dashboardPage == 'content'" />
</section>
</template>
<template v-slot:leftSidebar>
@@ -156,29 +65,6 @@ watch(() => selectedSideBar.value, cycleSideBar, { immediate: false });
@click="dashboardPage = page.title"
>
{{ page.title }}
- <div class="flex items-center flex-wrap gap-2" v-if="page.timeControls">
- <button
- @click="setPeriod('1_hour')"
- class="font-semibold sm:text-lg text-gray-300 dark:text-gray-600 hover:text-gray-400 dark:hover:text-gray-500"
- >
- 1h
- </button>
- <button
- @click="setPeriod('6_hours')"
- class="font-semibold sm:text-lg text-gray-300 dark:text-gray-600 hover:text-gray-400 dark:hover:text-gray-500"
- >
- 6h
- </button>
- <button @click="setPeriod('24_hours')" class="font-semibold sm:text-lg text-gray-700 dark:text-gray-300">
- 24h
- </button>
- <button
- @click="setPeriod('7_days')"
- class="font-semibold sm:text-lg text-gray-300 dark:text-gray-600 hover:text-gray-400 dark:hover:text-gray-500"
- >
- 7d
- </button>
- </div>
</div>
</section>
</div>
diff --git a/resources/js/views/VideoView.vue b/resources/js/views/VideoView.vue
index 00862bd9..c3fb64b3 100755
--- a/resources/js/views/VideoView.vue
+++ b/resources/js/views/VideoView.vue
@@ -34,9 +34,6 @@ async function cycleSideBar(state: string) {
await getRecords(10);
}
if (!state) return;
-
- await nextTick();
- document.querySelector('#list-card')?.scrollIntoView({ behavior: 'smooth' });
}
async function reload(nextFolderName: string | string[]) {
diff --git a/routes/api.php b/routes/api.php
index a3b937f4..1cb2b71e 100755
--- a/routes/api.php
+++ b/routes/api.php
@@ -1,5 +1,6 @@
<?php
+use App\Http\Controllers\Api\V1\AnalyticsController;
use App\Http\Controllers\Api\V1\AuthController;
use App\Http\Controllers\Api\V1\CategoryController;
use App\Http\Controllers\Api\V1\FolderController;
@@ -8,7 +9,6 @@ use App\Http\Controllers\Api\V1\PlaybackController;
use App\Http\Controllers\Api\V1\ProfileController;
use App\Http\Controllers\Api\V1\RecordController;
use App\Http\Controllers\Api\V1\SeriesController;
-use App\Http\Controllers\Api\V1\SiteController;
use App\Http\Controllers\Api\V1\TagController;
use App\Http\Controllers\Api\V1\VideoController;
use App\Http\Controllers\DirectoryController;
@@ -30,7 +30,7 @@ Route::group(['middleware' => ['auth:sanctum']], function () {
Route::resource('/series', SeriesController::class)->only(['index', 'store', 'update']);
Route::resource('/metadata', MetadataController::class)->only(['show', 'store', 'update']);
Route::resource('/tags', TagController::class)->only(['index', 'store']);
- Route::resource('/site', SiteController::class)->only(['index']);
+ Route::resource('/analytics', AnalyticsController::class)->only(['index']);
Route::resource('/categories', CategoryController::class)->only(['index']);
});