Skip to content

A self-hosted media server and file management system

Better tasks, better UI, album covers and audio metadata + support for ogg (tested) and flac (untested)

aminnausin8ab1d2996dec
diff --git a/.prettierrc.json b/.prettierrc.json
index a71af370..60326bd4 100644
--- a/.prettierrc.json
+++ b/.prettierrc.json
@@ -3,7 +3,7 @@
"semi": true,
"singleQuote": true,
"tabWidth": 4,
- "printWidth": 140,
+ "printWidth": 180,
"overrides": [
{
"files": "*.md",
diff --git a/app/Enums/TaskStatus.php b/app/Enums/TaskStatus.php
index b7bb09bd..cbbc2429 100644
--- a/app/Enums/TaskStatus.php
+++ b/app/Enums/TaskStatus.php
@@ -10,7 +10,6 @@ enum TaskStatus: int {
case CANCELLED = -1;
case FAILED = -2;
-
public function isPending(): bool {
return $this === self::PENDING;
}
diff --git a/app/Http/Controllers/Api/V1/SubTaskController.php b/app/Http/Controllers/Api/V1/SubTaskController.php
index 522a9250..8b58fae6 100644
--- a/app/Http/Controllers/Api/V1/SubTaskController.php
+++ b/app/Http/Controllers/Api/V1/SubTaskController.php
@@ -65,14 +65,15 @@ class SubTaskController extends Controller {
public function update(Request $request, string $id) {
//
}
+
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
- public function destroy(SubTask $task) {
- return $this->isNotAuthorised() ?? $task->delete() ? $this->success('', 'Success', 200) : $this->error('', 'Not found', 404);
+ public function destroy(SubTask $subTask) {
+ return $this->isNotAuthorised() ?? $subTask->delete() ? $this->success('', 'Success', 200) : $this->error($subTask, 'Not found', 404);
}
private function isNotAuthorised() {
diff --git a/app/Http/Controllers/Api/V1/TasksController.php b/app/Http/Controllers/Api/V1/TasksController.php
index 9b345462..54817fe6 100644
--- a/app/Http/Controllers/Api/V1/TasksController.php
+++ b/app/Http/Controllers/Api/V1/TasksController.php
@@ -4,7 +4,6 @@ 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;
@@ -42,7 +41,6 @@ class TasksController extends Controller {
return Response('Forbidden', 403);
}
-
$results = DB::table('sub_tasks')
->select(
DB::raw('AVG(duration) as avg_duration'),
@@ -52,7 +50,6 @@ class TasksController extends Controller {
)
->first();
-
$taskCounts = Task::select(
DB::raw('COUNT(*) as count_tasks'),
DB::raw('AVG(sub_tasks_total) as avg_count_sub_tasks')
diff --git a/app/Http/Controllers/DirectoryController.php b/app/Http/Controllers/DirectoryController.php
index 863d2728..708b304e 100755
--- a/app/Http/Controllers/DirectoryController.php
+++ b/app/Http/Controllers/DirectoryController.php
@@ -65,9 +65,9 @@ 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.";
+ 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\"";
@@ -108,17 +108,21 @@ class DirectoryController extends Controller {
});
$batch = $this->setupBatch($chain, $task);
- $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain)]);
+ $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain), 'sub_tasks_pending' => 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(),]);
+ 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.";
+ 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";
@@ -136,9 +140,13 @@ class DirectoryController extends Controller {
$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(),]);
+ if ($task) {
+ $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now()]);
+ }
+
return response()->json(['error' => 'Error cannot index files', 'details' => $th->getMessage()], 500);
// dump($th);
}
@@ -149,23 +157,29 @@ class DirectoryController extends Controller {
$task = $this->setupTask($userId, 'Sync Files', 'Syncs local file structure with database.', 1);
try {
- if (!isset($task->id)) throw ('waaa');
+ 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(),]);
+ 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.";
+ 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\"";
@@ -203,19 +217,23 @@ class DirectoryController extends Controller {
});
$batch = $this->setupBatch($chain, $task);
- $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain)]);
+ $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain), 'sub_tasks_pending' => count($chain)]);
+
return response()->json(['task_id' => $task->id, 'message' => 'Async Task "VERIFY FILES" was started.']);
} catch (\Throwable $th) {
- if ($task) $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now(),]);
+ 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);
}
}
- public function verifyFolders(Request $request, Category $category = null) {
- $name = "Verify Folders";
- $description = "Verifies folder metadata for all Libraries.";
+ public function verifyFolders(Request $request, ?Category $category = null) {
+ $name = 'Verify Folders';
+ $description = 'Verifies folder metadata for all Libraries.';
if (isset($category)) {
$name .= " for Library \"$category->name\"";
@@ -231,8 +249,6 @@ class DirectoryController extends Controller {
$folderQuery = Folder::orderBy('id');
if ($category) {
-
-
$folderQuery = $folderQuery->whereHas('category', function ($query) use ($category) {
$query->where('id', $category->id);
})->with('category');
@@ -245,10 +261,14 @@ class DirectoryController extends Controller {
});
$batch = $this->setupBatch($chain, $task);
- $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain)]);
+ $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain), 'sub_tasks_pending' => count($chain)]);
+
return response()->json(['task_id' => $task->id, 'message' => 'Async Task "VERIFY FOLDERS" was started.']);
} catch (\Throwable $th) {
- if ($task) $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now(),]);
+ if ($task) {
+ $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now()]);
+ }
+
return response()->json(['error' => 'Error cannot verify folders', 'details' => $th->getMessage()], 500);
// dump('Error cannot verify file metadata');
// dump($th);
@@ -256,8 +276,8 @@ class DirectoryController extends Controller {
}
public function cleanPaths(Request $request) {
- $name = "Clean Paths";
- $description = "Cleans file and folder paths for all Libraries.";
+ $name = 'Clean Paths';
+ $description = 'Cleans file and folder paths for all Libraries.';
try {
$userId = $request->user() ? $request->user()->id : null;
@@ -274,13 +294,14 @@ class DirectoryController extends Controller {
});
$batch = $this->setupBatch($chain, $task);
- $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain)]);
+ $task->update(['batch_id' => $batch->id, 'sub_tasks_total' => count($chain), 'sub_tasks_pending' => count($chain)]);
return response()->json(['task_id' => $task->id, 'message' => 'Async Task "CLEAN PATHS" was started.']);
} catch (\Throwable $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);
}
}
@@ -297,12 +318,12 @@ class DirectoryController extends Controller {
public static function setupBatch($chain, Task $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,
- ]);
+ // $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,
@@ -324,11 +345,11 @@ class DirectoryController extends Controller {
$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,
+ // '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
+ 'duration' => $duration < 0 ? $duration * -1 : $duration,
]);
})->before(function (Batch $batch) use ($task) {
$task->update([
diff --git a/app/Http/Middleware/UserLastActive.php b/app/Http/Middleware/UserLastActive.php
index bc4e73a7..634b34da 100644
--- a/app/Http/Middleware/UserLastActive.php
+++ b/app/Http/Middleware/UserLastActive.php
@@ -17,6 +17,7 @@ class UserLastActive {
if (Auth::check()) {
User::where('id', Auth::user()->id)->update(['last_active' => Carbon::now()]);
}
+
return $next($request);
}
}
diff --git a/app/Http/Requests/IndexFilesRequest.php b/app/Http/Requests/IndexFilesRequest.php
index 3d8e5218..36e1699e 100644
--- a/app/Http/Requests/IndexFilesRequest.php
+++ b/app/Http/Requests/IndexFilesRequest.php
@@ -22,7 +22,7 @@ class IndexFilesRequest extends FormRequest {
public function rules(): array {
return [
'categories' => 'sometimes|array',
- 'categories.*' => 'integer|min:1'
+ 'categories.*' => 'integer|min:1',
];
}
}
diff --git a/app/Http/Resources/TasksResource.php b/app/Http/Resources/TasksResource.php
index 8634311d..cef1a2fc 100644
--- a/app/Http/Resources/TasksResource.php
+++ b/app/Http/Resources/TasksResource.php
@@ -14,7 +14,6 @@ class TasksResource extends JsonResource {
*
* @return array<string, mixed>
*/
-
public function toArray(Request $request): array {
$userId = $this->user_id; // Assuming editor_id is the foreign key
$user = null;
@@ -34,7 +33,7 @@ class TasksResource extends JsonResource {
'name' => $this->name,
'description' => $this->description,
'summary' => $this->summary,
- 'sub_tasks' => [],
+ 'sub_tasks' => [],
'sub_tasks_total' => $this->sub_tasks_total,
'sub_tasks_pending' => $this->sub_tasks_pending,
'sub_tasks_complete' => $this->sub_tasks_complete,
diff --git a/app/Jobs/CleanFolderPaths.php b/app/Jobs/CleanFolderPaths.php
index 57bff06c..5989eaf0 100644
--- a/app/Jobs/CleanFolderPaths.php
+++ b/app/Jobs/CleanFolderPaths.php
@@ -18,8 +18,11 @@ class CleanFolderPaths implements ShouldQueue {
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $taskId;
+
protected $subTaskId;
+
protected $startedAt;
+
/**
* Create a new job instance.
*/
@@ -37,6 +40,7 @@ class CleanFolderPaths implements ShouldQueue {
if ($this->batch() && $this->batch()->cancelled()) {
// Determine if the batch has been cancelled...
SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::CANCELLED, 'summary' => 'Parent Task was Cancelled']);
+
return;
}
@@ -54,13 +58,14 @@ class CleanFolderPaths implements ShouldQueue {
'summary' => $summary,
'progress' => 100,
'ended_at' => $endedAt,
- 'duration' => $duration
+ 'duration' => $duration,
]);
} catch (\Throwable $th) {
$endedAt = now();
$duration = (int) $this->startedAt->diffInSeconds($endedAt);
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' => $endedAt, 'duration' => $duration]);
+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::FAILED, 'summary' => 'Error: ' . $th->getMessage(), 'ended_at' => $endedAt, 'duration' => $duration]);
+ throw $th;
}
}
diff --git a/app/Jobs/CleanVideoPaths.php b/app/Jobs/CleanVideoPaths.php
index 65ec3963..5927ae1b 100644
--- a/app/Jobs/CleanVideoPaths.php
+++ b/app/Jobs/CleanVideoPaths.php
@@ -18,8 +18,11 @@ class CleanVideoPaths implements ShouldQueue {
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $taskId;
+
protected $subTaskId;
+
protected $startedAt;
+
/**
* Create a new job instance.
*/
@@ -37,6 +40,7 @@ class CleanVideoPaths implements ShouldQueue {
if ($this->batch() && $this->batch()->cancelled()) {
// Determine if the batch has been cancelled...
SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::CANCELLED, 'summary' => 'Parent Task was Cancelled']);
+
return;
}
@@ -54,13 +58,14 @@ class CleanVideoPaths implements ShouldQueue {
'summary' => $summary,
'progress' => 100,
'ended_at' => $endedAt,
- 'duration' => $duration
+ 'duration' => $duration,
]);
} catch (\Throwable $th) {
$endedAt = now();
$duration = (int) $this->startedAt->diffInSeconds($endedAt);
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' => $endedAt, 'duration' => $duration]);
+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::FAILED, 'summary' => 'Error: ' . $th->getMessage(), 'ended_at' => $endedAt, 'duration' => $duration]);
+ throw $th;
}
}
diff --git a/app/Jobs/EmbedUidInMetadata.php b/app/Jobs/EmbedUidInMetadata.php
index a5e7a8ee..7cc9787c 100644
--- a/app/Jobs/EmbedUidInMetadata.php
+++ b/app/Jobs/EmbedUidInMetadata.php
@@ -4,6 +4,7 @@ namespace App\Jobs;
use App\Enums\TaskStatus;
use App\Models\SubTask;
+use App\Models\Task;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -11,6 +12,7 @@ use Illuminate\Queue\Attributes\DeleteWhenMissingModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
@@ -19,11 +21,13 @@ class EmbedUidInMetadata implements ShouldQueue {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $filePath;
+
protected $uid;
protected $taskId;
protected $subTaskId;
protected $startedAt;
+
/**
* Create a new job instance.
*
@@ -35,18 +39,27 @@ class EmbedUidInMetadata implements ShouldQueue {
$subTask = SubTask::create(['task_id' => $taskId, 'status' => TaskStatus::PENDING, 'name' => 'Embed UID in video file']); //
-
- DB::table('tasks')
- ->where('id', $this->taskId)
- ->update([
- 'sub_tasks_pending' => DB::raw('sub_tasks_pending + 1'),
- 'sub_tasks_total' => DB::raw('sub_tasks_total + 1'),
- ]);
-
-
-
$this->taskId = $taskId;
$this->subTaskId = $subTask->id;
+
+ // Start a database transaction
+ DB::beginTransaction();
+
+ try {
+ // Decrement the sub_tasks_pending only if it's greater than zero
+ DB::table('tasks')
+ ->where('id', $taskId)
+ ->update([
+ 'sub_tasks_pending' => DB::raw('sub_tasks_pending + 1'),
+ 'sub_tasks_total' => DB::raw('sub_tasks_total + 1'),
+ ]);
+
+ // Commit the transaction
+ DB::commit();
+ } catch (\Exception $e) {
+ DB::rollBack();
+ throw $e;
+ }
}
/**
@@ -56,26 +69,55 @@ class EmbedUidInMetadata implements ShouldQueue {
*/
public function handle() {
$this->startedAt = now();
- DB::table('tasks')->where('id', $this->taskId)->decrement('sub_tasks_pending');
+
+ DB::beginTransaction();
+
+ try {
+ DB::table('tasks')
+ ->where('id', $this->taskId)
+ ->where('sub_tasks_pending', '>', 0)
+ ->decrement('sub_tasks_pending');
+
+ DB::commit();
+ } catch (\Exception $e) {
+ DB::rollBack();
+ Log::error($e);
+ }
+
SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::PROCESSING, 'started_at' => $this->startedAt, 'summary' => "Adding uuid to $this->filePath"]);
try {
$summary = $this->handleEmbed();
$endedAt = now();
$duration = (int) $this->startedAt->diffInSeconds($endedAt);
- DB::table('tasks')->where('id', $this->taskId)->increment('sub_tasks_complete');
+ // DB::table('tasks')->where('id', $this->taskId)->increment('sub_tasks_complete');
+ $task = Task::where('id', $this->taskId)->first();
+
+ if ($task) {
+ if ($task->sub_tasks_complete == $task->sub_tasks_total - 1) {
+ $task->update([
+ 'sub_tasks_complete' => DB::raw('sub_tasks_complete + 1'),
+ 'status' => TaskStatus::COMPLETED,
+ ]);
+ } else {
+ $task->increment('sub_tasks_complete');
+ }
+ }
+
SubTask::where('id', $this->subTaskId)->update([
'status' => TaskStatus::COMPLETED,
'summary' => $summary,
'progress' => 100,
'ended_at' => $endedAt,
- 'duration' => $duration
+ 'duration' => $duration,
]);
} catch (\Throwable $th) {
$endedAt = now();
$duration = (int) $this->startedAt->diffInSeconds($endedAt);
+ dump($th->getMessage());
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' => $endedAt, 'duration' => $duration]);
+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::FAILED, 'summary' => 'Error: ' . $th->getMessage(), 'ended_at' => $endedAt, 'duration' => $duration]);
+ throw $th;
}
}
@@ -91,7 +133,7 @@ class EmbedUidInMetadata implements ShouldQueue {
$tempFilePath = $this->filePath . '.tmp';
- $formatMap = ['mp4' => 'mp4', 'mkv' => 'matroska', 'mp3' => 'mp3'];
+ $formatMap = ['mp4' => 'mp4', 'mkv' => 'matroska', 'mp3' => 'mp3', 'ogg' => 'opus', 'flac' => 'flac'];
$format = $formatMap[$ext] ?? $ext;
$command = [
diff --git a/app/Jobs/IndexFiles.php b/app/Jobs/IndexFiles.php
index f1dc2c62..0b1ee074 100755
--- a/app/Jobs/IndexFiles.php
+++ b/app/Jobs/IndexFiles.php
@@ -19,6 +19,7 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Ramsey\Uuid\Uuid;
@@ -29,8 +30,11 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $taskId;
+
protected $subTaskId;
+
protected $startedAt;
+
/**
* Create a new job instance.
*/
@@ -47,6 +51,7 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
if ($this->batch()->cancelled()) {
// Determine if the batch has been cancelled...
SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::CANCELLED, 'summary' => 'Parent Task was Cancelled']);
+
return;
}
@@ -66,13 +71,14 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
'summary' => $summary,
'progress' => 100,
'ended_at' => $endedAt,
- 'duration' => $duration
+ 'duration' => $duration,
]);
} catch (\Throwable $th) {
$endedAt = now();
$duration = (int) $this->startedAt->diffInSeconds($endedAt);
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' => $endedAt, 'duration' => $duration]);
+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::FAILED, 'summary' => 'Error: ' . $th->getMessage(), 'ended_at' => $endedAt, 'duration' => $duration]);
+ throw $th;
}
}
@@ -84,7 +90,6 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$error = 'Invalid Directory: "media"';
throw new \Exception($error);
-
// dd(json_encode(['success' => false, 'result' => '', 'error' => $error], JSON_UNESCAPED_SLASHES));
}
@@ -123,13 +128,13 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$changeAction = $categoryChange['action'];
if ($changeAction === 'INSERT') {
- $dbOut .= "INSERT INTO [Categories] VALUES ($changeID, $changeName, $changeMediaContent );\n"; // insert
+ $dbOut .= "INSERT INTO [Categories] VALUES ($changeID, $changeName, $changeMediaContent );\n\n"; // insert
$transaction = $categoryChange;
unset($transaction['action']);
array_push($categoryTransactions, $transaction);
} else {
- $dbOut .= "DELETE FROM [Categories] WHERE [Categories].[ID] = {$changeID};\n";
+ $dbOut .= "DELETE FROM [Categories] WHERE [Categories].[ID] = {$changeID};\n\n";
array_push($categoryDeletions, $changeID);
}
}
@@ -142,13 +147,13 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$changeAction = $folderChange['action'];
if ($changeAction === 'INSERT') {
- $dbOut .= "INSERT INTO [Folders] VALUES ({$changeID}, {$changeName}, {$changePath}, {$changeCategoryID} );\n"; // insert
+ $dbOut .= "INSERT INTO [Folders] VALUES ({$changeID}, {$changeName}, {$changePath}, {$changeCategoryID} );\n\n"; // insert
$transaction = $folderChange;
unset($transaction['action']);
array_push($folderTransactions, $transaction);
} else {
- $dbOut .= "DELETE FROM [Folders] WHERE [Folder].[ID] = {$changeID};\n";
+ $dbOut .= "DELETE FROM [Folders] WHERE [Folder].[ID] = {$changeID};\n\n";
array_push($folderDeletions, $changeID);
}
}
@@ -157,7 +162,7 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$folderID = $seriesChange['folder_id'];
$compositeID = $seriesChange['composite_id'];
- $dbOut .= "INSERT INTO [series] VALUES ({$folderID}, {$compositeID});\n"; // insert
+ $dbOut .= "INSERT INTO [series] VALUES ({$folderID}, {$compositeID});\n\n"; // insert
array_push($seriesTransactions, $seriesChange);
}
@@ -172,13 +177,13 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$changeAction = $videoChange['action'];
if ($changeAction === 'INSERT') {
- $dbOut .= "INSERT INTO [Videos] VALUES ({$changeID}, {$changeUUID}, {$changeName}, {$changePath}, {$changeFolderID}, {$changeDate});\n"; // insert
+ $dbOut .= "INSERT INTO [Videos] VALUES ({$changeID}, {$changeUUID}, {$changeName}, {$changePath}, {$changeFolderID}, {$changeDate});\n\n"; // insert
$transaction = $videoChange;
unset($transaction['action']);
array_push($videoTransactions, $transaction);
} else {
- $dbOut .= "DELETE FROM [Videos] WHERE [Video].[ID] = {$changeID};\n";
+ $dbOut .= "DELETE FROM [Videos] WHERE [Video].[ID] = {$changeID};\n\n";
array_push($videoDeletions, $changeID);
}
}
@@ -191,7 +196,7 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$duration = $metadataChange['duration'];
$date_scanned = $metadataChange['date_scanned'];
- $dbOut .= "INSERT INTO [metadata] VALUES ({$videoID}, {$compositeID}, {$uuid}, {$file_size}, {$duration}, {$date_scanned});\n"; // insert
+ $dbOut .= "INSERT INTO [metadata] VALUES ({$videoID}, {$compositeID}, {$uuid}, {$file_size}, {$duration}, {$date_scanned});\n\n"; // insert
array_push($metadataTransactions, $metadataChange);
}
@@ -230,9 +235,10 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
Storage::put('dataCache.json', json_encode($dataCache, JSON_UNESCAPED_SLASHES));
// dump('Categories | Folders | Videos | Data | SQL | DataCache', $directories, $subDirectories, $files, $data, $dbOut, $dataCache);
dump('Categories | Folders | Videos | Changes | SQL ', $directories, ['count' => count($subDirectories['data']['folderStructure'])], ['count' => count($files['data']['videoStructure'])], $data, $dbOut);
+ return "Changed " . count($data['categories']) . " libraries, " . count($data['folders']) . " folders and " . count($data['videos']) . " Videos. \n\n$dbOut";
} catch (\Throwable $th) {
dump($th);
- throw new \Exception("Unable to index files, " . $th->getMessage());
+ throw new \Exception('Unable to index files, ' . $th->getMessage());
}
}
@@ -282,6 +288,7 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$data['next_ID'] = $currentID;
$data['categoryStructure'] = $current;
+ SubTask::where('id', $this->subTaskId)->update(['summary' => 'Generated ' . count($changes) . ' Library Changes', 'progress' => 10]);
return ['categoryChanges' => $changes, 'data' => $data];
}
@@ -359,6 +366,7 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$data['next_ID'] = $currentID;
$data['folderStructure'] = $current;
+ SubTask::where('id', $this->subTaskId)->update(['summary' => 'Generated ' . count($changes) . ' Folder Changes', 'progress' => 30]);
return ['folderChanges' => $changes, 'data' => $data, 'cost' => $cost, 'seriesChanges' => $seriesChanges];
}
@@ -425,7 +433,7 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$absolutePath = str_replace('\\', '/', Storage::disk('public')->path('')) . $file;
$ext = pathinfo($file, PATHINFO_EXTENSION);
- if (strtolower($ext) !== 'mp4' && strtolower($ext) !== 'mkv' && strtolower($ext) !== 'mp3') {
+ if (strtolower($ext) !== 'mp4' && strtolower($ext) !== 'mkv' && strtolower($ext) !== 'mp3' && strtolower($ext) !== 'ogg' && strtolower($ext) !== 'flac') { //&& strtolower($ext) !== 'ogg' && strtolower($ext) !== 'flac' the conversion breaks ogg idk about flac
continue;
}
@@ -448,8 +456,10 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$current[$key] = $stored[$key]; // add to current
unset($stored[$key]); // remove from stored
} else {
+ $mime_type = File::mimeType($absolutePath) ?? null;
+
$generated = ['id' => $currentID, 'uuid' => $uuid, 'name' => $cleanName, 'path' => $key, 'folder_id' => $folderStructure[$folder]['id'], 'date' => date('Y-m-d h:i A', filemtime($rawFile)), 'action' => 'INSERT'];
- $metadata = ['video_id' => $currentID, 'composite_id' => "$folder/$name", 'uuid' => $uuid, 'file_size' => filesize($rawFile), 'duration' => isset($fileMetaData['duration']) ? $fileMetaData['duration'] : null, 'date_scanned' => date('Y-m-d h:i:s A')];
+ $metadata = ['video_id' => $currentID, 'composite_id' => "$folder/$name", 'uuid' => $uuid, 'file_size' => filesize($rawFile), 'duration' => isset($fileMetaData['format']['duration']) ? (int) $fileMetaData['format']['duration'] : null, 'mime_type' => $mime_type ?? null, 'date_scanned' => date('Y-m-d h:i:s A')];
$current[$key] = $currentID; // add to current
array_push($changes, $generated); // add to new (insert)
array_push($metadataChanges, $metadata); // create metadata (insert)
@@ -476,9 +486,11 @@ class IndexFiles implements ShouldBeUnique, ShouldQueue {
$data['next_ID'] = $currentID;
$data['videoStructure'] = $current;
+ SubTask::where('id', $this->subTaskId)->update(['summary' => 'Generated ' . count($changes) . ' Video Changes', 'progress' => 80]);
return ['videoChanges' => $changes, 'data' => $data, 'cost' => $cost, 'updatedFolderStructure' => $foldersCopy, 'metadataChanges' => $metadataChanges];
}
+ // Not Using
private function getUidFromMetadata($filePath) {
$command = [
'ffprobe',
diff --git a/app/Jobs/ScheduledIndexFiles.php b/app/Jobs/ScheduledIndexFiles.php
index 6165b373..2e8af036 100644
--- a/app/Jobs/ScheduledIndexFiles.php
+++ b/app/Jobs/ScheduledIndexFiles.php
@@ -29,8 +29,8 @@ class ScheduledIndexFiles implements ShouldQueue {
}
public function handleTask() {
- $name = "Scheduled Index Files";
- $description = "Looks for folder and video changes in in all Libraries.";
+ $name = 'Scheduled Index Files';
+ $description = 'Looks for folder and video changes in in all Libraries.';
try {
$task = DirectoryController::setupTask(null, $name, $description, 2);
$chain = [
@@ -42,7 +42,9 @@ class ScheduledIndexFiles implements ShouldQueue {
$task->update(['batch_id' => $batch->id]);
// return response()->json(['task_id' => $task->id, 'message' => 'Scheduled Task "INDEX FILES" was started.']);
} catch (\Throwable $th) {
- if ($task) $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now(), 'summary' => $th->getMessage()]);
+ if ($task) {
+ $task->update(['status' => TaskStatus::FAILED, 'ended_at' => now(), 'summary' => $th->getMessage()]);
+ }
Log::error($th->getMessage());
// return response()->json(['error' => 'Error cannot index files', 'details' => $th->getMessage()], 500);
}
diff --git a/app/Jobs/SyncFiles.php b/app/Jobs/SyncFiles.php
index 334128c2..10ce3ab7 100755
--- a/app/Jobs/SyncFiles.php
+++ b/app/Jobs/SyncFiles.php
@@ -21,8 +21,11 @@ class SyncFiles implements ShouldBeUnique, ShouldQueue {
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $taskId;
+
protected $subTaskId;
+
protected $startedAt;
+
/**
* Create a new job instance.
*/
@@ -40,6 +43,7 @@ class SyncFiles implements ShouldBeUnique, ShouldQueue {
if ($this->batch() && $this->batch()->cancelled()) {
// Determine if the batch has been cancelled...
SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::CANCELLED, 'summary' => 'Parent Task was Cancelled']);
+
return;
}
@@ -57,8 +61,8 @@ class SyncFiles implements ShouldBeUnique, ShouldQueue {
$endedAt = now();
$duration = (int) $this->startedAt->diffInSeconds($endedAt);
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' => $endedAt, 'duration' => $duration]);
- //throw $th;
+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::FAILED, 'summary' => 'Error: ' . $th->getMessage(), 'ended_at' => $endedAt, 'duration' => $duration]);
+ throw $th;
}
}
diff --git a/app/Jobs/VerifyFiles.php b/app/Jobs/VerifyFiles.php
index b41b92a0..1d50dbc1 100755
--- a/app/Jobs/VerifyFiles.php
+++ b/app/Jobs/VerifyFiles.php
@@ -6,7 +6,6 @@ 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;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -15,6 +14,7 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
+use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Ramsey\Uuid\Uuid;
@@ -25,8 +25,11 @@ class VerifyFiles implements ShouldQueue {
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $taskId;
+
protected $subTaskId;
+
protected $startedAt;
+
/**
* Create a new job instance.
*/
@@ -60,6 +63,7 @@ class VerifyFiles implements ShouldQueue {
if ($this->batch()->cancelled()) {
// Determine if the batch has been cancelled...
SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::CANCELLED, 'summary' => 'Parent Task was Cancelled']);
+
return;
}
@@ -77,26 +81,28 @@ class VerifyFiles implements ShouldQueue {
'summary' => $summary,
'progress' => 100,
'ended_at' => $endedAt,
- 'duration' => $duration
+ 'duration' => $duration,
]);
} catch (\Throwable $th) {
$endedAt = now();
$duration = (int) $this->startedAt->diffInSeconds($endedAt);
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' => $endedAt, 'duration' => $duration]);
+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::FAILED, 'summary' => 'Error: ' . $th->getMessage(), 'ended_at' => $endedAt, 'duration' => $duration]);
+ throw $th;
}
}
private function verifyFiles() {
$transactions = [];
$error = false;
+ $index = 0;
if (count($this->videos) == 0) {
throw new \Exception('Video Data Lost');
}
try {
- foreach ($this->videos as $index => $video) {
+ foreach ($this->videos as $video) {
$stored = []; // Metadata from db
$changes = []; // Changes -> stored + changes . length has to be the same for every video so must generate defaults
@@ -138,34 +144,46 @@ class VerifyFiles implements ShouldQueue {
$changes['file_size'] = filesize($filePath);
}
+ if (is_null($metadata->mime_type)) {
+ $changes['mime_type'] = File::mimeType($filePath) ?? null;
+ }
+
+ $mime_type = isset($changes['mime_type']) ? $changes['mime_type'] : $metadata->mime_type;
+
+ $audioMetadata = (is_null($metadata->description) || (is_null($metadata->episode) && is_null($metadata->season))) && str_starts_with($mime_type, 'audio') ? $this->getAudioDescription($filePath, $fileMetaData ?? null) : [];
+
+ if (is_null($metadata->poster_url) && $mime_type && str_starts_with($mime_type, 'audio')) {
+ $relativePath = $video->folder->path . '/' . $metadata->id;
+ $coverArtPath = "posters/audio/$relativePath-$uuid.png";
+
+ $coverArtUrl = $this->checkAlbumArt($filePath, $coverArtPath);
+ if ($coverArtUrl) {
+ $changes['poster_url'] = $coverArtUrl;
+ }
+ }
+
preg_match('![sS][0-9]+!', $video->name, $seasonRaw);
preg_match('![eE][0-9]+!', $video->name, $episodeRaw);
preg_match('![0-9]+!', $seasonRaw[0] ?? '', $season);
preg_match('![0-9]+!', $episodeRaw[0] ?? '', $episode);
if (is_null($metadata->duration)) {
- // dump(str_replace('\\', '/', Storage::disk('public')->path('')) . substr($video->path, 8));
if (! isset($fileMetaData['duration'])) {
$fileMetaData = $this->getFileMetadata($filePath);
}
- // $ffprobe = FFMpegFFProbe::create();
- // $duration = floor($ffprobe
- // ->format($filePath) // extracts file information
- // ->get('duration'));
-
$duration = isset($fileMetaData['duration']) ? floor($fileMetaData['duration']) : null;
$changes['duration'] = $duration;
}
if (is_null($metadata->episode)) {
- $changes['episode'] = count($episode) == 1 ? (int) $episode[0] : null;
+ $changes['episode'] = count($episode) == 1 ? (int) $episode[0] : $audioMetadata['episode'] ?? null;
}
if (is_null($metadata->season)) {
- $changes['season'] = count($season) == 1 ? (int) $season[0] : null;
+ $changes['season'] = count($season) == 1 ? (int) $season[0] : $audioMetadata['season'] ?? null;
}
- if (is_null($metadata->title)) {
+ if (is_null($metadata->title) && !str_starts_with($mime_type, 'audio')) {
$newTitle = count($season) == 1 ? 'S' . $season[0] : '';
$newTitle .= count($episode) == 1 ? 'E' . $episode[0] : '';
@@ -176,10 +194,6 @@ class VerifyFiles implements ShouldQueue {
}
}
- if (is_null($metadata->description)) {
- $changes['description'] = $video->description ?? null;
- }
-
if (is_null($metadata->date_released)) {
$changes['date_released'] = null;
}
@@ -188,8 +202,8 @@ class VerifyFiles implements ShouldQueue {
$changes['editor_id'] = null;
}
- if (is_null($metadata->mime_type)) {
- $changes['mime_type'] = File::mimeType($filePath) ?? 'feee';
+ if (is_null($metadata->description)) {
+ $changes['description'] = $audioMetadata['description'] ?? $video->description ?? null;
}
is_null($metadata->view_count) ? $changes['view_count'] = Record::where('video_id', $video->id)->count() + ($metadata->id ? Record::where('metadata_id', $metadata->id)->count() : 0) : $stored['view_count'] = $metadata->view_count;
@@ -203,7 +217,8 @@ class VerifyFiles implements ShouldQueue {
// dump($changes);
// dump($video->name);
}
- SubTask::where('id', $this->subTaskId)->update(['progress' => (int) (($index + 1) / count($this->videos) * 100)]);
+ $index += 1;
+ SubTask::where('id', $this->subTaskId)->update(['progress' => (int) (($index / count($this->videos)) * 100)]);
// dump($metadata->toArray());
}
@@ -224,7 +239,7 @@ class VerifyFiles implements ShouldQueue {
return 'No Changes Found';
}
- Metadata::upsert($transactions, 'id', ['video_id', 'title', 'description', 'duration', 'season', 'episode', 'view_count', 'uuid', 'file_size', 'mime_type', 'date_scanned']);
+ Metadata::upsert($transactions, 'id', ['video_id', 'title', 'description', 'duration', 'season', 'episode', 'view_count', 'uuid', 'file_size', 'mime_type', 'poster_url', 'date_scanned']);
$summary = 'Updated ' . count($transactions) . ' videos from id ' . ($transactions[0]['video_id']) . ' to ' . ($transactions[count($transactions) - 1]['video_id']);
dump($summary);
@@ -235,7 +250,7 @@ class VerifyFiles implements ShouldQueue {
return $transaction['id'];
}, $transactions);
- $errorMessage = 'Error cannot insert verified file metadata ' . $th->getMessage() . ' Cancelling ' . count($transactions) . ' updates with IDs ' . json_encode($ids); // . [...$ids]);
+ $errorMessage = 'Error cannot insert verified file metadata ' . $th->getMessage() . ' Cancelling ' . count($transactions) . ' updates with IDs ' . json_encode($ids); // . [...$ids]);
dump($errorMessage);
throw new \Exception($errorMessage);
@@ -277,4 +292,84 @@ class VerifyFiles implements ShouldQueue {
return ['tags' => []];
}
}
+
+ private function getAudioDescription($filePath, $metadata) {
+ if (is_null($metadata) || count($metadata) == 0) {
+ $metadata = $this->getFileMetadata($filePath);
+ }
+
+
+ $description = $metadata['tags']['artist'] ?? '';
+ $description = ($description ? ($description . ' - ') : '') . ($metadata['tags']['album'] ?? '');
+ $season = $metadata['tags']['disc'] ?? null;
+ $episode = $metadata['tags']['track'] ?? null;
+ return ['description' => $description === '' ? null : $description, 'season' => $season, 'episode' => $episode];
+ }
+
+
+ private function getPathUrl($path) {
+ /**
+ * @disregard P1013 Undefined method but it actually exists
+ */
+ return Storage::disk('public')->url($path);
+ }
+
+ private function checkAlbumArt($filePath, $coverArtPath) {
+ if (Storage::disk('public')->exists($coverArtPath)) {
+ return $this->getPathUrl($coverArtPath);
+ } else {
+ $coverGenerated = $this->extractAlbumArt($filePath, $coverArtPath);
+ if ($coverGenerated) {
+ Storage::disk('public')->put($coverArtPath, $coverGenerated);
+ return $this->getPathUrl($coverArtPath);
+ }
+ }
+ return null;
+ }
+
+
+
+ private function extractAlbumArt($filePath, $outputPath) {
+ try {
+ //code...'ffmpeg',
+ $tempPath = sys_get_temp_dir() . '/' . basename($outputPath);
+ $command = [
+ 'ffmpeg',
+ '-i',
+ $filePath,
+ '-an',
+ '-vcodec',
+ 'copy',
+ $tempPath,
+ ];
+
+ $process = new Process($command);
+ $process->run();
+
+ if (! $process->isSuccessful()) {
+ $errorOutput = $process->getErrorOutput(); // Checks if error is caused by missing album art (never set so dont log)
+ if (strpos($errorOutput, 'Output file does not contain any stream') !== false) {
+ return false;
+ }
+
+ throw new ProcessFailedException($process);
+ }
+
+ if (! file_exists($tempPath) || filesize($tempPath) == 0) {
+ unlink($tempPath);
+
+ return false;
+ }
+
+ $coverArtContent = file_get_contents($tempPath);
+ unlink($tempPath);
+
+ return $coverArtContent;
+ } catch (\Throwable $th) {
+ dump($th->getMessage());
+ Log::error($th);
+
+ return false;
+ }
+ }
}
diff --git a/app/Jobs/VerifyFolders.php b/app/Jobs/VerifyFolders.php
index d31ade41..6d892bac 100644
--- a/app/Jobs/VerifyFolders.php
+++ b/app/Jobs/VerifyFolders.php
@@ -18,7 +18,9 @@ class VerifyFolders implements ShouldQueue {
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $taskId;
+
protected $subTaskId;
+
protected $startedAt;
/**
@@ -37,6 +39,7 @@ class VerifyFolders implements ShouldQueue {
if ($this->batch()->cancelled()) {
// Determine if the batch has been cancelled...
SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::CANCELLED, 'summary' => 'Parent Task was Cancelled']);
+
return;
}
@@ -54,13 +57,14 @@ class VerifyFolders implements ShouldQueue {
'summary' => $summary,
'progress' => 100,
'ended_at' => $endedAt,
- 'duration' => $duration
+ 'duration' => $duration,
]);
} catch (\Throwable $th) {
$endedAt = now();
$duration = (int) $this->startedAt->diffInSeconds($endedAt);
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' => $endedAt, 'duration' => $duration]);
+ SubTask::where('id', $this->subTaskId)->update(['status' => TaskStatus::FAILED, 'summary' => 'Error: ' . $th->getMessage(), 'ended_at' => $endedAt, 'duration' => $duration]);
+ throw $th;
}
}
@@ -71,8 +75,9 @@ class VerifyFolders implements ShouldQueue {
$transactions = [];
$error = false;
+ $index = 0;
- foreach ($this->folders as $index => $folder) {
+ foreach ($this->folders as $folder) {
try {
$stored = [];
$changes = [];
@@ -96,7 +101,8 @@ class VerifyFolders implements ShouldQueue {
// dump($folder->name);
}
- SubTask::where('id', $this->subTaskId)->update(['progress' => (int) (($index + 1) / count($this->folders)) * 100]);
+ $index += 1;
+ SubTask::where('id', $this->subTaskId)->update(['progress' => (int) (($index / count($this->folders)) * 100)]);
// dump($series->toArray());
} catch (\Throwable $th) {
diff --git a/app/Models/SubTask.php b/app/Models/SubTask.php
index bcc2cbcd..1a1b65f5 100644
--- a/app/Models/SubTask.php
+++ b/app/Models/SubTask.php
@@ -2,9 +2,8 @@
namespace App\Models;
-use Illuminate\Database\Eloquent\Model;
use App\Enums\TaskStatus;
-use Illuminate\Support\Facades\Log;
+use Illuminate\Database\Eloquent\Model;
class SubTask extends Model {
protected $fillable = [
@@ -31,10 +30,10 @@ class SubTask extends Model {
}
public function updateDuration() {
-
- if (!isset($this->started_at)) {
+ if (! isset($this->started_at)) {
$this->duration = 0;
$this->save;
+
return;
}
diff --git a/app/Models/Task.php b/app/Models/Task.php
index 619c7a71..02a993ab 100644
--- a/app/Models/Task.php
+++ b/app/Models/Task.php
@@ -2,8 +2,8 @@
namespace App\Models;
-use Illuminate\Database\Eloquent\Model;
use App\Enums\TaskStatus;
+use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Task extends Model {
@@ -27,7 +27,6 @@ class Task extends Model {
'status' => TaskStatus::class,
];
-
// Boot method to register model events
protected static function boot() {
parent::boot();
diff --git a/composer.json b/composer.json
index 38968c46..69ceab95 100755
--- a/composer.json
+++ b/composer.json
@@ -60,7 +60,8 @@
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
- "dev": "npx concurrently -c \"#93c5fd,#c4b5fd,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"npm run dev\" --names='server,queue,vite'"
+ "dev": "npx concurrently -c \"#93c5fd,#c4b5fd,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"npm run dev\" --names='server,queue,vite'",
+ "pint": "@php ./vendor/bin/pint"
},
"extra": {
"laravel": {
diff --git a/package.json b/package.json
index 992d6b67..798bb10a 100755
--- a/package.json
+++ b/package.json
@@ -12,13 +12,14 @@
"vite:dev2": "concurrently -k -p \"[{name}]\" -c \"blue.bold,green.bold,red.bold\" \"npm:php:serve\" \"npm:php:pail\" \"npm:dev\"",
"vite:cron": "concurrently -k -p \"[{name}]\" -c \"blue.bold,green.bold,red.bold,white.bold\" \"npm:php:queue\" \"npm:php:scheduler\" \"npm:dev\" \"npm:php:pulse\"",
"vite:php": "concurrently -k -p \"[{name}]\" -c \"blue.bold,green.bold,white.bold\" \"npm:php:queue\" \"npm:php:scheduler\" \"npm:php:pulse\"",
- "build": "npm run type-check && npm run build-only",
+ "build": "npm run pint && npm run type-check && npm run build-only",
"build-only": "vite build",
"type-check": "vue-tsc --build",
"lint": "eslint . --fix",
"lintold": "eslint ./resources/js --ext .js,.vue --ignore-path .gitignore --fix src",
"format": "prettier --write \"{resources/js/**/*.{js,ts,vue,json},*.{json,js,ts,md,php}}\"",
- "typegen": "laravel-typegen"
+ "typegen": "laravel-typegen",
+ "pint": "php ./vendor/bin/pint"
},
"devDependencies": {
"@7nohe/laravel-typegen": "^0.6.1",
diff --git a/resources/js/components/cards/CategoryCard.vue b/resources/js/components/cards/CategoryCard.vue
index 23e9421a..c8b749ff 100644
--- a/resources/js/components/cards/CategoryCard.vue
+++ b/resources/js/components/cards/CategoryCard.vue
@@ -8,18 +8,17 @@ import { useQueryClient } from '@tanstack/vue-query';
import { updateCategory } from '@/service/mediaAPI.ts';
import { toast } from '@/service/toaster/toastService';
-import Popover from '@/components/pinesUI/Popover.vue';
-import ButtonText from '@/components/inputs/ButtonText.vue';
import FormInputLabel from '@/components/labels/FormInputLabel.vue';
import InputSelect from '@/components/pinesUI/InputSelect.vue';
+import ButtonIcon from '@/components/inputs/ButtonIcon.vue';
+import ButtonText from '@/components/inputs/ButtonText.vue';
+import Popover from '@/components/pinesUI/Popover.vue';
import ProiconsMoreVertical from '~icons/proicons/more-vertical';
import ProiconsArrowSync from '~icons/proicons/arrow-sync';
import ProiconsDelete from '~icons/proicons/delete';
import ProiconsLock from '~icons/proicons/lock';
-import CircumEdit from '~icons/circum/edit';
import CircumShare1 from '~icons/circum/share-1';
-import ButtonIcon from '../inputs/ButtonIcon.vue';
const props = defineProps<{ data?: CategoryResource }>();
const defaultFolder = ref<FolderResource>();
@@ -69,9 +68,7 @@ watch(
() => {
if (!props.data?.folders || props.data.folders.length < 1) return;
- defaultFolder.value = props.data.default_folder_id
- ? props.data.folders.find((folder) => folder.id === props.data?.default_folder_id)
- : props.data.folders[0];
+ defaultFolder.value = props.data.default_folder_id ? props.data.folders.find((folder) => folder.id === props.data?.default_folder_id) : props.data.folders[0];
},
{ immediate: true },
);
@@ -92,7 +89,7 @@ watch(
</RouterLink>
<section class="flex flex-1 h-full flex-col p-4 gap-2">
<div class="flex items-start justify-between flex-wrap">
- <h3 class="capitalize text-lg group-hover:text-purple-600">
+ <h3 class="capitalize group-hover:text-purple-600">
{{ data?.name }}
</h3>
<span class="flex flex-wrap gap-2 [&>*]:h-6 text-sm">
@@ -133,19 +130,11 @@ watch(
"
/>
</div>
- <ButtonText
- class="h-8 dark:!bg-neutral-950"
- :title="'Scan for Folder Changes'"
- @click="handleStartScan"
- >
+ <ButtonText class="h-8 dark:!bg-neutral-950" :title="'Scan for Folder Changes'" @click="handleStartScan">
<template #text> Scan Folders </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'"
- disabled
- >
+ <ButtonText class="h-8 dark:!bg-neutral-950 disabled:opacity-60" :title="'Set User Access Permissions'" disabled>
<template #text> Manage Access </template>
<template #icon> <ProiconsLock class="h-4 w-4" /></template>
</ButtonText>
diff --git a/resources/js/components/cards/HoverCard.vue b/resources/js/components/cards/HoverCard.vue
index b36ad809..e9749fd1 100644
--- a/resources/js/components/cards/HoverCard.vue
+++ b/resources/js/components/cards/HoverCard.vue
@@ -69,11 +69,11 @@ const updateTooltipPosition = (event: MouseEvent) => {
@mouseleave="hoverCardLeave"
v-show="hoverCardHovered"
v-cloak
- :class="`flex ${positionClasses} absolute overflow-auto transition-opacity ease-in-out duration-200 md:max-w-xl text-sm p-3 h-fit 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`"
+ :class="`flex ${positionClasses} absolute overflow-auto transition-opacity ease-in-out duration-200 md:max-w-xl xl:max-w-3xl text-sm p-3 h-fit 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`"
:style="tooltipStyles"
>
<slot name="icon">
- <ProiconsCommentExclamation class="h-4 w-4 shrink-0" />
+ <ProiconsCommentExclamation class="h-5 w-5 mb-auto shrink-0" />
</slot>
<slot name="content">
<p class="text-pretty h-fit w-full break-words whitespace-pre-wrap">
diff --git a/resources/js/components/cards/RecordCardDetails.vue b/resources/js/components/cards/RecordCardDetails.vue
index e06cebae..747d4556 100755
--- a/resources/js/components/cards/RecordCardDetails.vue
+++ b/resources/js/components/cards/RecordCardDetails.vue
@@ -14,8 +14,7 @@ const rawDate = new Date((props.data?.attributes.created_at ?? '').replace(' ',
const timeSpan = toTimeSpan(rawDate);
const videoLink = computed(() => {
- if (!props.data.relationships.video_id || !props.data.relationships.category?.name || !props.data.relationships.folder?.name)
- return false;
+ if (!props.data.relationships.video_id || !props.data.relationships.category?.name || !props.data.relationships.folder?.name) return false;
return `/${encodeURIComponent(props.data.relationships?.category?.name ?? '')}/${encodeURIComponent(props.data.relationships.folder?.name ?? '')}?video=${props.data.relationships.video_id}`;
});
</script>
@@ -26,7 +25,7 @@ const videoLink = computed(() => {
class="text-left relative flex flex-col gap-4 sm:flex-row flex-wrap 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 p-3 w-full group cursor-pointer divide-gray-300 dark:divide-neutral-400"
>
<section class="flex justify-between gap-4 w-full">
- <h2 class="text-xl w-full truncate" :title="props.data.relationships.file_name">
+ <h2 class="w-full truncate" :title="props.data.relationships.file_name">
{{ props.data.relationships.video_name }}
</h2>
<div class="flex justify-end gap-1">
@@ -51,7 +50,7 @@ const videoLink = computed(() => {
/>
</div>
</section>
- <section class="flex flex-col sm:flex-row sm:justify-between w-full text-neutral-500 dark:text-neutral-400">
+ <section class="flex flex-col sm:flex-row sm:justify-between w-full text-neutral-500 dark:text-neutral-400 text-sm">
<h3
class="w-full text-wrap truncate sm:text-nowrap"
:title="`Watched on ${rawDate.toLocaleDateString('en-ca', {
diff --git a/resources/js/components/cards/SubTaskCard.vue b/resources/js/components/cards/SubTaskCard.vue
index d3a9b449..9aca6263 100644
--- a/resources/js/components/cards/SubTaskCard.vue
+++ b/resources/js/components/cards/SubTaskCard.vue
@@ -12,6 +12,7 @@ import ProiconsDelete from '~icons/proicons/delete';
import ProiconsArrowReply from '~icons/proicons/arrow-reply';
const props = defineProps<{ data: SubTaskResource; isScreenLarge?: boolean }>();
+const emit = defineEmits(['clickAction']);
</script>
<template>
@@ -22,8 +23,8 @@ const props = defineProps<{ data: SubTaskResource; isScreenLarge?: boolean }>();
<div class="relative group flex flex-col gap-1 flex-1">
<HoverCard :content="data.summary ?? ''" class="flex gap-x-4 gap-y-2 items-center">
<template #trigger>
- <h2 class="truncate capitalize group" :title="data.name">{{ data.name }}</h2>
- <p v-if="data.summary" class="truncate text-neutral-500 dark:text-neutral-400 max-w-64 hidden md:block">
+ <h2 class="truncate capitalize group" :title="data.name">{{ data.id }} - {{ data.name }}</h2>
+ <p v-if="data.summary" class="truncate text-neutral-500 dark:text-neutral-400 max-w-48 lg:max-w-20 xl:max-w-64 hidden md:block">
{{ data.summary }}
</p>
</template>
@@ -45,10 +46,7 @@ const props = defineProps<{ data: SubTaskResource; isScreenLarge?: boolean }>();
: `Created: ${toFormattedDate(new Date(data.created_at), true, within24Hrs(data.created_at) ? { hour: '2-digit', minute: '2-digit' } : undefined)}`
}}
</h4>
- <h4
- class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize w-20 hidden sm:block"
- title="Duration"
- >
+ <h4 class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize w-20 hidden sm:block" title="Duration">
Duration: {{ toFormattedDuration(data.duration, false) }}
</h4>
</div>
@@ -114,11 +112,12 @@ const props = defineProps<{ data: SubTaskResource; isScreenLarge?: boolean }>();
:label="data.status"
/>
<ButtonCorner
- disabled
+ :disabled="data.status === 'pending' || data.status === 'processing'"
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"
+ @click="$emit('clickAction', 'subTask')"
>
<template #text> Remove </template>
<template #icon> <ProiconsDelete class="h-4 w-4" /></template>
diff --git a/resources/js/components/cards/TaskCard.vue b/resources/js/components/cards/TaskCard.vue
index 0533b151..9f992932 100644
--- a/resources/js/components/cards/TaskCard.vue
+++ b/resources/js/components/cards/TaskCard.vue
@@ -34,18 +34,8 @@ const progress = computed(() => {
if (!props.data.id || !props.data.sub_tasks_total) return { complete: 0, processing: 0, failed: 0, pending: 100 };
let complete = roundDown(props.data.sub_tasks_complete / props.data.sub_tasks_total);
let failed = roundDown(props.data.sub_tasks_failed / props.data.sub_tasks_total);
- let pending = Math.ceil(
- (Math.max(props.data.sub_tasks_total - props.data.sub_tasks_complete - props.data.sub_tasks_failed, 0) /
- props.data.sub_tasks_total) *
- 100,
- );
+ let pending = Math.ceil((Math.max(props.data.sub_tasks_total - props.data.sub_tasks_complete - props.data.sub_tasks_failed, 0) / props.data.sub_tasks_total) * 100);
let processing = Math.max(100 - complete - failed - pending, 0);
- console.log(props.data, {
- complete,
- processing,
- failed,
- pending,
- });
return {
complete,
@@ -68,9 +58,9 @@ const loadSubTasks = async () => {
subTasksFetched.value = true;
};
-const handleClick = (cancel: boolean = false) => {
+const handleClick = (type: '' | 'cancel' | 'subTask' = '') => {
popover.value?.handleClose();
- emit('clickAction', true);
+ emit('clickAction', type);
};
watch(
@@ -130,33 +120,20 @@ watch(
: `Created: ${toFormattedDate(new Date(data.created_at), true, within24Hrs(data.created_at) ? { hour: '2-digit', minute: '2-digit' } : undefined)}`
}}
</h4>
- <h4 class="text-xs text-neutral-500 dark:text-neutral-400 truncate capitalize md:ml-auto" title="Time">
- Duration:
- </h4>
+ <h4 class="text-xs text-neutral-500 dark:text-neutral-400 truncate capitalize md:ml-auto" title="Time">Duration:</h4>
<h4 class="text-xs text-neutral-500 dark:text-neutral-400 capitalize md:me-auto" title="Time">
{{ toFormattedDuration(data.duration, false) }}
</h4>
</span>
<span :class="`grid xs:grid-cols-2 col-span-3 md:col-span-2 gap-x-4`">
- <h4
- class="text-xs text-neutral-500 dark:text-neutral-400 truncate line-clamp-1 capitalize w-20"
- title="Pending Tasks"
- >
+ <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"
- >
+ <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"
- >
+ <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>
@@ -200,10 +177,7 @@ watch(
{{ Math.ceil((Math.max(data.sub_tasks_complete, 0) / (data.sub_tasks_total ? data.sub_tasks_total : 1)) * 100) }}%
</p>
<div class="px-2 text-xs hidden sm:flex flex-col gap-1 h-fit min-w-32 flex-1">
- <p class="w-full text-left">
- {{ Math.ceil((Math.max(data.sub_tasks_complete, 0) / (data.sub_tasks_total ? data.sub_tasks_total : 1)) * 100) }}%
- Processed
- </p>
+ <p class="w-full text-left">{{ Math.ceil((Math.max(data.sub_tasks_complete, 0) / (data.sub_tasks_total ? data.sub_tasks_total : 1)) * 100) }}% Processed</p>
<div class="h-1 w-full bg-primary-dark-900 flex overflow-clip rounded-full">
<div
:class="`${data.sub_tasks_failed + data.sub_tasks_pending == 0 ? 'rounded-full' : 'rounded-l-full'} bg-purple-600`"
@@ -266,7 +240,7 @@ watch(
<ButtonText
v-if="data.status_key >= 0 && data.status_key <= 1"
class="h-8 text-rose-600 dark:!bg-rose-700 disabled:opacity-60"
- @click.stop.prevent="handleClick(true)"
+ @click.stop.prevent="handleClick('cancel')"
:title="'Cancel Task'"
>
<template #text> Cancel </template>
@@ -275,7 +249,7 @@ watch(
<ButtonText
v-else
class="h-8 text-rose-600 dark:!bg-rose-700 disabled:opacity-60"
- @click.stop.prevent="handleClick"
+ @click.stop.prevent="handleClick()"
:title="'Remove Task\'s Record From Server'"
>
<template #text> Remove </template>
@@ -304,7 +278,7 @@ watch(
>
<div
v-if="(subTasks.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"
+ 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-2"
>
{{ 'No Sub Tasks Found' }}
</div>
@@ -314,6 +288,7 @@ watch(
:key="subTask.id"
:data="subTask"
:isScreenSmall="isScreenLarge"
+ @click-action="$emit('clickAction', 'subTask', subTask.id)"
/>
<TableBase
v-else
@@ -327,6 +302,11 @@ watch(
:table-styles="'gap-4 xs:gap-2'"
:use-toolbar="false"
:items-per-page="8"
+ :clickAction="
+ (id: number) => {
+ $emit('clickAction', 'subTask', id);
+ }
+ "
/>
</section>
</div>
diff --git a/resources/js/components/cards/VideoCard.vue b/resources/js/components/cards/VideoCard.vue
index b4de708d..9095d70f 100755
--- a/resources/js/components/cards/VideoCard.vue
+++ b/resources/js/components/cards/VideoCard.vue
@@ -23,7 +23,7 @@ const handlePropsUpdate = () => {
metaData.updateData({ ...props.data, id: props.data.id, skipBaseURL: true });
};
-watch(props, handlePropsUpdate, { immediate: true });
+watch(props, handlePropsUpdate, { immediate: true, deep: true });
// @click.left.stop.prevent.capture="handlePlay"
</script>
@@ -35,22 +35,20 @@ watch(props, handlePropsUpdate, { immediate: true });
:data-id="props.data?.id"
:data-path="`../${props.data?.path}`"
>
- <section class="flex justify-between gap-4 w-full items-start overflow-hidden" :title="metaData?.fields?.description">
+ <section class="flex justify-between gap-4 w-full items-center overflow-hidden" :title="metaData?.fields?.description">
<h3 class="w-full line-clamp-1 flex gap-8 items-end min-w-fit max-w-[30%]">
{{ metaData?.fields?.title }}
<!-- <span class="text-ellipsis text-wrap line-clamp-1 text-sm sm:text-base text-neutral-500 dark:text-neutral-400">{{
metaData?.fields?.description
}}</span> -->
</h3>
- <h4 class="text-ellipsis text-wrap line-clamp-1 text-neutral-500 dark:text-neutral-400">
+ <h4 class="text-ellipsis text-wrap line-clamp-1 text-neutral-500 dark:text-neutral-400 text-sm">
{{ metaData?.fields?.duration }}
</h4>
</section>
- <section
- class="flex justify-between gap-4 w-full items-start text-sm sm:text-base sm:w-auto text-neutral-500 dark:text-neutral-400"
- >
+ <section class="flex justify-between gap-4 w-full items-start text-sm sm:w-auto text-neutral-500 dark:text-neutral-400">
<span class="flex gap-2 items-center w-full flex-1">
- <h4 class="text-sm sm:text-base text-nowrap text-start truncate">
+ <h4 class="text-nowrap text-start truncate">
{{ metaData?.fields?.views }}
</h4>
diff --git a/resources/js/components/dashboard/DashboardAnalytics.vue b/resources/js/components/dashboard/DashboardAnalytics.vue
index a4124cb7..28a08e3f 100644
--- a/resources/js/components/dashboard/DashboardAnalytics.vue
+++ b/resources/js/components/dashboard/DashboardAnalytics.vue
@@ -2,8 +2,9 @@
import type { PulseResponse } from '@/types/types';
import { useGetPulse, useGetSiteAnalytics } from '@/service/queries';
+import { ref, useTemplateRef, watch } from 'vue';
+import { handleStartTask } from '@/service/taskService';
import { periodForHumans } from '@/service/util';
-import { ref, watch } from 'vue';
import { toast } from '@/service/toaster/toastService';
import PulseRequests from '@/components/pulseCards/PulseRequests.vue';
@@ -12,9 +13,14 @@ import PulseServers from '@/components/pulseCards/PulseServers.vue';
import PulseQueues from '@/components/pulseCards/PulseQueues.vue';
import PulseUsage from '@/components/pulseCards/PulseUsage.vue';
import ButtonText from '@/components/inputs/ButtonText.vue';
+import Popover from '@/components/pinesUI/Popover.vue';
import LucideChartNoAxesCombined from '~icons/lucide/chart-no-axes-combined';
+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 validPeriods: { key: string; value: string }[] = [
@@ -27,6 +33,7 @@ const validPeriods: { key: string; value: string }[] = [
const period = ref<string>('1_hour');
const pulseData = ref<PulseResponse>();
+const taskPopover = useTemplateRef('taskPopover');
const { data: stats, isLoading } = useGetSiteAnalytics(period);
const { data: rawPulseData, isLoading: pulseLoading } = useGetPulse({ period });
@@ -44,16 +51,73 @@ watch(
<section class="flex flex-wrap gap-4 flex-col">
<section class="flex justify-between flex-wrap gap-2">
<div class="flex items-center gap-2 flex-wrap [&>*]:h-8">
- <ButtonText @click="toast.add('Success', { type: 'success', description: 'Submitted Scan Request!', life: 3000 })" disabled>
+ <ButtonText @click.stop.prevent="handleStartTask('scan')">
<template #text>Run Full Scan</template>
<template #icon><ProiconsArrowSync /></template>
</ButtonText>
- <ButtonText @click="toast.add('Success', { type: 'success', description: 'Submitted Scan Request!', life: 3000 })" disabled>
- <template #text>New Task</template>
- <template #icon><ProiconsAdd /></template>
- </ButtonText>
+ <Popover popoverClass="!w-52 rounded-lg " :button-attributes="{ title: 'Start New Task' }" ref="taskPopover">
+ <template #buttonText>New Task</template>
+ <template #buttonIcon>
+ <ProiconsAdd />
+ </template>
+ <template #content>
+ <div class="grid gap-4">
+ <div class="space-y-2">
+ <h4 class="font-medium leading-none">Start Server Task</h4>
+ </div>
+
+ <div class="grid gap-2">
+ <ButtonText
+ class="h-8 dark:!bg-neutral-950"
+ :title="'Scan for Folder Changes'"
+ @click="
+ handleStartTask('index').then(() => {
+ taskPopover?.handleClose();
+ })
+ "
+ >
+ <template #text> Index Files </template>
+ <template #icon> <LucideFolderSearch class="-order-1 h-4 w-4" /></template>
+ </ButtonText>
+ <ButtonText
+ class="h-8 dark:!bg-neutral-950"
+ :title="'Sync Folder With Database'"
+ @click="
+ handleStartTask('sync').then(() => {
+ taskPopover?.handleClose();
+ })
+ "
+ >
+ <template #text> Sync Files </template>
+ <template #icon> <LucideFolderSync class="-order-1 h-4 w-4" /></template>
+ </ButtonText>
+ <ButtonText
+ class="h-8 dark:!bg-neutral-950 disabled:opacity-60"
+ :title="'Scan for New Metadata'"
+ @click="
+ handleStartTask('verify').then(() => {
+ taskPopover?.handleClose();
+ })
+ "
+ >
+ <template #text> Verify Metadata </template>
+ <template #icon> <LucideFolderCheck class="-order-1 h-4 w-4" /></template>
+ </ButtonText>
+
+ <ButtonText
+ class="h-8 text-rose-600 dark:!bg-rose-700 disabled:opacity-60"
+ :title="'Scan and Index All Files For Metadata'"
+ @click.stop.prevent="handleStartTask('scan')"
+ >
+ <template #text> Scan All Files </template>
+ <template #icon> <LucideFolderTree class="-order-1 h-4 w-4" /></template>
+ </ButtonText>
+ </div>
+ </div>
+ </template>
+ </Popover>
</div>
- <div class="flex items-center flex-wrap gap-2 ml-auto">
+ <div class="flex items-center flex-wrap gap-2 ml-auto text-sm font-medium">
<h5>Time Period</h5>
<button
v-for="(validPeriod, index) in validPeriods"
@@ -68,13 +132,7 @@ watch(
<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)}`"
- >
+ <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" />
</template>
diff --git a/resources/js/components/dashboard/DashboardLibraries.vue b/resources/js/components/dashboard/DashboardLibraries.vue
index 732cb8bd..8963b52c 100644
--- a/resources/js/components/dashboard/DashboardLibraries.vue
+++ b/resources/js/components/dashboard/DashboardLibraries.vue
@@ -44,9 +44,7 @@ const filteredCategories = computed(() => {
? categories.value.filter((category: CategoryResource) => {
{
try {
- let strRepresentation = [category.name, category.folders_count, category.folders[0]?.name ?? '', category.created_at]
- .join(' ')
- .toLowerCase();
+ let strRepresentation = [category.name, category.folders_count, category.folders[0]?.name ?? '', category.created_at].join(' ').toLowerCase();
return strRepresentation.includes(searchQuery.value.toLowerCase());
} catch (error) {
console.log(error);
@@ -113,11 +111,7 @@ onMounted(() => {
<section id="content-libraries" class="flex gap-8 flex-col">
<div class="flex items-center gap-2 justify-between flex-wrap">
<div class="flex flex-wrap items-center gap-2 [&>*]:h-fit [&>*]:xs:h-8">
- <ButtonText
- title="Add New Library"
- @click="toast.add('Success', { type: 'success', description: 'Submitted Scan Request!', life: 3000 })"
- disabled
- >
+ <ButtonText title="Add New Library" @click="toast.add('Success', { type: 'success', description: 'Submitted Scan Request!', life: 3000 })" disabled>
<template #text>New Library</template>
<template #icon><ProiconsAdd /></template>
</ButtonText>
@@ -126,7 +120,7 @@ onMounted(() => {
<template #icon><ProiconsArrowSync /></template>
</ButtonText>
</div>
- <p class="capitalize text-sm">Count: {{ categories?.length }}</p>
+ <p class="capitalize text-sm font-medium">Count: {{ categories?.length }}</p>
</div>
<TableBase
:use-grid="'grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 2xl:grid-cols-4 3xl:grid-cols-5 gap-3'"
diff --git a/resources/js/components/dashboard/DashboardTasks.vue b/resources/js/components/dashboard/DashboardTasks.vue
index 8dc8fc04..7523aad7 100644
--- a/resources/js/components/dashboard/DashboardTasks.vue
+++ b/resources/js/components/dashboard/DashboardTasks.vue
@@ -2,17 +2,9 @@
import type { TaskStatsResponse } from '@/types/types';
import type { TaskResource } from '@/types/resources';
-import {
- cancelTask,
- deleteTask,
- getTasks,
- getTaskStats,
- startIndexFilesTask,
- startSyncFilesTask,
- startVerifyFilesTask,
-} from '@/service/siteAPI';
-
import { computed, onMounted, onUnmounted, ref, useTemplateRef } from 'vue';
+import { cancelTask, deleteSubTask, deleteTask, getTasks, getTaskStats } from '@/service/siteAPI';
+import { handleStartTask } from '@/service/taskService';
import { toast } from '@/service/toaster/toastService';
import ButtonText from '@/components/inputs/ButtonText.vue';
@@ -118,28 +110,58 @@ const handleSearch = (query: string) => {
searchQuery.value = query;
};
-const handleDelete = (id: number, cancel: boolean = false) => {
+const handleDelete = (id: number, type: '' | 'cancel' | 'subTask' = '', innerId?: number) => {
cachedID.value = id;
- if (cancel) cancelModal.toggleModal(true);
- else deleteModal.toggleModal(true);
+ if (type == 'cancel') cancelModal.toggleModal(true);
+ else if (type == 'subTask') {
+ if (!innerId && innerId !== 0) return;
+ submitSubTaskDelete(innerId);
+ } else deleteModal.toggleModal(true);
};
const submitCancel = async () => {
- if (!cachedID.value) return;
- let request = await cancelTask(cachedID.value);
- if (request) {
+ if (!cachedID.value) {
+ toast('Error', { type: 'danger', description: 'Invalid ID' });
+ return;
+ }
+
+ try {
+ await cancelTask(cachedID.value);
toast.add('Success', { type: 'success', description: 'Task cancelled successfully!', life: 3000 });
loadData();
- } else toast.add('Error', { type: 'warning', description: 'Unable to cancel task. Please try again.', life: 3000 });
+ } catch (error) {
+ toast.add('Error', { type: 'warning', description: 'Unable to cancel task. Please try again.', life: 3000 });
+ }
};
const submitDelete = async () => {
- if (!cachedID.value) return;
- let request = await deleteTask(cachedID.value);
- if (request) {
+ if (!cachedID.value) {
+ toast('Error', { type: 'danger', description: 'Invalid ID' });
+ return;
+ }
+
+ try {
+ await deleteTask(cachedID.value);
toast.add('Success', { type: 'success', description: 'Task deleted successfully!', life: 3000 });
loadData();
- } else toast.add('Error', { type: 'warning', description: 'Unable to delete task. Please try again.', life: 3000 });
+ } catch (error) {
+ toast.add('Error', { type: 'warning', description: 'Unable to delete task. Please try again.', life: 3000 });
+ }
+};
+
+const submitSubTaskDelete = async (id: number) => {
+ if (!id) {
+ toast('Error', { type: 'danger', description: 'Invalid ID' });
+ return;
+ }
+
+ try {
+ await deleteSubTask(id);
+ toast.add('Success', { type: 'success', description: `Sub Task ${id} deleted successfully!`, life: 3000 });
+ loadData();
+ } catch (error) {
+ toast.add('Error', { type: 'warning', description: 'Unable to delete sub task. Please try again.', life: 3000 });
+ }
};
const loadData = async () => {
@@ -150,19 +172,6 @@ const loadData = async () => {
tasks.value = rawTasks?.data?.length > 0 ? rawTasks.data : [];
};
-const handleStartTask = async (job: 'index' | 'sync' | 'verify' | 'scan') => {
- try {
- const result =
- job === 'index' ? await startIndexFilesTask() : job === 'sync' ? await startSyncFilesTask() : await startVerifyFilesTask();
-
- toast.add('Success', { type: 'success', description: `Submitted ${job} Request!` });
- } catch (error) {
- toast('Failure', { type: 'danger', description: `Unable to submit ${job} request.` });
- }
-
- taskPopover.value?.handleClose();
-};
-
const updateScreenSize = () => {
isScreenSmall.value = window.innerWidth < 640;
isScreenLarge.value = window.innerWidth < 1024;
@@ -198,7 +207,11 @@ onUnmounted(() => {
<ButtonText
class="h-8 dark:!bg-neutral-950"
:title="'Scan for Folder Changes'"
- @click="handleStartTask('index')"
+ @click="
+ handleStartTask('index').then(() => {
+ taskPopover?.handleClose();
+ })
+ "
>
<template #text> Index Files </template>
<template #icon> <LucideFolderSearch class="-order-1 h-4 w-4" /></template>
@@ -206,7 +219,11 @@ onUnmounted(() => {
<ButtonText
class="h-8 dark:!bg-neutral-950"
:title="'Sync Folder With Database'"
- @click="handleStartTask('sync')"
+ @click="
+ handleStartTask('sync').then(() => {
+ taskPopover?.handleClose();
+ })
+ "
>
<template #text> Sync Files </template>
<template #icon> <LucideFolderSync class="-order-1 h-4 w-4" /></template>
@@ -214,7 +231,11 @@ onUnmounted(() => {
<ButtonText
class="h-8 dark:!bg-neutral-950 disabled:opacity-60"
:title="'Scan for New Metadata'"
- @click="handleStartTask('verify')"
+ @click="
+ handleStartTask('verify').then(() => {
+ taskPopover?.handleClose();
+ })
+ "
>
<template #text> Verify Metadata </template>
<template #icon> <LucideFolderCheck class="-order-1 h-4 w-4" /></template>
@@ -224,7 +245,6 @@ onUnmounted(() => {
class="h-8 text-rose-600 dark:!bg-rose-700 disabled:opacity-60"
:title="'Scan and Index All Files For Metadata'"
@click.stop.prevent="handleStartTask('scan')"
- disabled
>
<template #text> Scan All Files </template>
<template #icon> <LucideFolderTree class="-order-1 h-4 w-4" /></template>
@@ -233,7 +253,7 @@ onUnmounted(() => {
</div>
</template>
</Popover>
- <ButtonText @click="toast.add('Success', { type: 'success', description: 'Submitted Scan Request!', life: 3000 })" disabled>
+ <ButtonText @click.stop.prevent="handleStartTask('scan')">
<template #text>Run Full Scan</template>
<template #icon><ProiconsArrowSync /></template>
</ButtonText>
diff --git a/resources/js/components/dashboard/DashboardUsers.vue b/resources/js/components/dashboard/DashboardUsers.vue
index 6d14c16c..9a18edcc 100644
--- a/resources/js/components/dashboard/DashboardUsers.vue
+++ b/resources/js/components/dashboard/DashboardUsers.vue
@@ -108,11 +108,7 @@ onMounted(() => {
<section id="tasks" class="flex gap-8 flex-col">
<div class="flex items-start gap-2 justify-between flex-wrap">
<div class="flex flex-wrap items-center gap-2 [&>*]:h-fit [&>*]:xs:h-8">
- <ButtonText
- title="Create new user"
- @click="toast.add('Success', { type: 'success', description: 'User Created!', life: 3000 })"
- disabled
- >
+ <ButtonText title="Create new user" @click="toast.add('Success', { type: 'success', description: 'User Created!', life: 3000 })" disabled>
<template #text>New User</template>
<template #icon><ProiconsAdd /></template>
</ButtonText>
@@ -130,8 +126,8 @@ 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">Active Users: {{ users.length }}</p>
- <p class="w-fit">Active Users: {{ activeSessions }}</p>
+ <p class="w-fit">Users: {{ users.length }}</p>
+ <p class="w-fit">Active: {{ activeSessions }}</p>
</div>
</div>
<TableBase
diff --git a/resources/js/components/labels/ChipTag.vue b/resources/js/components/labels/ChipTag.vue
index aedff563..8ca7fcc8 100644
--- a/resources/js/components/labels/ChipTag.vue
+++ b/resources/js/components/labels/ChipTag.vue
@@ -3,9 +3,9 @@ import { RouterLink } from 'vue-router';
import ButtonCorner from '../inputs/ButtonCorner.vue';
-const props = defineProps(['label', 'colour', 'URL', 'removeable']);
+const props = defineProps(['label', 'colour', 'textClass', 'URL', 'removeable']);
-const styling = `p-1 px-2 text-sm leading-none rounded-xl truncate lowercase text-neutral-100 dark:text-neutral-300 ${props.colour ? `${props.colour}` : 'bg-violet-600 dark:bg-violet-900/90'} shrink-0 transition-colors duration-200 `;
+const styling = `p-1 px-2 text-sm ${props.textClass} leading-none rounded-xl truncate lowercase text-neutral-100 dark:text-neutral-300 ${props.colour ? `${props.colour}` : 'bg-violet-600 dark:bg-violet-900/90'} shrink-0 transition-colors duration-200 `;
</script>
<template>
<RouterLink v-if="props.URL" :class="styling" :to="props.URL">
@@ -13,7 +13,7 @@ const styling = `p-1 px-2 text-sm leading-none rounded-xl truncate lowercase tex
<ButtonCorner
v-if="removeable"
:positionClasses="'w-4 h-4'"
- :textClasses="'text-white dark:text-rose-700'"
+ :textClasses="`text-white dark:text-rose-700`"
:colourClasses="'dark:bg-neutral-900/20 dark:hover:bg-rose-700 hover:bg-rose-300 hover:text-rose-700 dark:hover:text-white drop-shadow'"
:label="'Remove'"
@click.stop.prevent="$emit('clickAction')"
@@ -24,7 +24,7 @@ const styling = `p-1 px-2 text-sm leading-none rounded-xl truncate lowercase tex
<ButtonCorner
v-if="removeable"
:positionClasses="'w-4 h-4'"
- :textClasses="'text-white dark:text-rose-700'"
+ :textClasses="`text-white dark:text-rose-700 ${textClass}`"
:colourClasses="'dark:bg-neutral-900/20 dark:hover:bg-rose-700 hover:bg-rose-300 hover:text-rose-700 dark:hover:text-white drop-shadow'"
:label="'Remove'"
@click.stop.prevent="$emit('clickAction')"
diff --git a/resources/js/components/pinesUI/DropdownItem.vue b/resources/js/components/pinesUI/DropdownItem.vue
index 05140089..989b329f 100755
--- a/resources/js/components/pinesUI/DropdownItem.vue
+++ b/resources/js/components/pinesUI/DropdownItem.vue
@@ -1,6 +1,6 @@
<script setup>
import { RouterLink } from 'vue-router';
-const { linkData, selected, external, disabled } = defineProps(['linkData', 'selected', 'external', 'disabled']);
+const props = defineProps(['linkData', 'selected', 'external', 'disabled']);
</script>
<template>
<a
@@ -11,44 +11,37 @@ const { linkData, selected, external, disabled } = defineProps(['linkData', 'sel
class="cursor-pointer relative w-full flex select-none hover:bg-neutral-100 dark:hover:bg-neutral-900 items-center rounded px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
>
<slot name="icon">
- <span
- width="24"
- height="24"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2"
- stroke-linecap="round"
- stroke-linejoin="round"
- class="w-4 h-4 mr-2"
- >
+ <span width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="w-4 h-4 mr-2">
</span>
</slot>
<span class="text-nowrap">{{ linkData.text }}</span
><span class="ml-auto text-xs tracking-widest opacity-60">{{ linkData.shortcut ?? '' }}</span>
</a>
<RouterLink
- v-else
+ v-else-if="linkData.url"
:class="{ 'font-bold text-violet-500': selected }"
:to="disabled ? '' : linkData.url"
:data-disabled="disabled"
class="cursor-pointer relative w-full flex select-none hover:bg-neutral-100 dark:hover:bg-neutral-900 items-center rounded px-2 py-1.5 text-sm outline-none transition-colors data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50"
>
<slot name="icon">
- <span
- width="24"
- height="24"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2"
- stroke-linecap="round"
- stroke-linejoin="round"
- class="w-4 h-4 mr-2"
- >
+ <span width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="w-4 h-4 mr-2">
</span>
</slot>
<span class="text-nowrap">{{ linkData.text }}</span>
<span class="ml-auto text-xs tracking-widest opacity-60">{{ linkData.shortcut ?? '' }}</span>
</RouterLink>
+ <button
+ v-else
+ :class="{ 'font-bold text-violet-500': selected }"
+ :disabled="disabled"
+ class="cursor-pointer relative w-full flex select-none hover:bg-neutral-100 dark:hover:bg-neutral-900 items-center rounded px-2 py-1.5 text-sm outline-none transition-colors data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50"
+ >
+ <slot name="icon">
+ <span width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="w-4 h-4 mr-2">
+ </span>
+ </slot>
+ <span class="text-nowrap">{{ linkData.text }}</span>
+ <span class="ml-auto text-xs tracking-widest opacity-60">{{ linkData.shortcut ?? '' }}</span>
+ </button>
</template>
diff --git a/resources/js/components/pinesUI/DropdownMenu.vue b/resources/js/components/pinesUI/DropdownMenu.vue
index a54f167a..ca780ff8 100755
--- a/resources/js/components/pinesUI/DropdownMenu.vue
+++ b/resources/js/components/pinesUI/DropdownMenu.vue
@@ -26,6 +26,8 @@ import LucideImages from '~icons/lucide/images';
import CircumServer from '~icons/circum/server';
import ProiconsServer from '~icons/proicons/server';
import CircumHardDrive from '~icons/circum/hard-drive';
+import { handleStartTask } from '@/service/taskService';
+import type { Component } from 'vue';
const authStore = useAuthStore();
const props = defineProps(['dropdownOpen']);
@@ -39,7 +41,7 @@ const dropDownItems = [
{ ...defaults, name: 'register', url: '/register', text: 'Sign up', icon: LucideUserPlus },
],
];
-const dropDownItemsAuth = [
+const dropDownItemsAuth: { name: string; url?: string; text: string; icon?: Component; disabled?: boolean; external?: boolean; action?: () => void; shortcut?: string }[][] = [
[
{ ...defaults, name: 'profile', url: '/profile', text: 'Profile', icon: LucideUser, disabled: true },
{ ...defaults, name: 'settings', url: '/settings', text: 'Settings', icon: LucideSettings },
@@ -57,9 +59,33 @@ const dropDownItemsAuth = [
{ ...defaults, name: 'tasks', url: '/dashboard/tasks', text: 'Tasks', icon: CircumHardDrive },
],
[
- { ...defaults, name: 'index', url: '/jobs/indexFiles', text: 'Index Files', external: true, icon: LucideFolderSearch },
- { ...defaults, name: 'sync', url: '/jobs/syncFiles', text: 'Sync Files', external: true, icon: LucideFolderSync },
- { ...defaults, name: 'verify', url: '/jobs/verifyFiles', text: 'Verify Files', external: true, icon: LucideFolderCheck },
+ {
+ ...defaults,
+ name: 'index',
+ text: 'Index Files',
+ icon: LucideFolderSearch,
+ action: () => {
+ handleStartTask('index');
+ },
+ },
+ {
+ ...defaults,
+ name: 'sync',
+ text: 'Sync Files',
+ icon: LucideFolderSync,
+ action: () => {
+ handleStartTask('sync');
+ },
+ },
+ {
+ ...defaults,
+ name: 'verify',
+ text: 'Verify Files',
+ icon: LucideFolderCheck,
+ action: () => {
+ handleStartTask('verify');
+ },
+ },
],
[{ ...defaults, name: 'logout', url: '/logout', text: 'Log out', icon: LucideLogOut, shortcut: '⇧⌘Q' }],
];
@@ -87,27 +113,23 @@ const { userData } = storeToRefs(authStore);
<div class="px-2 py-1.5 text-sm font-semibold">My Account</div>
<div class="h-px my-1 -mx-1 bg-neutral-200 dark:bg-neutral-500"></div>
<section v-for="(group, groupIndex) in dropDownItemsAuth" :key="groupIndex">
- <div
- v-if="groupIndex !== 0 && groupIndex !== dropDownItemsAuth.length"
- class="h-px my-1 -mx-1 bg-neutral-200 dark:bg-neutral-500"
- ></div>
+ <div v-if="groupIndex !== 0 && groupIndex !== dropDownItemsAuth.length" class="h-px my-1 -mx-1 bg-neutral-200 dark:bg-neutral-500"></div>
<DropdownItem
v-for="(item, index) in dropDownItemsAuth[groupIndex]"
:key="index"
:linkData="item"
- :selected="$route.path === item.name || $route.path === item.url"
+ :selected="item?.url && ($route.path === item.name || $route.path === item.url)"
:external="item?.external"
:disabled="item?.disabled ?? false"
- @click="$emit('toggleDropdown', false)"
+ @click="
+ () => {
+ $emit('toggleDropdown', false);
+ if (item.action) item.action();
+ }
+ "
>
<template #icon>
- <component
- :is="item.icon"
- viewBox="0 0 24 24"
- stroke="currentColor"
- stroke-width="0.2"
- class="w-4 h-4 mr-2"
- />
+ <component :is="item.icon" viewBox="0 0 24 24" stroke="currentColor" stroke-width="0.2" class="w-4 h-4 mr-2" />
</template>
</DropdownItem>
</section>
@@ -117,10 +139,7 @@ const { userData } = storeToRefs(authStore);
class="p-1 mt-1 bg-white dark:bg-neutral-800/70 backdrop-blur-lg border rounded-md shadow-md border-neutral-200/70 dark:border-neutral-700 text-neutral-700 dark:text-neutral-100"
>
<section v-for="(group, groupIndex) in dropDownItems" :key="groupIndex">
- <div
- v-if="groupIndex !== 0 && groupIndex !== dropDownItems.length"
- class="h-px my-1 -mx-1 bg-neutral-200 dark:bg-neutral-500"
- ></div>
+ <div v-if="groupIndex !== 0 && groupIndex !== dropDownItems.length" class="h-px my-1 -mx-1 bg-neutral-200 dark:bg-neutral-500"></div>
<DropdownItem
v-for="(item, index) in dropDownItems[groupIndex]"
:key="index"
diff --git a/resources/js/components/table/TableBase.vue b/resources/js/components/table/TableBase.vue
index 33be7814..7be8e204 100755
--- a/resources/js/components/table/TableBase.vue
+++ b/resources/js/components/table/TableBase.vue
@@ -80,14 +80,7 @@ onMounted(() => {
<span class="flex items-end gap-2 flex-wrap">
<div class="flex gap-2 flex-col w-full sm:w-40 flex-1">
<FormInputLabel :field="{ name: 'sort', text: 'Sort by:' }" />
- <InputSelect
- :placeholder="'None'"
- :options="props.sortingOptions"
- class="w-full"
- title="Select Sort"
- @selectItem="handleSortChange"
- :defaultItem="0"
- />
+ <InputSelect :placeholder="'None'" :options="props.sortingOptions" class="w-full" title="Select Sort" @selectItem="handleSortChange" :defaultItem="0" />
</div>
<ButtonIcon
@click="
@@ -122,7 +115,7 @@ onMounted(() => {
:index="index"
:currentID="props.selectedID ?? null"
v-bind="rowAttributes"
- @clickAction="props.clickAction(row?.id)"
+ @clickAction="(...args: any[]) => props.clickAction?.(row?.id, ...args)"
@otherAction="$emit('otherAction', $event)"
></component>
</tbody>
diff --git a/resources/js/components/table/TablePagination.vue b/resources/js/components/table/TablePagination.vue
index bf8b58c7..e61d266c 100755
--- a/resources/js/components/table/TablePagination.vue
+++ b/resources/js/components/table/TablePagination.vue
@@ -39,7 +39,7 @@ const handleSetPage = async (page: number) => {
<template>
<div class="flex items-center flex-col sm:flex-row sm:justify-between flex-wrap gap-2 scroll-mb-12" ref="$element">
- <p class="text-gray-700 dark:text-neutral-300 line-clamp-1">
+ <p class="text-gray-700 dark:text-neutral-300 line-clamp-1 text-sm">
Showing
<span class="font-medium dark:text-neutral-100">{{ props.listLength ? props.itemsPerPage * (currentPage - 1) + 1 : 0 }}</span>
to
@@ -52,44 +52,18 @@ const handleSetPage = async (page: number) => {
<ul
class="flex flex-wrap items-center text-sm leading-tight bg-white dark:bg-primary-dark-800/70 border divide-x rounded h-9 text-neutral-500 dark:text-neutral-200 divide-neutral-200 dark:divide-neutral-700 border-neutral-200 dark:border-neutral-700"
>
- <TablePaginationButton
- :pageNumber="-1"
- :text="'Previous'"
- :disabled="props.currentPage === 1"
- @click="handleSetPage(Math.max(1, props.currentPage - 1))"
- />
+ <TablePaginationButton :pageNumber="-1" :text="'Previous'" :disabled="props.currentPage === 1" @click="handleSetPage(Math.max(1, props.currentPage - 1))" />
<template v-if="pageCount > 5 && props.currentPage > 3">
<TablePaginationButton :pageNumber="1" :currentPage="props.currentPage" @click="handleSetPage(1)" :sticky="true" />
- <TablePaginationButton
- :pageNumber="-1"
- :text="'...'"
- @click="handleSetPage(Math.floor(currentPage / 2))"
- :underline="true"
- />
+ <TablePaginationButton :pageNumber="-1" :text="'...'" @click="handleSetPage(Math.floor(currentPage / 2))" :underline="true" />
</template>
- <TablePaginationButton
- v-for="page in pageRange"
- :key="page"
- :pageNumber="page"
- :currentPage="props.currentPage"
- @click="handleSetPage(page)"
- />
+ <TablePaginationButton v-for="page in pageRange" :key="page" :pageNumber="page" :currentPage="props.currentPage" @click="handleSetPage(page)" />
<template v-if="pageCount > 5 && pageCount - props.currentPage > 2">
- <TablePaginationButton
- :pageNumber="-1"
- :text="'...'"
- @click="handleSetPage(Math.floor((pageCount - currentPage) / 2 + currentPage))"
- :underline="true"
- />
- <TablePaginationButton
- :pageNumber="pageCount"
- :currentPage="props.currentPage"
- @click="handleSetPage(pageCount)"
- :sticky="true"
- />
+ <TablePaginationButton :pageNumber="-1" :text="'...'" @click="handleSetPage(Math.floor((pageCount - currentPage) / 2 + currentPage))" :underline="true" />
+ <TablePaginationButton :pageNumber="pageCount" :currentPage="props.currentPage" @click="handleSetPage(pageCount)" :sticky="true" />
</template>
<TablePaginationButton
diff --git a/resources/js/components/video/VideoPlayer.vue b/resources/js/components/video/VideoPlayer.vue
index b69954aa..8718436f 100755
--- a/resources/js/components/video/VideoPlayer.vue
+++ b/resources/js/components/video/VideoPlayer.vue
@@ -173,10 +173,7 @@ const handleProgress = (override = false) => {
if (isNaN(progress) || !progress) return;
- progressCache.value = [
- ...progressCache.value,
- { metadata_id: stateVideo.value?.metadata?.id, progress: parseFloat(progress.toFixed(2)) * 1000 },
- ];
+ progressCache.value = [...progressCache.value, { metadata_id: stateVideo.value?.metadata?.id, progress: parseFloat(progress.toFixed(2)) * 1000 }];
if (progressCache.value.length >= playbackDataBuffer || override) {
createPlayback({ entries: progressCache.value });
@@ -185,7 +182,6 @@ const handleProgress = (override = false) => {
};
const onPlayerPlay = (event: any) => {
- // console.log(event.type);
// player.setPlaying(true);
handlePlayVideo();
emit('play');
@@ -213,7 +209,11 @@ const onPlayerLoadeddata = (event: any) => {
const onPlayerWaiting = (event: any) => {
// console.log(event.type);
- if (player.value?.loop) currentID.value = -1;
+ if (player.value?.loop) {
+ createRecord(stateVideo.value.id);
+ updateViewCount(stateVideo.value.id);
+ handleProgress(true);
+ }
};
const onPlayerPlaying = (event: any) => {
@@ -263,6 +263,8 @@ onMounted(() => {
player.value.volume = parseFloat(savedVolume);
}
+ isAudio.value = stateVideo.value?.metadata?.mime_type?.startsWith('audio') ?? false;
+
// document.querySelector('video')?.addEventListener('ended', function () {
// console.count('loop restart');
// this.play();
@@ -293,7 +295,7 @@ onUnmounted(() => {
ref="player"
style="z-index: 3"
:src="stateVideo?.path ? `../${stateVideo?.path}` : ''"
- :class="`relative focus:outline-none flex object-contain ${stateVideo?.path ? (stateVideo.path.endsWith('.mp3') ? 'max-h-[60vh]' : '') : 'aspect-video'}`"
+ :class="`relative focus:outline-none flex object-contain ${stateVideo?.path ? (isAudio ? 'max-h-[60vh]' : '') : 'aspect-video'}`"
:poster="
isAudio
? (stateVideo?.metadata?.poster_url ??
@@ -328,16 +330,7 @@ onUnmounted(() => {
</clipPath>
</defs>
<rect class="ytp-heat-map-graph" clip-path="url(#4)" height="100%" width="100%" x="0" y="0"></rect>
- <rect
- class="ytp-heat-map-hover"
- clip-path="url(#4)"
- fill="white"
- fill-opacity="0.7"
- height="100%"
- width="100%"
- x="0"
- y="0"
- ></rect>
+ <rect class="ytp-heat-map-hover" clip-path="url(#4)" fill="white" fill-opacity="0.7" height="100%" width="100%" x="0" y="0"></rect>
<rect class="ytp-heat-map-play" clip-path="url(#4)" height="100%" x="0" y="0"></rect>
</svg>
</section>
diff --git a/resources/js/service/api.ts b/resources/js/service/api.ts
index 94be1149..81e1c928 100644
--- a/resources/js/service/api.ts
+++ b/resources/js/service/api.ts
@@ -1,4 +1,5 @@
import axios from 'axios';
+import { toast } from './toaster/toastService';
const handleResponse = (response: any) => {
return response;
@@ -13,7 +14,8 @@ const handleError = (error: { response: { status: number; data: { message: any }
return;
}
- if (error.response.status === 401 || error.response.status == 422 || error.response.status == 500) throw error;
+ toast('Error', { type: 'danger', description: error.message });
+ if (error.response.status === 401 || error.response.status == 422 || error.response.status == 500 || error.response.status == 404) throw error;
console.log(error);
diff --git a/resources/js/service/taskService.ts b/resources/js/service/taskService.ts
new file mode 100644
index 00000000..76642a64
--- /dev/null
+++ b/resources/js/service/taskService.ts
@@ -0,0 +1,19 @@
+import { startIndexFilesTask, startScanFilesTask, startSyncFilesTask, startVerifyFilesTask } from './siteAPI';
+import { toast } from './toaster/toastService';
+
+export async function handleStartTask(job: 'index' | 'sync' | 'verify' | 'scan') {
+ try {
+ const result =
+ job === 'index'
+ ? await startIndexFilesTask()
+ : job === 'sync'
+ ? await startSyncFilesTask()
+ : job === 'verify'
+ ? await startVerifyFilesTask()
+ : await startScanFilesTask();
+
+ toast.add('Success', { type: 'success', description: `Submitted ${job} Request!` });
+ } catch (error) {
+ toast('Failure', { type: 'danger', description: `Unable to submit ${job} request.` });
+ }
+}
diff --git a/resources/js/stores/ContentStore.js b/resources/js/stores/ContentStore.js
index e060030c..e0ef78f4 100755
--- a/resources/js/stores/ContentStore.js
+++ b/resources/js/stores/ContentStore.js
@@ -3,10 +3,10 @@ import { computed, ref } from 'vue';
import { useAuthStore } from './AuthStore';
import { useAppStore } from './AppStore';
import { useRoute } from 'vue-router';
+import { toast } from '@/service/toaster/toastService';
import recordsAPI from '@/service/recordsAPI';
import mediaAPI from '@/service/mediaAPI.ts';
-import { toast } from '@/service/toaster/toastService';
export const useContentStore = defineStore('Content', () => {
const AuthStore = useAuthStore();
diff --git a/resources/js/views/VideoView.vue b/resources/js/views/VideoView.vue
index 36ce03a0..6cc89057 100755
--- a/resources/js/views/VideoView.vue
+++ b/resources/js/views/VideoView.vue
@@ -44,10 +44,8 @@ async function reload() {
loading.value = true;
if (stateDirectory.value?.name && stateDirectory.value.name === URL_CATEGORY) {
- console.log(stateDirectory.value);
await getFolder(URL_FOLDER);
} else {
- console.log('2');
await getCategory(URL_CATEGORY, URL_FOLDER);
}
loading.value = false;