A self-hosted media server and file management system
Vue ffmpegfile-serverjellyfinlaravelmediamedia-playermedia-servermediabrowsermediaservermusicmusic-librarymusic-playermusicplayerself-hostedvuejs
task state and ui
aminnausin07b0954532f9
diff --git a/app/Enums/TaskStatus.php b/app/Enums/TaskStatus.phpindex b89f715a..b7bb09bd 100644--- a/app/Enums/TaskStatus.php+++ b/app/Enums/TaskStatus.php@@ -2,13 +2,13 @@namespace App\Enums;-enum TaskStatus: string {- case PENDING = 'pending';- case PROCESSING = 'processing';- case COMPLETE = 'complete';- case CANCELLED = 'cancelled';- case FAILED = 'failed';- case INCOMPLETE = 'incomplete';+enum TaskStatus: int {+ case PENDING = 0;+ case PROCESSING = 1;+ case INCOMPLETE = 2;+ case COMPLETED = 3;+ case CANCELLED = -1;+ case FAILED = -2;public function isPending(): bool {@@ -20,15 +20,15 @@ enum TaskStatus: string {}public function isComplete(): bool {- return $this === self::PROCESSING;+ return $this === self::COMPLETED;}public function isCancelled(): bool {- return $this === self::PROCESSING;+ return $this === self::CANCELLED;}public function isFailed(): bool {- return $this === self::PROCESSING;+ return $this === self::FAILED;}public function isIncomplete(): bool {@@ -38,9 +38,9 @@ enum TaskStatus: string {/*** Check if a given value is a valid enum case.*/- public static function isValid(string $type): bool {+ public static function isValid(int $type): bool {foreach (self::cases() as $case) {- if ($case->value === $type) {+ if ($case->value == $type) {return true;}}@@ -51,4 +51,15 @@ enum TaskStatus: string {public static function getValues(): array {return array_column(self::cases(), 'value');}++ public static function getLabel(TaskStatus $type): string {+ return match ($type) {+ self::PENDING => 'pending',+ self::PROCESSING => 'processing',+ self::COMPLETED => 'completed',+ self::INCOMPLETE => 'incomplete',+ self::CANCELLED => 'cancelled',+ self::FAILED => 'failed',+ };+ }}diff --git a/app/Http/Controllers/Api/V1/TasksController.php b/app/Http/Controllers/Api/V1/TasksController.phpnew file mode 100644index 00000000..13349757--- /dev/null+++ b/app/Http/Controllers/Api/V1/TasksController.php@@ -0,0 +1,75 @@+<?php++namespace App\Http\Controllers\Api\V1;++use App\Http\Controllers\Controller;+use App\Http\Resources\TasksResource;+use App\Models\SubTask;+use App\Models\Task;+use App\Traits\HttpResponses;+use Illuminate\Http\Request;+use Illuminate\Support\Facades\Auth;+use Illuminate\Support\Facades\DB;++class TasksController extends Controller {+ use HttpResponses;++ /**+ * Display a listing of the resource.+ */+ public function index() {+ try {+ if (! Auth::user() || Auth::user()->id !== 1) {+ abort(403, 'Unauthorized action.');+ }++ return+ TasksResource::collection(+ Task::all()->sortBy('id')+ );+ } catch (\Throwable $th) {+ return $this->error(null, 'Unable to get list of tasks. Error: ' . $th->getMessage(), 500);+ }+ }++ public function stats(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);+ }+++ $results = DB::table('sub_tasks')+ ->select(+ DB::raw('AVG(duration) as avg_duration'),+ // DB::raw('SUM(CASE WHEN status = "failed" THEN 1 ELSE 0 END) / COUNT(*) * 100 as avg_fail_rate'),+ // DB::raw('SUM(CASE WHEN status = "cancelled" THEN 1 ELSE 0 END) as count_cancelled'),+ DB::raw('COUNT(*) as count_subtasks')+ )+ ->first();+++ $taskCounts = Task::select(+ DB::raw('COUNT(*) as count_tasks'),+ DB::raw('AVG(sub_tasks_total) as avg_count_sub_tasks')+ )->first();++ $currentCounts = [+ 'avg_duration' => $results->avg_duration,+ 'avg_fail_rate' => 0,+ 'count_cancelled' => 0,+ 'avg_count_sub_tasks' => $taskCounts->avg_count_sub_tasks,+ 'count_tasks' => $taskCounts->count_tasks,+ 'count_subtasks' => $results->count_subtasks,+ ];++ return response()->json($currentCounts);+ } catch (\Throwable $th) {+ return $this->error(null, 'Unable to get stats. Error: ' . $th->getMessage(), 500);+ }+ }+}diff --git a/app/Http/Controllers/Api/V1/UserController.php b/app/Http/Controllers/Api/V1/UserController.phpindex 0a8f1f58..18e3ea77 100644--- a/app/Http/Controllers/Api/V1/UserController.php+++ b/app/Http/Controllers/Api/V1/UserController.php@@ -30,6 +30,19 @@ class UserController extends Controller {}}+ /**+ * Remove the specified resource from storage.+ *+ * @param int $id+ * @return \Illuminate\Http\Response+ */+ public function destroy(User $user) {+ if (! Auth::user() || Auth::user()->id !== 1 || Auth::user()->id === $user->id) {+ abort(403, 'Unauthorized action.');+ }++ return $user->delete() ? $this->success('', 'Success', 200) : $this->error('', 'Not found', 404);+ }public function SessionCount() {try {diff --git a/app/Http/Controllers/DirectoryController.php b/app/Http/Controllers/DirectoryController.phpindex 2b5861d9..3fd81f15 100755--- a/app/Http/Controllers/DirectoryController.php+++ b/app/Http/Controllers/DirectoryController.php@@ -2,6 +2,7 @@namespace App\Http\Controllers;+use App\Enums\TaskStatus;use App\Http\Requests\IndexFilesRequest;use App\Http\Resources\FolderResource;use App\Http\Resources\SeriesResource;@@ -14,11 +15,14 @@ use App\Jobs\VerifyFiles;use App\Jobs\VerifyFolders;use App\Models\Category;use App\Models\Folder;+use App\Models\Task;use App\Models\Video;use App\Traits\HttpResponses;+use Illuminate\Bus\Batch;use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Bus;+use Illuminate\Support\Facades\Log;class DirectoryController extends Controller {use HttpResponses;@@ -63,35 +67,147 @@ class DirectoryController extends Controller {}public function scanFiles(Request $request, Category $category = null) {+ $name = "Scan Files";+ $description = "Scans for file changes and loads metadata from all Libraries.";++ if (isset($category)) {+ $name .= " from the Library $category->name";+ $description = "Scans for file changes and loads metadata from the specified Library $category->name";+ }+try {+ $userId = $request->user() ? $request->user()->id : null;+ $task = $this->setupTask($userId, $name, $description);+$chain = [- new SyncFiles,- new IndexFiles,+ new SyncFiles($task->id),+ new IndexFiles($task->id),];- $fileChunks = [];++ $videoQuery = Video::orderBy('id');+ $folderQuery = Folder::orderBy('id');if ($category) {- $videos = Video::whereHas('folder.category', function ($query) use ($category) {+ $videoQuery = $videoQuery->whereHas('folder.category', function ($query) use ($category) {$query->where('id', $category->id);- })- ->with('folder.category')- ->orderBy('id')- ->get();- } else {- $videos = Video::orderBy('id')->get();+ })->with('folder.category');++ $folderQuery = $folderQuery->whereHas('category', function ($query) use ($category) {+ $query->where('id', $category->id);+ })->with('category');}- $videos->chunk(20, function ($videos) use (&$fileChunks) {- $fileChunks[] = $videos;+ $videos = $videoQuery->get();+ $folders = $folderQuery->get();+++ // if ($category) {+ // $videos = Video::whereHas('folder.category', function ($query) use ($category) {+ // $query->where('id', $category->id);+ // })+ // ->with('folder.category')+ // ->orderBy('id')+ // ->get();+ // $folders = Folder::whereHas('category', function ($query) use ($category) {+ // $query->where('id', $category->id);+ // })+ // ->with('category')+ // ->orderBy('id')+ // ->get();+ // } else {+ // $videos = Video::orderBy('id')->get();+ // $folders = Folder::orderBy('id')->get();+ // }++ $videos->chunk(20, function ($chunk) use (&$fileChunks, $task) {+ $chain[] = new VerifyFiles($chunk, $task->id);});- foreach ($fileChunks as $chunk) {- $chain[] = new VerifyFiles($chunk);- }+ $folders->chunk(20)->each(function ($chunk) use (&$folderChunks, $task) {+ $chain[] = new VerifyFolders($chunk, $task->id);+ });++ $batch = $this->setupBatch($chain, $task);+ $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain)]);+ return response()->json(['task_id' => $task->id, 'message' => 'Async Task "SCAN FILES" was started.']);+ } catch (\Throwable $th) {+ if ($task) $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now(),]);+ return response()->json(['error' => 'Error cannot scan files', 'details' => $th->getMessage()], 500);+ }+ }++ public function indexFiles(Request $request, Category $category = null) {+ $name = "Index Files";+ $description = "Looks for folder and video changes in in all Libraries.";++ if (isset($category)) {+ $name .= " for Library $category->name";+ $description = "Looks for folder and video changes in the specified Library $category->name";+ }++ $userId = $request->user() ? $request->user()->id : null;+ $task = $this->setupTask($userId, $name, $description, 2);++ try {+ $chain = [+ new SyncFiles($task->id),+ new IndexFiles($task->id),+ ];++ $batch = $this->setupBatch($chain, $task);+ $task->update(['batch_id' => $batch->id]);+ return response()->json(['task_id' => $task->id, 'message' => 'Async Task "INDEX FILES" was started.']);+ } catch (\Throwable $th) {+ if ($task) $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now(),]);+ return response()->json(['error' => 'Error cannot index files', 'details' => $th->getMessage()], 500);+ // dump($th);+ }+ }++ public function syncFiles(Request $request) {+ $userId = $request->user() ? $request->user()->id : null;+ $task = $this->setupTask($userId, 'Sync Files', 'Syncs local file structure with database.', 1);++ try {+ if (!isset($task->id)) throw ('waaa');+ $chain = [+ new SyncFiles($task->id),+ ];++ $batch = $this->setupBatch($chain, $task);+ $task->update(['batch_id' => $batch->id]);+ return response()->json(['task_id' => $task->id, 'message' => 'Async Task "SYNC FILES" was started.']);+ } catch (\Throwable $th) {+ if ($task) $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now(),]);+ return response()->json(['error' => 'Error cannot sync files', 'details' => $th->getMessage()], 500);+ }+ }++ public function verifyFiles(Request $request, Category $category = null) {+ $name = "Verify Files";+ $description = "Verifies folder and video metadata for all Libraries.";++ if (isset($category)) {+ $name .= " for Library $category->name";+ $description = "Verifies folder and video metadata for the specified Library $category->name";+ }++ try {+ $userId = $request->user() ? $request->user()->id : null;+ $task = $this->setupTask($userId, $name, $description);+ $chain = [];+ $videoChunks = [];$folderChunks = [];+if ($category) {+ $videos = Video::whereHas('folder.category', function ($query) use ($category) {+ $query->where('id', $category->id);+ })+ ->with('folder.category')+ ->orderBy('id')+ ->get();$folders = Folder::whereHas('category', function ($query) use ($category) {$query->where('id', $category->id);})@@ -100,51 +216,184 @@ class DirectoryController extends Controller {->get();} else {$folders = Folder::orderBy('id')->get();+ $videos = Video::orderBy('id')->get();}- $folders->chunk(20)->each(function ($chunk) use (&$folderChunks) {- $folderChunks[] = $chunk;+ $videos->chunk(20, function ($videos) use (&$videoChunks) {+ $videoChunks[] = $videos;});+ $folders->chunk(20)->each(function ($folders) use (&$folderChunks) {+ $folderChunks[] = $folders;+ });++ foreach ($videoChunks as $chunk) {+ $chain[] = new VerifyFiles($chunk, $task->id);+ }+foreach ($folderChunks as $chunk) {$chain[] = new VerifyFolders($chunk);}- Bus::batch($chain)->dispatch();-- // dump('All jobs have been dispatched: Sync, Index, Verify Files, and Verify Folders.');+ $batch = $this->setupBatch($chain, $task);+ $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain)]);+ return response()->json(['task_id' => $task->id, 'message' => 'Async Task "VERIFY FILES" was started.']);} catch (\Throwable $th) {- // dump('Error: cannot process the jobs');+ if ($task) $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now(),]);+ return response()->json(['error' => 'Error cannot verify files', 'details' => $th->getMessage()], 500);+ // dump('Error cannot verify file metadata');// dump($th);- abort(500, $th->getMessage());}}- public function indexFiles(Request $request, Category $category = null) {+ public function verifyFolders(Request $request, Category $category = null) {try {- $chain = [- new SyncFiles,- new IndexFiles,- ];- Bus::batch($chain)->dispatch();- dump('This job now uses ffprobe so it must be async');+ $jobs = [];+ $chunks = [];++ Folder::orderBy('id')->chunk(20, function ($folders) use (&$chunks) {+ $chunks[] = $folders;+ });++ foreach ($chunks as $chunk) {+ $jobs[] = new VerifyFolders($chunk);+ // break;+ }++ Bus::batch($jobs)->dispatch();+ dump('verifyFolders : This job has no web output. Check queue listener console for updates.');} catch (\Throwable $th) {- dump('Error cannot index files');+ dump('Error cannot verify folder series data');dump($th);}}- public function syncFiles(Request $request) {+ public function cleanPaths(Request $request) {+ $name = "Clean Paths";+ $description = "Cleans file and folder paths for all Libraries.";+ $chain = [];+try {- SyncFiles::dispatchSync();- dump('success');+ $userId = $request->user() ? $request->user()->id : null;+ $task = $this->setupTask($userId, $name, $description);++ Video::orderBy('id')->chunk(20, function ($videos) use (&$chain) {+ $chain[] = new CleanFolderPaths($videos);+ });++ Folder::orderBy('id')->chunk(20, function ($folders) use (&$chain) {+ $chain[] = new CleanFolderPaths($folders);+ });++ $chain[] = new SyncFiles($task->id);++ $batch = $this->setupBatch($chain, $task);+ $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain)]);++ return response()->json(['task_id' => $task->id, 'message' => 'Async Task "CLEAN PATHS" was started.']);} catch (\Throwable $th) {- dump('Error cannot sync files');- dump($th);+ if (isset($task)) {+ $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now()]);+ }+ return response()->json(['error' => 'Error cannot clean folder or video paths', 'details' => $th->getMessage()], 500);}}- public function verifyFiles(Request $request, Category $category = null) {+ function setupTask($userId, $name, $description = '', $taskCount = 0) {+ return Task::create([+ 'user_id' => $userId,+ 'name' => $name,+ 'description' => $description,+ 'sub_tasks_total' => $taskCount,+ 'sub_tasks_pending' => $taskCount,+ ]);+ }++ function setupBatch($chain, $task) {+ return Bus::batch($chain)->progress(function (Batch $batch) use ($task) {+ $task->refresh();+ $task->update([+ 'sub_tasks_pending' => $batch->pendingJobs,+ 'sub_tasks_failed' => $batch->failedJobs,+ 'sub_tasks_complete' => $task->sub_tasks_total - $batch->pendingJobs - $batch->failedJobs,+ ]);+ })->catch(function (Batch $batch, \Throwable $e) use ($task) {+ $task->update([+ 'status' => TaskStatus::FAILED,+ ]);++ Log::error('Batch failed', ['task_id' => $task->id, 'error' => $e->getMessage()]);+ })->finally(function (Batch $batch) use ($task) {+ $task->refresh();+ $status = $task->status !== TaskStatus::PROCESSING ? $task->status : ($batch->cancelled() ? TaskStatus::CANCELLED : ($batch->processedJobs() !== $task->sub_tasks_total ? TaskStatus::INCOMPLETE : TaskStatus::COMPLETED));+ $ended_at = now();++ try {+ $started_at = $task->started_at ? \Carbon\Carbon::parse($task->started_at) : null;+ $duration = $started_at ? (int) $ended_at->diffInSeconds($started_at) : 0;+ } catch (\Throwable $th) {+ Log::error('Batch Error on Completion', ['task_id' => $task->id, 'error' => $th->getMessage()]);+ $duration = 0;+ }++ $task->update([+ 'status' => $status,+ 'sub_tasks_pending' => $batch->pendingJobs,+ 'sub_tasks_failed' => $batch->failedJobs,+ 'sub_tasks_complete' => $task->sub_tasks_total - $batch->pendingJobs - $batch->failedJobs,+ 'ended_at' => $ended_at,+ 'duration' => $duration < 0 ? $duration * -1 : $duration+ ]);+ })->before(function (Batch $batch) use ($task) {+ $task->update([+ 'status' => TaskStatus::PROCESSING,+ 'started_at' => now(),+ ]);+ })->dispatch();+ }++ function setupBatch2($chain, $task) {+ return Bus::batch($chain)->then(function (Batch $batch) use ($task) {+ // $status = $batch->cancelled() ? TaskStatus::CANCELLED : ($batch->processedJobs() !== $task->sub_tasks_total ? TaskStatus::INCOMPLETE : TaskStatus::COMPLETED);++ // $task->update([+ // 'status' => $status,+ // 'sub_tasks_pending' => $batch->pendingJobs,+ // 'sub_tasks_complete' => $batch->processedJobs(),+ // 'sub_tasks_failed' => $batch->failedJobs,+ // 'ended_at' => now(),+ // ]);+ })->progress(function (Batch $batch) use ($task) {+ $task->update([+ 'sub_tasks_pending' => $batch->pendingJobs,+ 'sub_tasks_complete' => $batch->processedJobs(),+ 'sub_tasks_failed' => $batch->failedJobs,+ ]);+ })->catch(function (Batch $batch, \Throwable $e) use ($task) {+ $task->update([+ 'status' => TaskStatus::FAILED,+ ]);+ // Log the error for debugging+ Log::error('Batch failed', ['task_id' => $task->id, 'error' => $e->getMessage()]);+ })->finally(function (Batch $batch) use ($task) {+ $status = $task->status !== TaskStatus::PROCESSING ? $task->status : ($batch->cancelled() ? TaskStatus::CANCELLED : ($batch->processedJobs() !== $task->sub_tasks_total ? TaskStatus::INCOMPLETE : TaskStatus::COMPLETED));++ $task->update([+ 'status' => $status,+ 'sub_tasks_pending' => $batch->pendingJobs,+ 'sub_tasks_failed' => $batch->failedJobs,+ 'ended_at' => now(),+ ]);+ })->before(function (Batch $batch) use ($task) {+ $task->update([+ 'status' => TaskStatus::PROCESSING,+ 'started_at' => now(),+ ]);+ })->dispatch();+ }+++ public function verifyFiles2(Request $request, Category $category = null) {try {$jobs = [];$chunks = [];@@ -165,7 +414,7 @@ class DirectoryController extends Controller {});foreach ($chunks as $chunk) {- $jobs[] = new VerifyFiles($chunk);+ // $jobs[] = new VerifyFiles($chunk);// break;}@@ -212,67 +461,4 @@ class DirectoryController extends Controller {dump($th);}}-- public function verifyFolders(Request $request, Category $category = null) {- try {- $jobs = [];- $chunks = [];-- Folder::orderBy('id')->chunk(20, function ($folders) use (&$chunks) {- $chunks[] = $folders;- });-- foreach ($chunks as $chunk) {- $jobs[] = new VerifyFolders($chunk);- // break;- }-- Bus::batch($jobs)->dispatch();- dump('verifyFolders : This job has no web output. Check queue listener console for updates.');- } catch (\Throwable $th) {- dump('Error cannot verify folder series data');- dump($th);- }- }-- public function cleanPaths() {- $jobs = [];-- try {- $chunks = [];-- Video::orderBy('id')->chunk(20, function ($videos) use (&$chunks) {- $chunks[] = $videos;- });-- foreach ($chunks as $chunk) {- $jobs[] = new CleanVideoPaths($chunk);- // break;- }- } catch (\Throwable $th) {- dump('Error cannot clean video paths');- dump($th);- }-- try {- $chunks = [];-- Folder::orderBy('id')->chunk(20, function ($folders) use (&$chunks) {- $chunks[] = $folders;- });-- foreach ($chunks as $chunk) {- $jobs[] = new CleanFolderPaths($chunk);- // break;- }- } catch (\Throwable $th) {- dump('Error cannot clean folder paths');- dump($th);- }-- $jobs[] = new SyncFiles;- Bus::batch($jobs)->dispatch();-- dump('This job has no web output. Check queue listener console for updates.');- }}diff --git a/app/Http/Resources/SubTasksResource.php b/app/Http/Resources/SubTasksResource.phpnew file mode 100644index 00000000..e540d2e4--- /dev/null+++ b/app/Http/Resources/SubTasksResource.php@@ -0,0 +1,29 @@+<?php++namespace App\Http\Resources;++use App\Enums\TaskStatus;+use Illuminate\Http\Request;+use Illuminate\Http\Resources\Json\JsonResource;++class SubTasksResource extends JsonResource {+ /**+ * Transform the resource into an array.+ *+ * @return array<string, mixed>+ */+ public function toArray(Request $request): array {+ return [+ 'id' => $this->id,+ 'status_key' => $this->status,+ 'status' => TaskStatus::getLabel($this->status),+ 'name' => $this->name,+ 'summary' => $this->summary,+ 'progress' => $this->progress,+ 'duration' => $this->duration,+ 'started_at' => $this->started_at,+ 'ended_at' => $this->ended_at,+ 'created_at' => $this->created_at,+ ];+ }+}diff --git a/app/Http/Resources/TasksResource.php b/app/Http/Resources/TasksResource.phpnew file mode 100644index 00000000..dbc09223--- /dev/null+++ b/app/Http/Resources/TasksResource.php@@ -0,0 +1,48 @@+<?php++namespace App\Http\Resources;++use App\Enums\TaskStatus;+use Illuminate\Http\Request;+use Illuminate\Http\Resources\Json\JsonResource;++class TasksResource extends JsonResource {+ protected static $userCache = [];++ /**+ * Transform the resource into an array.+ *+ * @return array<string, mixed>+ */++ public function toArray(Request $request): array {+ $userId = $this->user_id; // Assuming editor_id is the foreign key+ $user = null;++ if (isset(self::$userCache[$userId])) {+ $user = self::$userCache[$userId];+ } else {+ $user = $this->user;+ self::$userCache[$userId] = $user;+ }++ return [+ 'id' => $this->id,+ 'user' => $user->name,+ 'status_key' => $this->status,+ 'status' => TaskStatus::getLabel($this->status),+ 'name' => $this->name,+ 'description' => $this->description,+ 'summary' => $this->summary,+ 'sub_tasks' => SubTasksResource::collection($this->sub_tasks),+ 'sub_tasks_total' => $this->sub_tasks_total,+ 'sub_tasks_pending' => $this->sub_tasks_pending,+ 'sub_tasks_complete' => $this->sub_tasks_complete,+ 'sub_tasks_failed' => $this->sub_tasks_failed,+ 'duration' => $this->duration,+ 'started_at' => $this->started_at,+ 'ended_at' => $this->ended_at,+ 'created_at' => $this->created_at,+ ];+ }+}diff --git a/app/Jobs/SyncFiles.php b/app/Jobs/SyncFiles.phpindex 817aeba8..26905b28 100755--- a/app/Jobs/SyncFiles.php+++ b/app/Jobs/SyncFiles.php@@ -2,9 +2,12 @@namespace App\Jobs;+use App\Enums\TaskStatus;use App\Models\Category;use App\Models\Folder;+use App\Models\SubTask;use App\Models\Video;+use Error;use Illuminate\Bus\Batchable;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldBeUnique;@@ -12,16 +15,23 @@ use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Storage;class SyncFiles implements ShouldBeUnique, ShouldQueue {use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;+ protected $taskId;+ protected $subTaskId;+/*** Create a new job instance.*/- public function __construct() {+ public function __construct($taskId) {//+ $subTask = SubTask::create(['task_id' => $taskId, 'status' => TaskStatus::PENDING, 'name' => 'Sync Files']); //+ $this->taskId = $taskId;+ $this->subTaskId = $subTask->id;}/**@@ -30,10 +40,22 @@ class SyncFiles implements ShouldBeUnique, ShouldQueue {public function handle(): void {if ($this->batch() && $this->batch()->cancelled()) {// Determine if the batch has been cancelled...+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::CANCELLED]);return;}- $this->syncCache();+ DB::table('tasks')->where('id', $this->taskId)->decrement('sub_tasks_pending');+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::PROCESSING, 'started_at' => now()]);++ try {+ $this->syncCache();+ DB::table('tasks')->where('id', $this->taskId)->increment('sub_tasks_complete');+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::COMPLETED, 'summary' => '', 'ended_at' => now(), 'progress' => 100]);+ } catch (\Throwable $th) {+ DB::table('tasks')->where('id', $this->taskId)->increment('sub_tasks_failed');+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::FAILED, 'summary' => "Error: " . $th->getMessage(), 'ended_at' => now(), 'progress' => 100]);+ //throw $th;+ }}public function syncCache() {@@ -47,6 +69,7 @@ class SyncFiles implements ShouldBeUnique, ShouldQueue {$error = 'Missing "media" directory in storage';dd(json_encode(['success' => false, 'result' => '', 'error' => $error], JSON_UNESCAPED_SLASHES));+ throw new Error($error, 404);}$directories = $this->generateCategories();@@ -71,12 +94,15 @@ class SyncFiles implements ShouldBeUnique, ShouldQueue {$dataCache[date('Y-m-d-h:i:sa')] = ['job' => 'sync', 'data' => $data];Storage::put('dataCache.json', json_encode($dataCache, JSON_UNESCAPED_SLASHES));+if (! $this->batch()) {dump('Categories | Folders | Videos | Data | dataCache', $directories, $subDirectories, $files, $data, $dataCache);}}private function generateCategories() {+ SubTask::where('id', $this->subTaskId)->update(['summary' => 'Generating Categories']);+$data = Storage::json('categories.json') ?? ['next_ID' => 1, 'categoryStructure' => []]; //array("anime"=>1,"tv"=>2,"yogscast"=>3); // read from json$scanned = Category::all(); // read folder structure@@ -120,6 +146,8 @@ class SyncFiles implements ShouldBeUnique, ShouldQueue {}private function generateFolders($path) {+ SubTask::where('id', $this->subTaskId)->update(['summary' => 'Generating Folders', 'progress' => 25]);+$data = Storage::json('folders.json') ?? ['next_ID' => 1, 'folderStructure' => []]; //array("anime/frieren"=>array("id"=>0,"name"=>"frieren"),"starwars/andor"=>array("id"=1,"name"="andor")); // read from json$cost = 0;$scanned = Folder::all();@@ -167,6 +195,8 @@ class SyncFiles implements ShouldBeUnique, ShouldQueue {}private function generateVideos($path, $folderStructure) {+ SubTask::where('id', $this->subTaskId)->update(['summary' => 'Generating Videos', 'progress' => 50]);+$data = Storage::json('videos.json') ?? ['next_ID' => 1, 'videoStructure' => []]; //array("anime/frieren/S1E01.mp4"=>array("id"=>0,"name"=>"S1E01"),"starwars/andor/S1E01.mkv"=>array("id"=1,"name"="S1E01.mkv")); // read from json$scanned = Video::all();$cost = 0;diff --git a/app/Jobs/VerifyFiles.php b/app/Jobs/VerifyFiles.phpindex e3f2ab98..a63fa59f 100755--- a/app/Jobs/VerifyFiles.php+++ b/app/Jobs/VerifyFiles.php@@ -2,8 +2,10 @@namespace App\Jobs;+use App\Enums\TaskStatus;use App\Models\Metadata;use App\Models\Record;+use App\Models\SubTask;use FFMpeg\FFProbe as FFMpegFFProbe;use Illuminate\Bus\Batchable;use Illuminate\Bus\Queueable;@@ -20,11 +22,18 @@ use Symfony\Component\Process\Process;class VerifyFiles implements ShouldQueue {use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ protected $taskId;+ protected $subTaskId;+/*** Create a new job instance.*/- public function __construct(public $videos) {+ public function __construct(public $videos, $taskId) {//+ $subTask = SubTask::create(['task_id' => $taskId, 'status' => TaskStatus::PENDING, 'name' => 'Index ' . count($videos) . ' Files']); //+ $this->taskId = $taskId;+ $this->subTaskId = $subTask->id;}/**diff --git a/app/Models/SubTask.php b/app/Models/SubTask.phpindex 81b6bbd7..c95fb35e 100644--- a/app/Models/SubTask.php+++ b/app/Models/SubTask.php@@ -8,8 +8,11 @@ use App\Enums\TaskStatus;class SubTask extends Model {protected $fillable = ['task_id',- 'name','status',+ 'name',+ 'summary',+ 'progress',+ 'duration','started_at','ended_at',];@@ -18,6 +21,26 @@ class SubTask extends Model {'status' => TaskStatus::class,];+ protected static function boot() {+ parent::boot();++ static::updated(function ($subTask) {+ $subTask->updateDuration();+ });+ }++ public function updateDuration() {+ if (!isset($this->started_at)) {+ $this->duration = 0;+ $this->save;+ return;+ }++ $time = now();+ $this->duration = (int) $time->diffInSeconds($this->started_at);+ $this->save();+ }+public function task() {return $this->belongsTo(Task::class);}diff --git a/app/Models/Task.php b/app/Models/Task.phpindex cc44608e..619c7a71 100644--- a/app/Models/Task.php+++ b/app/Models/Task.php@@ -9,13 +9,16 @@ use Illuminate\Database\Eloquent\Relations\HasMany;class Task extends Model {protected $fillable = ['user_id',+ 'batch_id',+ 'status','name','summary',- 'status',- 'sub_tasks',+ 'description',+ 'sub_tasks_total','sub_tasks_pending',- 'sub_tasks_completed',+ 'sub_tasks_complete','sub_tasks_failed',+ 'duration','started_at','ended_at',];@@ -24,6 +27,25 @@ class Task extends Model {'status' => TaskStatus::class,];++ // Boot method to register model events+ protected static function boot() {+ parent::boot();++ // static::updated(function ($task) {+ // // This will run whenever the task is updated+ // // Add your custom logic here+ // $task->updateDuration();+ // });+ }++ // public function updateDuration() {+ // if ($this->started_at && $this->ended_at) {+ // $this->duration = $this->ended_at->diffInSeconds($this->started_at);+ // $this->save();+ // }+ // }+public function user() {return $this->belongsTo(User::class);}diff --git a/database/migrations/2024_12_24_064559_create_edits_table.php b/database/migrations/2024_12_24_064559_create_edits_table.php.baksimilarity index 100%rename from database/migrations/2024_12_24_064559_create_edits_table.phprename to database/migrations/2024_12_24_064559_create_edits_table.php.bakdiff --git a/database/migrations/2024_12_24_064717_create_tasks_and_sub_tasks_table.php b/database/migrations/2024_12_24_064717_create_tasks_and_sub_tasks_table.phpindex 8c183006..a480114a 100644--- a/database/migrations/2024_12_24_064717_create_tasks_and_sub_tasks_table.php+++ b/database/migrations/2024_12_24_064717_create_tasks_and_sub_tasks_table.php@@ -13,24 +13,32 @@ return new class extends Migration {Schema::create('tasks', function (Blueprint $table) {$table->id();$table->foreignId('user_id')->constrained()->nullOnDelete();- $table->string('status')->default(TaskStatus::PENDING);+ $table->string('batch_id')->nullable();+ $table->tinyInteger('status')->default(TaskStatus::PENDING);$table->string('name')->nullable();- $table->string('summary')->nullable();- $table->unsignedSmallInteger('sub_tasks')->default(0);+ $table->string('description')->nullable();+ $table->text('summary')->nullable();+ $table->text('url')->nullable();+ $table->unsignedSmallInteger('sub_tasks_total')->default(0);$table->unsignedSmallInteger('sub_tasks_pending')->default(0);$table->unsignedSmallInteger('sub_tasks_complete')->default(0);$table->unsignedSmallInteger('sub_tasks_failed')->default(0);+ $table->unsignedBigInteger('duration')->default(0);$table->timestamp('started_at')->nullable();$table->timestamp('ended_at')->nullable();$table->timestamps();++ $table->foreign('batch_id')->references('id')->on('job_batches')->nullOnDelete();});Schema::create('sub_tasks', function (Blueprint $table) {$table->id();- $table->foreignId('tasks_id')->constrained()->cascadeOnDelete();- $table->string('status')->default(TaskStatus::PENDING);+ $table->foreignId('task_id')->constrained()->cascadeOnDelete();+ $table->tinyInteger('status')->default(TaskStatus::PENDING);$table->string('name')->nullable();- $table->unsignedInteger('model_count');+ $table->text('summary')->nullable();+ $table->unsignedTinyInteger('progress')->default(0);+ $table->unsignedBigInteger('duration')->default(0);$table->timestamp('started_at')->nullable();$table->timestamp('ended_at')->nullable();$table->timestamps();@@ -41,7 +49,7 @@ return new class extends Migration {* Reverse the migrations.*/public function down(): void {- Schema::dropIfExists('tasks');Schema::dropIfExists('sub_tasks');+ Schema::dropIfExists('tasks');}};diff --git a/database/migrations/2024_12_28_180714_connect_tasks_to_jobs_and_batches.php b/database/migrations/2024_12_28_180714_connect_tasks_to_jobs_and_batches.phpnew file mode 100644index 00000000..9eb1c297--- /dev/null+++ b/database/migrations/2024_12_28_180714_connect_tasks_to_jobs_and_batches.php@@ -0,0 +1,42 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration {+ /**+ * Run the migrations.+ */+ public function up(): void {+ Schema::table('tasks', function (Blueprint $table) {+ $table->string('batch_id')->nullable()->after('user_id');+ $table->foreign('batch_id')->references('id')->on('job_batches')->nullOnDelete();+ $table->unsignedSmallInteger('total_sub_tasks')->default(0)->after('status');+ $table->dropColumn('sub_tasks');+ // $table->dropColumn('sub_tasks_pending');+ // $table->dropColumn('sub_tasks_complete');+ // $table->dropColumn('sub_tasks_failed');+ });++ Schema::table('sub_tasks', function (Blueprint $table) {+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void {+ Schema::table('tasks', function (Blueprint $table) {+ $table->dropForeign(['batch_id']);+ $table->dropColumn('batch_id');+ $table->unsignedSmallInteger('sub_tasks')->default(0);+ // $table->unsignedSmallInteger('sub_tasks_pending')->default(0);+ // $table->unsignedSmallInteger('sub_tasks_complete')->default(0);+ // $table->unsignedSmallInteger('sub_tasks_failed')->default(0);+ });++ Schema::table('sub_tasks', function (Blueprint $table) {+ });+ }+};diff --git a/resources/js/components/cards/CategoryCardList.vue b/resources/js/components/cards/CategoryCardList.vuedeleted file mode 100644index 2d9a157b..00000000--- a/resources/js/components/cards/CategoryCardList.vue+++ /dev/null@@ -1,44 +0,0 @@-<script setup lang="ts">-import type { CategoryResource } from '@/types/resources';--import CircumEdit from '~icons/circum/edit';-import { toFormattedDate } from '@/service/util';-import ButtonCorner from '../inputs/ButtonCorner.vue';-import ButtonIcon from '@/components/inputs/ButtonIcon.vue';--const props = defineProps<{ data?: CategoryResource }>();-</script>--<template>- <div class="flex 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">- <div class="h-28 object-cover rounded-md shadow-md aspect-2/3 mb-auto relative group">- <img- id="folder-thumbnail"- class="h-28 object-cover rounded-md aspect-2/3 ring-1 ring-gray-900/5"- :src="- data?.folders[0]?.series?.thumbnail_url ??- 'https://m.media-amazon.com/images/M/MV5BMjVjZGU5ZTktYTZiNC00N2Q1LThiZjMtMDVmZDljN2I3ZWIwXkEyXkFqcGdeQXVyMTUzMTg2ODkz._V1_.jpg'- "- alt="Folder Cover Art"- />- </div>- <section class="flex flex-1 h-full flex-col">- <h3 class="capitalize text-lg flex items-start justify-between">- {{ data?.name }}- <ButtonIcon class="!w-6 !h-6 !p-1 !static">- <template #icon>- <CircumEdit class="w-full h-full" />- </template>- </ButtonIcon>- </h3>- <span class="flex items-center justify-between gap-2 text-sm mt-auto" v-if="data?.folders[0]">- <p class="text-slate-400">First Folder: {{ data.folders[0].name }}</p>- <p class="text-slate-400">Videos: {{ data.folders[0].file_count }}</p>- </span>- <span class="flex items-center justify-between gap-2 text-sm">- <p class="text-slate-400">Folders: {{ data?.folders_count }}</p>- <p class="text-slate-400">Added: {{ data?.created_at ? toFormattedDate(new Date(data?.created_at + ' EST')) : 'N/A' }}</p>- </span>- </section>- </div>-</template>diff --git a/resources/js/components/cards/SubTaskCard.vue b/resources/js/components/cards/SubTaskCard.vuenew file mode 100644index 00000000..f3082b33--- /dev/null+++ b/resources/js/components/cards/SubTaskCard.vue@@ -0,0 +1,175 @@+<script setup lang="ts">+import type { SubTaskResource } from '@/types/resources';+import type { TaskStatus } from '@/types/types';++import { toFormattedDate, toFormattedDuration, toTimeSpan, within24Hrs } from '@/service/util';+import { ref } from 'vue';++import ButtonCorner from '@/components/inputs/ButtonCorner.vue';+import ButtonText from '@/components/inputs/ButtonText.vue';+import Popover from '@/components/pinesUI/Popover.vue';+import ChipTag from '@/components/labels/ChipTag.vue';++import ProiconsCommentExclamation from '~icons/proicons/comment-exclamation';+import ProiconsMoreVertical from '~icons/proicons/more-vertical';+import PulseDoughnutChart from '../charts/PulseDoughnutChart.vue';+import ProiconsChevronDown from '~icons/proicons/chevron-down';+import ProiconsArrowSync from '~icons/proicons/arrow-sync';+import ProiconsDelete from '~icons/proicons/delete';+import SubTaskCard from './SubTaskCard.vue';+import ButtonIcon from '../inputs/ButtonIcon.vue';+import ProiconsArrowReply from '~icons/proicons/arrow-reply';++const props = defineProps<{ data: SubTaskResource }>();+</script>++<template>+ <span+ class="flex text-left rounded-xl dark:bg-primary-dark-800/50 bg-primary-800 ring-1 ring-gray-900/5 dark:text-white shadow w-full divide-gray-300 dark:divide-neutral-400"+ >+ <div class="flex flex-col gap-2 ring-1 ring-inset ring-purple-700 rounded-xl shadow-sm w-full">+ <section+ class="bg-white dark:bg-primary-dark-800/70 dark:hover:bg-primary-dark-600 hover:bg-primary-800 p-3 rounded-xl ring-1 ring-gray-900/5 flex gap-4 w-full items-center flex-wrap"+ >+ <div class="flex flex-col gap-2 sm:gap-1 flex-1">+ <div class="flex gap-x-4 gap-y-2 items-center">+ <h2 class="truncate capitalize group" :title="data.name">+ {{ data.name }}+ </h2>+ <p+ v-if="data.summary"+ class="flex justify-end gap-1 flex-1 line-clamp-3 sm:line-clamp-1 text-wrap text-ellipsis sm:text-nowrap text-neutral-500 dark:text-neutral-400"+ >+ {{ data.summary }}+ </p>+ </div>+ <div class="flex gap-x-8 gap-y-2 flex-wrap">+ <h4 class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize" title="">+ {{+ data.ended_at !== null+ ? `Finished: ${toFormattedDate(new Date(data.ended_at + ' UTC'), true, within24Hrs(data.ended_at + ' UTC') ? { hour: '2-digit', minute: '2-digit' } : undefined)}`+ : data.started_at !== null+ ? `Started: ${toFormattedDate(new Date(data.started_at + ' UTC'), true, within24Hrs(data.started_at + ' UTC') ? { hour: '2-digit', minute: '2-digit' } : undefined)}`+ : `Created: ${toFormattedDate(new Date(data.created_at + ' UTC'), true, within24Hrs(data.created_at + ' UTC') ? { hour: '2-digit', minute: '2-digit' } : undefined)}`+ }}+ </h4>+ <span class="flex gap-x-4 flex-1 flex-wrap">+ <h4+ class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize w-20"+ title="Duration"+ >+ Duration: {{ toFormattedDuration(data.duration) }}+ </h4>+ </span>+ </div>+ </div>++ <div class="px-2 text-xs flex flex-col gap-1 h-fit min-w-32">+ <p class="w-full text-left pe-8">{{ data.progress }}% Processed</p>+ <div class="rounded-full h-1 w-full bg-primary-dark-900 flex overflow-clip">+ <span+ :class="`h-1 ${data.status === 'completed' ? 'bg-purple-600' : data.status === 'failed' ? 'bg-rose-600' : 'bg-amber-500'} rounded-full`"+ :style="`width: ${data.progress}%;`"+ ></span>+ </div>+ </div>++ <!-- <td>+ <PulseDoughnutChart+ class="!h-8 !w-8"+ :chart-options="{+ borderWidth: 0,+ plugins: {+ legend: {+ display: false,+ },+ tooltip: {+ enabled: false,+ displayColors: false,+ },+ },+ }"+ :chart-data="{+ labels: ['Pending', 'Completed', 'Failed'],+ datasets: [+ {+ data: [data.sub_tasks_pending, data.sub_tasks_complete, data.sub_tasks_failed],+ backgroundColor: ['#c084fc30', '#9333ea', '#be123c'],+ hoverBackgroundColor: ['#c084fc30', '#9333ea', '#e11d48'],+ },+ ],+ }"+ />+ </td> -->++ <div class="flex gap-1 items-center">+ <ChipTag+ :class="`h-6 shadow-sm`"+ :colour="` ${+ data.status === 'pending'+ ? 'bg-[#e4e4e4] dark:bg-white !text-neutral-900'+ : data.status === 'processing'+ ? 'bg-purple-600 dark:bg-purple-700 !text-white'+ : data.status === 'completed'+ ? 'bg-[#660099] !text-white'+ : data.status === 'incomplete' || data.status === 'cancelled'+ ? 'bg-amber-500 !text-neutral-900 '+ : 'bg-rose-600 dark:bg-rose-700 !text-white'+ }`"+ :label="data.status"+ />+ <ButtonCorner+ disabled+ positionClasses="w-7 h-7 !p-1 ml-auto"+ textClasses="hover:text-rose-600 dark:hover:text-rose-500"+ colourClasses="dark:hover:bg-neutral-900 hover:bg-gray-100 hover:shadow-md"+ label="Remove Sub Task Record From Server"+ >+ <template #text> Remove </template>+ <template #icon> <ProiconsDelete class="h-4 w-4" /></template>+ </ButtonCorner>+ <!-- <Popover+ popoverClass="w-40 rounded-lg "+ :buttonComponent="ButtonCorner"+ :button-attributes="{+ positionClasses: 'w-7 h-7 !p-1 ml-auto',+ textClasses: 'hover:text-violet-600 dark:hover:text-violet-500',+ colourClasses: 'dark:hover:bg-neutral-900 hover:bg-gray-100 hover:shadow-md',+ label: 'Manage Permissions',+ }"+ @click.stop="() => {}"+ >+ <template #buttonIcon>+ <ProiconsMoreVertical class="h-4 w-4" />+ </template>+ <template #content>+ <div class="grid gap-4">+ <div class="space-y-2">+ <h4 class="font-medium leading-none">Manage Task</h4>+ </div>++ <div class="grid gap-2">+ <ButtonText class="h-8 dark:!bg-neutral-950" :title="'Scan for Folder Changes'" :to="'/profile'">+ <template #text> Run Again </template>+ <template #icon> <ProiconsArrowSync class="h-4 w-4" /></template>+ </ButtonText>+ <ButtonText+ v-if="data.status_key >= 0 && data.status_key <= 1"+ class="h-8 text-rose-600 dark:!bg-rose-700 disabled:opacity-60"+ :title="'Remove User From Server'"+ @click.stop.prevent="$emit('clickAction')"+ disabled+ >+ <template #text> Cancel </template>+ <template #icon> <ProiconsDelete class="h-4 w-4" /></template>+ </ButtonText>+ </div>+ </div>+ </template>+ </Popover> -->+ </div>+ </section>+ </div>+ <ProiconsArrowReply class="-scale-y-100 h-6 w-6 mx-2 my-auto" />+ </span>+</template>diff --git a/resources/js/components/cards/TaskCard.vue b/resources/js/components/cards/TaskCard.vueindex 230bb7b8..273706f0 100644--- a/resources/js/components/cards/TaskCard.vue+++ b/resources/js/components/cards/TaskCard.vue@@ -1,44 +1,180 @@<script setup lang="ts">-import type { UserResource } from '@/types/resources';+import type { TaskResource } from '@/types/resources';-import { toFormattedDate, toTimeSpan } from '@/service/util';+import { toFormattedDate, toFormattedDuration, toTimeSpan, within24Hrs } from '@/service/util';+import { ref } from 'vue';import ButtonCorner from '@/components/inputs/ButtonCorner.vue';import ButtonText from '@/components/inputs/ButtonText.vue';import Popover from '@/components/pinesUI/Popover.vue';+import ChipTag from '@/components/labels/ChipTag.vue';+import ProiconsCommentExclamation from '~icons/proicons/comment-exclamation';import ProiconsMoreVertical from '~icons/proicons/more-vertical';-import ProiconsPersonCircle from '~icons/proicons/person-circle';-import ProiconsLockOpen from '~icons/proicons/lock-open';+import PulseDoughnutChart from '../charts/PulseDoughnutChart.vue';+import ProiconsChevronDown from '~icons/proicons/chevron-down';+import ProiconsArrowSync from '~icons/proicons/arrow-sync';import ProiconsDelete from '~icons/proicons/delete';+import SubTaskCard from './SubTaskCard.vue';+import ButtonIcon from '../inputs/ButtonIcon.vue';-const props = defineProps<{ data: UserResource }>();+const props = defineProps<{ data: TaskResource }>();++const expanded = ref(false);</script><template><div- class="text-left relative flex flex-col xs:flex-row xs:gap-4 xs:p-3 rounded-xl dark:bg-primary-dark-800/70 bg-white ring-1 ring-gray-900/5 dark:hover:bg-primary-dark-600 hover:bg-primary-800 dark:text-white shadow w-full group divide-gray-300 dark:divide-neutral-400"+ class="text-left flex flex-col rounded-xl dark:bg-primary-dark-800/50 bg-primary-800 ring-1 ring-gray-900/5 dark:text-white shadow w-full divide-gray-300 dark:divide-neutral-400">- <img- class="aspect-square h-full max-h-28 xs:max-h-16 my-auto rounded-t-xl xs:rounded-full object-cover"- :src="`https://ui-avatars.com/api/?name=${data.name[0]}&color=7F9CF5&background=random`"- alt="aminushki"- />- <div class="flex flex-col gap-4 flex-wrap flex-1 max-w-full max-h-full p-3 xs:p-0">- <section class="flex justify-between gap-2 w-full items-center">- <h2 class="md:text-xl truncate capitalize flex-1" :title="data.name">- {{ data.name }}- </h2>+ <section+ class="bg-white dark:bg-primary-dark-800/70 dark:hover:bg-primary-dark-600 hover:bg-primary-800 p-3 rounded-xl ring-1 ring-gray-900/5 flex gap-4 w-full items-center flex-wrap"+ >+ <div class="flex flex-col gap-2 sm:gap-1 flex-1 relative">+ <div class="flex gap-x-4 gap-y-2 items-center">+ <h2 class="truncate capitalize group" :title="data.name">+ {{ data.name }}+ <div+ v-if="(data.description?.length ?? 0) > 0"+ class="flex z-30 left-20 bottom-10 absolute opacity-0 group-hover:opacity-100 transition-opacity ease-in-out duration-500 w-1/2 text-sm p-3 bg-white dark:odd:bg-primary-dark-600/70 dark:bg-neutral-800/70 backdrop-blur-lg border dark:border-none rounded-md shadow-md border-neutral-200/70 gap-2 items-center"+ >+ <ProiconsCommentExclamation class="h-4 w-4" />+ <p class="text-wrap">{{ data.description }}</p>+ </div>+ </h2>+ <p+ v-if="data.summary"+ class="flex justify-end gap-1 flex-1 line-clamp-3 sm:line-clamp-1 text-wrap text-ellipsis sm:text-nowrap text-neutral-500 dark:text-neutral-400"+ >+ {{ data.summary }}+ </p>+ </div>+ <div class="grid grid-cols-1 md:grid-cols-3 flex-1 w-fit gap-1">+ <div class="flex gap-1 h-fit">+ <img+ class="aspect-square h-4 my-auto rounded-t-xl xs:rounded-full object-cover"+ :src="`https://ui-avatars.com/api/?name=${data.user[0]}&color=7F9CF5&background=random`"+ alt="aminushki"+ />+ <h4 class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize" title="">+ {{ data.user }}+ </h4>+ </div>++ <span class="flex gap-1">+ <h4 class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize" title="Time">+ {{+ data.ended_at+ ? `Finished: ${toFormattedDate(new Date(data.ended_at + ' UTC'), true, within24Hrs(data.ended_at + ' UTC') ? { hour: '2-digit', minute: '2-digit' } : undefined)}`+ : data.started_at+ ? `Started: ${toFormattedDate(new Date(data.started_at + ' UTC'), true, within24Hrs(data.started_at + ' UTC') ? { hour: '2-digit', minute: '2-digit' } : undefined)}`+ : `Created: ${toFormattedDate(new Date(data.created_at + ' UTC'), true, within24Hrs(data.created_at + ' UTC') ? { hour: '2-digit', minute: '2-digit' } : undefined)}`+ }}+ </h4>++ <h4 class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize" title="Time">+ {{ toFormattedDuration(data.duration) }}+ </h4>+ </span>++ <span class="flex flex-col md:flex-row gap-x-4 flex-1">+ <h4+ class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize w-20"+ title="Pending Tasks"+ >+ Sub Tasks: {{ data.sub_tasks_total }}+ </h4>+ <h4+ class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize"+ v-if="data.sub_tasks_failed"+ title="Failed Tasks"+ >+ Failed: {{ data.sub_tasks_failed }}+ </h4>+ <h4+ class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize"+ v-else+ title="Pending Tasks"+ >+ Pending: {{ data.sub_tasks_pending }}+ </h4>+ </span>+ </div>+ </div>++ <!-- <td>+ <PulseDoughnutChart+ class="!h-8 !w-8"+ :chart-options="{+ borderWidth: 0,+ plugins: {+ legend: {+ display: false,+ },+ tooltip: {+ enabled: false,+ displayColors: false,+ },+ },+ }"+ :chart-data="{+ labels: ['Pending', 'Completed', 'Failed'],+ datasets: [+ {+ data: [data.sub_tasks_pending, data.sub_tasks_complete, data.sub_tasks_failed],+ backgroundColor: ['#c084fc30', '#9333ea', '#be123c'],+ hoverBackgroundColor: ['#c084fc30', '#9333ea', '#e11d48'],+ },+ ],+ }"+ />+ </td> -->- <div class="flex justify-end gap-1 flex-1">+ <div class="flex items-center gap-2 w-full md:w-fit">+ <div class="px-2 text-xs flex flex-col gap-1 h-fit min-w-32 flex-1">+ <p class="w-full text-left pe-8">+ {{ (data.sub_tasks_complete / (data.sub_tasks_total ? data.sub_tasks_total : 1)) * 100 }}% Processed+ </p>+ <div class="rounded-full h-1 w-full bg-primary-dark-900 flex overflow-clip">+ <div+ :class="`h-1 bg-purple-600 rounded-full`"+ :style="`width: ${(data.sub_tasks_complete / (data.sub_tasks_total ? data.sub_tasks_total : 1)) * 100}%;`"+ ></div>+ <div+ :class="`h-1 bg-amber-500 rounded-full`"+ :style="`width: ${(data.sub_tasks_pending / (data.sub_tasks_total ? data.sub_tasks_total : 1)) * 100}%;`"+ ></div>+ <div+ :class="`h-1 bg-rose-600 rounded-full`"+ :style="`width: ${(data.sub_tasks_failed / (data.sub_tasks_total ? data.sub_tasks_total : 1)) * 100}%;`"+ ></div>+ </div>+ </div>+ <div class="flex gap-1 items-center ml-auto">+ <ChipTag+ :class="`h-6 shadow-sm`"+ :colour="`!text-white ${+ data.status === 'pending'+ ? 'bg-[#e4e4e4] dark:bg-white !text-neutral-900'+ : data.status === 'processing'+ ? 'bg-purple-600 dark:bg-purple-700'+ : data.status === 'completed'+ ? 'bg-[#660099] '+ : data.status === 'incomplete' || data.status === 'cancelled'+ ? 'bg-amber-500 !text-neutral-900 '+ : 'bg-rose-600 dark:bg-rose-700 '+ }`"+ :label="data.status"+ /><Popover- popoverClass="w-48 rounded-lg "+ popoverClass="w-40 rounded-lg ":buttonComponent="ButtonCorner":button-attributes="{- positionClasses: 'w-7 h-7 !p-1 ml-auto sm:hidden',+ positionClasses: 'w-7 h-7 !p-1 ml-auto',textClasses: 'hover:text-violet-600 dark:hover:text-violet-500',- colourClasses: 'dark:hover:bg-neutral-800 hover:bg-gray-200',+ colourClasses: 'dark:hover:bg-neutral-900 hover:bg-gray-100 hover:shadow-md',label: 'Manage Permissions',}"+ @click.stop="() => {}"><template #buttonIcon><ProiconsMoreVertical class="h-4 w-4" />@@ -46,87 +182,75 @@ const props = defineProps<{ data: UserResource }>();<template #content><div class="grid gap-4"><div class="space-y-2">- <h4 class="font-medium leading-none">Manage User</h4>+ <h4 class="font-medium leading-none">Manage Task</h4></div><div class="grid gap-2">- <ButtonText- class="h-8 dark:!bg-neutral-950 2xl:hidden"- :title="'Scan for Folder Changes'"- :to="'/profile'"- >- <template #text> View Profile </template>- <template #icon> <ProiconsPersonCircle class="h-4 w-4" /></template>+ <ButtonText class="h-8 dark:!bg-neutral-950" :title="'Scan for Folder Changes'" :to="'/profile'">+ <template #text> Run Again </template>+ <template #icon> <ProiconsArrowSync class="h-4 w-4" /></template></ButtonText><ButtonText- class="h-8 dark:!bg-neutral-950 disabled:opacity-60"- :title="'Set User Access Permissions'"+ v-if="data.status_key >= 0 && data.status_key <= 1"+ class="h-8 text-rose-600 dark:!bg-rose-700 disabled:opacity-60"+ :title="'Remove User From Server'"+ @click.stop.prevent="$emit('clickAction')"disabled>- <template #text> Manage Permissions </template>- <template #icon> <ProiconsLockOpen class="h-4 w-4" /></template>+ <template #text> Cancel </template>+ <template #icon> <ProiconsDelete class="h-4 w-4" /></template></ButtonText><ButtonText+ v-elseclass="h-8 text-rose-600 dark:!bg-rose-700 disabled:opacity-60"- :title="'Remove User From Server'"+ :title="'Remove Record From Server'"@click.stop.prevent="$emit('clickAction')"disabled>- <template #text> Remove User </template>+ <template #text> Remove </template><template #icon> <ProiconsDelete class="h-4 w-4" /></template></ButtonText></div></div></template></Popover>- <ButtonCorner- :positionClasses="'w-7 h-7 sm:flex hidden'"- :textClasses="'hover:text-violet-600 dark:hover:text-violet-500'"- :colourClasses="'dark:hover:bg-neutral-800 hover:bg-gray-200'"- :to="`/profile/${data.name}`"- :label="'View Profile'"- @click.stop.prevent="() => {}"+ <ButtonIcon+ variant="ghost"+ :class="`hover:shadow-md rounded-xl transition-transform duration-200 ease-in-out p-1 w-fit h-fit dark:hover:bg-neutral-900 hover:bg-gray-100 ${expanded ? 'rotate-180' : 'rotate-0'}`"+ @click="expanded = !expanded"+ :title="`${expanded ? 'Hide Sub Tasks' : 'Show Sub Tasks'}`"><template #icon>- <ProiconsPersonCircle width="20" height="20" />+ <ProiconsChevronDown :class="`w-6 h-6 hover:text-violet-600 dark:hover:text-violet-500`" /></template>- </ButtonCorner>- <ButtonCorner- :positionClasses="'w-7 h-7 sm:flex hidden'"- :textClasses="'hover:text-violet-600 dark:hover:text-violet-500'"- :colourClasses="'dark:hover:bg-neutral-800 hover:bg-gray-200'"- :label="'Manage Permissions'"- @click.stop.prevent="() => {}"- disabled- >- <template #icon>- <ProiconsLockOpen width="20" height="20" />- </template>- </ButtonCorner>- <ButtonCorner- :positionClasses="'w-7 h-7 sm:flex hidden'"- :textClasses="'text-rose-700 hover:text-rose-600'"- :colourClasses="'dark:hover:bg-neutral-800 hover:bg-gray-200'"- :label="'Remove User'"- disabled- @click.stop.prevent="$emit('clickAction')"- />+ </ButtonIcon></div>- </section>- <section class="flex flex-col sm:flex-row sm:justify-between w-full text-sm text-neutral-500 dark:text-neutral-400">- <h3 class="w-full text-wrap truncate sm:text-nowrap" :title="`Date joined`">- Date Joined:- {{- data.created_at- ? toFormattedDate(new Date(data.created_at), false, { year: 'numeric', month: 'short', day: 'numeric' })- : 'Unknown'- }}+ </div>+ <!-- <section class="flex flex-col sm:flex-row sm:justify-between w-full text-sm text-neutral-500 dark:text-neutral-400">+ <h3 class="w-full text-wrap line-clamp-2" :title="`Description`">+ {{ data.summary ?? 'This task has no summary.' }}</h3>- <h3 class="truncate sm:text-right w-full line-clamp-2 capitalize" v-show="data.last_active" title="Last date of activity">- Last Active:- {{ data.last_active ? toTimeSpan(new Date(data.last_active + ' UTC')) : 'Unknown' }}- </h3>- </section>- </div>+ <span>+ <h3 class="truncate sm:text-right w-full line-clamp-1 capitalize" title="Time Started">+ Started:+ {{ data.created_at ? toFormattedDate(new Date(data.created_at)) : 'Unknown' }}+ </h3>+ <h3 class="truncate sm:text-right w-full line-clamp-1 capitalize" title="Time Started">Duration: 23m</h3>+ </span>+ </section> -->+ </section>++ <section+ :class="`flex flex-col overflow-hidden transition-all duration-300 ease-in-out ${expanded ? `py-1` : ''}`"+ :style="`height: ${expanded ? `${Math.max(52, (data?.sub_tasks?.length ?? 0) * (68 + 4))}px` : '0px'};`"+ >+ <SubTaskCard v-for="subTask in data.sub_tasks" :key="subTask.id" :data="subTask" />+ <div+ v-if="(data.sub_tasks?.length ?? 0) == 0"+ class="col-span-full flex items-center justify-center text-center text-gray-500 dark:text-gray-400 uppercase tracking-wider w-full gap-2 text-sm my-auto"+ >+ {{ 'No Sub Tasks Found' }}+ </div>+ </section></div></template>diff --git a/resources/js/components/cards/UserCard.vue b/resources/js/components/cards/UserCard.vueindex 8004bbc3..c971b561 100644--- a/resources/js/components/cards/UserCard.vue+++ b/resources/js/components/cards/UserCard.vue@@ -21,17 +21,17 @@ const props = defineProps<{ data: UserResource }>();<imgclass="aspect-square h-full max-h-28 xs:max-h-16 my-auto rounded-t-xl xs:rounded-full object-cover":src="`https://ui-avatars.com/api/?name=${data.name[0]}&color=7F9CF5&background=random`"- alt="aminushki"+ :alt="data.name ?? 'user profile picture'"/><div class="flex flex-col gap-4 flex-wrap flex-1 max-w-full max-h-full p-3 xs:p-0"><section class="flex justify-between gap-2 w-full items-center">- <h2 class="md:text-xl truncate capitalize flex-1" :title="data.name">+ <h2 class="truncate capitalize flex-1" :title="data.name ?? 'username'">{{ data.name }}</h2><div class="flex justify-end gap-1 flex-1"><Popover- popoverClass="w-48 rounded-lg "+ popoverClass="w-64 rounded-lg ":buttonComponent="ButtonCorner":button-attributes="{positionClasses: 'w-7 h-7 !p-1 ml-auto sm:hidden',diff --git a/resources/js/components/charts/PulseDoughnutChart.vue b/resources/js/components/charts/PulseDoughnutChart.vueindex 60b037f6..0ff29b44 100644--- a/resources/js/components/charts/PulseDoughnutChart.vue+++ b/resources/js/components/charts/PulseDoughnutChart.vue@@ -1,6 +1,9 @@<script setup lang="ts">+import { Chart, registerables } from 'chart.js';import { Doughnut } from 'vue-chartjs';+Chart.register(...registerables);+const props = defineProps<{class: string;chartData?: any;diff --git a/resources/js/components/dashboard/DashboardActivity.vue b/resources/js/components/dashboard/DashboardActivity.vueindex 5a4b8b21..6104ba2a 100644--- a/resources/js/components/dashboard/DashboardActivity.vue+++ b/resources/js/components/dashboard/DashboardActivity.vue@@ -55,7 +55,10 @@ const handleSort = async (column = 'date', dir = 1) => {let dateB = new Date(categoryB?.created_at ?? '');return (dateB.getTime() - dateA.getTime()) * dir;}- return `${categoryB[column as keyof CategoryResource]}`?.localeCompare(`${categoryA[column as keyof CategoryResource]}`) * dir;+ let valueA = categoryA[column as keyof CategoryResource];+ let valueB = categoryB[column as keyof CategoryResource];+ if (valueA && valueB && typeof valueA === 'number' && typeof valueB === 'number') return (valueB - valueA) * dir;+ return `${valueB}`?.localeCompare(`${valueA}`) * dir;});categories.value = tempList;return tempList;diff --git a/resources/js/components/dashboard/DashboardLibraries.vue b/resources/js/components/dashboard/DashboardLibraries.vueindex 75752340..224db8b8 100644--- a/resources/js/components/dashboard/DashboardLibraries.vue+++ b/resources/js/components/dashboard/DashboardLibraries.vue@@ -78,7 +78,10 @@ const handleSort = async (column = 'date', dir = 1) => {let dateB = new Date(categoryB?.created_at ?? '');return (dateB.getTime() - dateA.getTime()) * dir;}- return `${categoryB[column as keyof CategoryResource]}`?.localeCompare(`${categoryA[column as keyof CategoryResource]}`) * dir;+ let valueA = categoryA[column as keyof CategoryResource];+ let valueB = categoryB[column as keyof CategoryResource];+ if (valueA && valueB && typeof valueA === 'number' && typeof valueB === 'number') return (valueB - valueA) * dir;+ return `${valueB}`?.localeCompare(`${valueA}`) * dir;});categories.value = tempList;return tempList;diff --git a/resources/js/components/dashboard/DashboardTasks.vue b/resources/js/components/dashboard/DashboardTasks.vueindex e1f00f17..a12faa9f 100644--- a/resources/js/components/dashboard/DashboardTasks.vue+++ b/resources/js/components/dashboard/DashboardTasks.vue@@ -1,59 +1,75 @@<script setup lang="ts">-import type { UserResource } from '@/types/resources';+import type { TaskStatsResponse } from '@/types/types';+import type { TaskResource } from '@/types/resources';++import { getTasks, getTaskStats, startIndexFilesTask, startSyncFilesTask, startVerifyFilesTask } from '@/service/siteAPI';-import { getActiveSessions, getUsers, startIndexFilesTask, startSyncFilesTask, startVerifyFilesTask } from '@/service/siteAPI';import { computed, onMounted, ref, useTemplateRef } from 'vue';import { toast } from '@/service/toaster/toastService';import ButtonText from '@/components/inputs/ButtonText.vue';import ModalBase from '@/components/pinesUI/ModalBase.vue';import TableBase from '@/components/table/TableBase.vue';+import TaskCard from '@/components/cards/TaskCard.vue';import useModal from '@/composables/useModal';+import Popover from '@/components/pinesUI/Popover.vue';-import UserCard from '../cards/UserCard.vue';-import Popover from '../pinesUI/Popover.vue';--import ProiconsArrowSync from '~icons/proicons/arrow-sync';-import ProiconsAdd from '~icons/proicons/add';--import LucideFolderSync from '~icons/lucide/folder-sync';import LucideFolderSearch from '~icons/lucide/folder-search';import LucideFolderCheck from '~icons/lucide/folder-check';+import ProiconsArrowSync from '~icons/proicons/arrow-sync';import LucideFolderTree from '~icons/lucide/folder-tree';+import LucideFolderSync from '~icons/lucide/folder-sync';+import ProiconsAdd from '~icons/proicons/add';const confirmModal = useModal({ title: 'Remove User?', submitText: 'Confim' });const searchQuery = ref('');const sortingOptions = ref([{- title: 'Username',+ title: 'Name',value: 'name',disabled: false,},{- title: 'Date Joined',+ title: 'Add Time',value: 'created_at',disabled: false,},{- title: 'Last Active',- value: 'last_active',+ title: 'Start Time',+ value: 'started_at',+ disabled: false,+ },+ {+ title: 'End Time',+ value: 'ended_at',+ disabled: false,+ },+ {+ title: 'Status',+ value: 'status_key',+ disabled: false,+ },+ {+ title: 'Task Length',+ value: 'sub_tasks',disabled: false,},]);-const activeSessions = ref(0);-const users = ref<UserResource[]>([]);+const taskStats = ref<TaskStatsResponse>();+const tasks = ref<TaskResource[]>([]);+const cachedID = ref<number | null>(null);const taskPopover = useTemplateRef('taskPopover');-const filteredUsers = computed(() => {+const filteredTasks = computed(() => {let tempList = searchQuery.value- ? users.value.filter((user: UserResource) => {+ ? tasks.value.filter((task: TaskResource) => {{try {- let strRepresentation = [user.name, user.email, user.created_at].join(' ').toLowerCase();+ let strRepresentation = [task.name, task.summary, task.description, task.created_at].join(' ').toLowerCase();return strRepresentation.includes(searchQuery.value.toLowerCase());} catch (error) {console.log(error);@@ -61,20 +77,24 @@ const filteredUsers = computed(() => {}}})- : users.value;+ : tasks.value;return tempList;});const handleSort = async (column = 'date', dir = 1) => {- let tempList = users.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] ?? '');+ let tempList = tasks.value.sort((taskA: TaskResource, taskB: TaskResource) => {+ if (column === 'created_at' || column === 'started_at' || column === 'ended_at') {+ let dateA = new Date(taskA?.[column] ?? '');+ let dateB = new Date(taskB?.[column] ?? '');return (dateB.getTime() - dateA.getTime()) * dir;}- return `${userB[column as keyof UserResource]}`?.localeCompare(`${userA[column as keyof UserResource]}`) * dir;++ let valueA = taskA[column as keyof TaskResource];+ let valueB = taskB[column as keyof TaskResource];+ if (valueA && valueB && typeof valueA === 'number' && typeof valueB === 'number') return (valueB - valueA) * dir;+ return `${valueB}`?.localeCompare(`${valueA}`) * dir;});- users.value = tempList;+ tasks.value = tempList;return tempList;};@@ -97,12 +117,11 @@ const submitDelete = async () => {};const loadData = async () => {- const { data: rawActiveSessions } = await getActiveSessions();- activeSessions.value = parseInt(rawActiveSessions) ?? 0;-- const { data: rawUsers } = await getUsers();+ const { data: rawTaskStats } = await getTaskStats();+ taskStats.value = rawTaskStats ?? undefined;- users.value = rawUsers?.data?.length > 0 ? rawUsers.data : [];+ const { data: rawTasks } = await getTasks();+ tasks.value = rawTasks?.data?.length > 0 ? rawTasks.data : [];};const handleStartTask = async (job: 'index' | 'sync' | 'verify') => {@@ -195,14 +214,14 @@ 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">Running Tasks: {{ activeSessions }}</p>- <p class="w-fit">Failed Tasks: {{ users.length }}</p>+ <p class="w-fit">Running Tasks: {{ tasks.filter((task) => task.status === 'processing').length }}</p>+ <p class="w-fit">Total Tasks: {{ tasks.length }}</p></div></div><TableBase:use-pagination="true"- :data="[...filteredUsers]"- :row="UserCard"+ :data="[...filteredTasks]"+ :row="TaskCard":loading="false":clickAction="handleDelete":sort-action="handleSort"@@ -214,7 +233,7 @@ onMounted(() => {<ModalBase :modalData="confirmModal" :action="submitDelete"><template #content><div class="relative w-auto pb-8">- <p>Are you sure you want to remove this user?</p>+ <p>Are you sure you want to cancel this task and all of its sub tasks?</p></div></template></ModalBase>diff --git a/resources/js/components/dashboard/DashboardUsers.vue b/resources/js/components/dashboard/DashboardUsers.vueindex ed6730ae..1cbaf02c 100644--- a/resources/js/components/dashboard/DashboardUsers.vue+++ b/resources/js/components/dashboard/DashboardUsers.vue@@ -63,7 +63,10 @@ const handleSort = async (column = 'date', dir = 1) => {let dateB = new Date(userB?.[column] ?? '');return (dateB.getTime() - dateA.getTime()) * dir;}- return `${userB[column as keyof UserResource]}`?.localeCompare(`${userA[column as keyof UserResource]}`) * 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 (valueB - valueA) * dir;+ return `${valueB}`?.localeCompare(`${valueA}`) * dir;});users.value = tempList;return tempList;diff --git a/resources/js/components/inputs/ButtonIcon.vue b/resources/js/components/inputs/ButtonIcon.vueindex 92616b59..1a8235b1 100755--- a/resources/js/components/inputs/ButtonIcon.vue+++ b/resources/js/components/inputs/ButtonIcon.vue@@ -1,20 +1,33 @@<script setup lang="ts">-const props = defineProps<{- class?: string;- type?: 'reset' | 'submit' | 'button' | undefined;- disabled?: boolean;- title?: string;-}>();+const props = withDefaults(+ defineProps<{+ class?: string;+ type?: 'reset' | 'submit' | 'button' | undefined;+ disabled?: boolean;+ title?: string;+ variant?: 'default' | 'ghost';+ }>(),+ {+ variant: 'default',+ },+);</script><template><button- :class="`p-2 flex items-center justify-center h-10 max-h-full- aspect-square shadow-sm rounded-md cursor-pointer focus:outline-none- ring-1 ring-neutral-200 dark:ring-neutral-700 hocus:ring-[0.125rem]+ :class="`flex items-center justify-center h-10 max-h-full+ aspect-square rounded-md cursor-pointer focus:outline-none+ text-gray-900 dark:text-neutral-100+ ${+ variant === 'default'+ ? `p-2 shadow-sm+ ring-1 ring-neutral-200 dark:ring-neutral-700 hocus:ring-[0.125rem]focus:ring-indigo-400 dark:focus:ring-indigo-500 hover:ring-violet-400 hover:dark:ring-violet-700- text-gray-900 dark:text-neutral-100 bg-white dark:bg-primary-dark-800- ${props.class} disabled:cursor-not-allowed disabled:hover:ring-neutral-200 disabled:hover:dark:ring-neutral-700 disabled:ring-1`"+ bg-white dark:bg-primary-dark-800+ disabled:cursor-not-allowed disabled:hover:ring-neutral-200 disabled:hover:dark:ring-neutral-700 disabled:ring-1`+ : ''+ }+ ${props.class} `":type="props.type":disabled="props.disabled":title="props.title ?? 'Icon'"diff --git a/resources/js/components/pinesUI/Accordion.vue b/resources/js/components/pinesUI/Accordion.vuenew file mode 100644index 00000000..adadd376--- /dev/null+++ b/resources/js/components/pinesUI/Accordion.vue@@ -0,0 +1,63 @@+<script setup lang="ts">+import { ref } from 'vue';++const props = defineProps();++const activeAccordion = ref<string>('');+const accordions = ref<{ id: string; key: string; value: string }[]>([+ { id: '1', key: 'What is Pines?', value: 'Pines is a UI library built for AlpineJS and TailwindCSS.' },+ {+ id: '2',+ key: 'How do I install Pines?',+ value: 'Add AlpineJS and TailwindCSS to your page and then copy and paste any of these elements into your project.',+ },+ {+ id: '3',+ key: 'Can I use Pines with other libraries or frameworks?',+ value: 'Absolutely! Pines works with any other library or framework. Pines works especially well with the TALL stack.',+ },+]);++function setActiveAccordion(id: string) {+ activeAccordion.value = activeAccordion.value == id ? '' : id;+}+</script>+<template>+ <!-- :class="{ 'rotate-180': activeAccordion == id }" -->+ <div+ class="relative w-full mx-auto overflow-hidden text-sm font-normal bg-white border border-gray-200 divide-y divide-gray-200 rounded-md"+ >+ <div v-for="accordion in accordions" :key="accordion.id" class="cursor-pointer group">+ <button+ @click="setActiveAccordion(accordion.id)"+ class="flex items-center justify-between w-full p-4 text-left select-none group-hover:underline"+ >+ <span>{{ accordion.key }}</span>+ <svg+ :class="`w-4 h-4 duration-200 ease-out ${activeAccordion == accordion.id ? 'rotate-180' : ''}`"+ viewBox="0 0 24 24"+ xmlns="http://www.w3.org/2000/svg"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ >+ <polyline points="6 9 12 15 18 9"></polyline>+ </svg>+ </button>+ <Transition+ enter-active-class=""+ enter-from-class="h-0 overflow-hidden"+ enter-to-class="h-full overflow-hidden"+ leave-active-class=""+ leave-from-class="h-0 overflow-hidden"+ leave-to-class="h-0 overflow-hidden"+ >+ <div class="ease-in duration-300" v-show="activeAccordion == accordion.id" v-cloak>+ <div class="p-4 pt-0 opacity-70">{{ accordion.value }}</div>+ </div>+ </Transition>+ </div>+ </div>+</template>diff --git a/resources/js/service/siteAPI.ts b/resources/js/service/siteAPI.tsindex 2e71119c..dd6b4159 100644--- a/resources/js/service/siteAPI.ts+++ b/resources/js/service/siteAPI.ts@@ -23,6 +23,18 @@ export function getActiveSessions() {return API.get('/active-sessions');}+export function getTasks() {+ return API.get('/tasks');+}++export function getTaskStats() {+ return API.get('/tasks/stats');+}++export function startGenericTast(url: string) {+ return API.post(`/tasks/${url}`);+}+export function startIndexFilesTask(category?: number) {return API.post(`/tasks/index/${category ?? ''}`);}diff --git a/resources/js/service/util.ts b/resources/js/service/util.tsindex 327999db..678ea8c6 100644--- a/resources/js/service/util.ts+++ b/resources/js/service/util.ts@@ -44,7 +44,19 @@ export function toFormattedDate(hour12: true,},) {- let result = rawDate.toLocaleString(['en-CA'], format).replaceAll('.', '');+ let result = rawDate+ .toLocaleString(+ ['en-CA'],+ format ?? {+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ hour12: true,+ },+ )+ .replaceAll('.', '');return toUpperCase ? result.toLocaleUpperCase() : result;}@@ -127,3 +139,11 @@ export function formatFileSize(size: number, space = true) {const formattedSize = Math.round(size * 100) / 100;return `${formattedSize}${space ? ' ' : ''}${units[unitIndex]}`;}++export function within24Hrs(date: string) {+ const now = new Date();+ const then = new Date(date);+ const diffInHours = (now.getTime() - then.getTime()) / (1000 * 60 * 60);++ return diffInHours < 24;+}diff --git a/resources/js/stores/ContentStore.js b/resources/js/stores/ContentStore.jsindex c582eb82..30f12807 100755--- a/resources/js/stores/ContentStore.js+++ b/resources/js/stores/ContentStore.js@@ -50,9 +50,11 @@ export const useContentStore = defineStore('Content', () => {let dateB = new Date(videoB[videoSort.value.column]);return (dateB - dateA) * videoSort.value.dir;}- if (videoSort.value.column === 'name' || videoSort.value.column === 'title')- return videoA[videoSort.value.column].localeCompare(videoB[videoSort.value.column]) * videoSort.value.dir;- return (videoB[videoSort.value.column] - videoA[videoSort.value.column]) * videoSort.value.dir;+ let valueA = videoA[videoSort.value.column];+ let valueB = videoB.relationships[videoSort.value.column];+ if (valueA && valueB && typeof valueA === 'number' && typeof valueB === 'number')+ return (valueB - valueA) * videoSort.value.dir;+ return `${valueB}`?.localeCompare(`${valueA}`) * videoSort.value.dir;});return sortedList;@@ -68,7 +70,10 @@ export const useContentStore = defineStore('Content', () => {let dateB = new Date(recordB?.attributes['created_at']);return (dateB - dateA) * dir;}- return recordB?.relationships[column]?.localeCompare(recordA?.relationships[column]) * dir;+ let valueA = recordA.relationships[column];+ let valueB = recordB.relationships[column];+ if (valueA && valueB && typeof valueA === 'number' && typeof valueB === 'number') return (valueB - valueA) * dir;+ return `${valueB}`?.localeCompare(`${valueA}`) * dir;});stateRecords.value = tempList;return tempList;diff --git a/resources/js/types/resources.ts b/resources/js/types/resources.tsindex 885f3bc5..7013405a 100644--- a/resources/js/types/resources.ts+++ b/resources/js/types/resources.ts@@ -1,4 +1,5 @@import type { Category, Folder, Metadata, User } from './model';+import type { TaskStatus } from './types';export interface UserResource {id: number;@@ -133,3 +134,39 @@ export interface VideoTagResource {name?: string;id: number; // tag id}++export interface TaskResource {+ id: number;+ user: string;+ status: TaskStatus;+ status_key: number;+ name?: string;+ summary?: string;+ description?: string;+ url?: string;+ sub_tasks: SubTaskResource[];+ sub_tasks_total: number;+ sub_tasks_pending: number;+ sub_tasks_complete: number;+ sub_tasks_failed: number;+ duration: number;+ started_at?: Date;+ ended_at?: Date;+ created_at: Date;+ updated_at: Date;+}++export interface SubTaskResource {+ id: number;+ task_id: number;+ status: TaskStatus;+ status_key: number;+ name?: string;+ summary?: string;+ progress: number;+ duration: number;+ started_at?: Date;+ ended_at?: Date;+ created_at: Date;+ updated_at: Date;+}diff --git a/resources/js/types/types.ts b/resources/js/types/types.tsindex 647fca2f..41cb925b 100644--- a/resources/js/types/types.ts+++ b/resources/js/types/types.ts@@ -117,6 +117,15 @@ export interface SiteAnalyticsResponse {prev: number;}+export interface TaskStatsResponse {+ avg_duration: number;+ avg_fail_rate: number;+ count_cancelled: number;+ avg_count_sub_tasks: number;+ count_tasks: number;+ count_subtasks: number;+}+export interface FormField {name: string;text: string;@@ -126,3 +135,5 @@ export interface FormField {default?: any;class?: string;}++export type TaskStatus = 'pending' | 'processing' | 'completed' | 'cancelled' | 'failed' | 'incomplete';diff --git a/routes/api.php b/routes/api.phpindex a703b11d..27b8ab35 100755--- a/routes/api.php+++ b/routes/api.php@@ -10,6 +10,7 @@ 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\TagController;+use App\Http\Controllers\Api\V1\TasksController;use App\Http\Controllers\Api\V1\UserController;use App\Http\Controllers\Api\V1\VideoController;use App\Http\Controllers\DirectoryController;@@ -36,9 +37,11 @@ Route::group(['middleware' => ['auth:sanctum']], function () {Route::resource('/tags', TagController::class)->only(['index', 'store']);Route::resource('/analytics', AnalyticsController::class)->only(['index']);Route::resource('/categories', CategoryController::class)->only(['index', 'update']);- Route::resource('/users', UserController::class)->only(['index']);+ Route::resource('/users', UserController::class)->only(['index', 'destroy']);Route::prefix('tasks')->group(function () {+ Route::resource('/', TasksController::class)->only(['index']);+ Route::get('/stats', [TasksController::class, 'stats']);Route::post('/sync', [DirectoryController::class, 'syncFiles']);Route::post('/index/{category?}', [DirectoryController::class, 'indexFiles']);Route::post('/verify/{category?}', [DirectoryController::class, 'verifyFiles']);