Skip to content

A self-hosted media server and file management system

feat: lyrics api and updating service + tests and factories

aminnausindfcfc4572c4a
diff --git a/app/Http/Controllers/Api/V1/ExternalMetadataController.php b/app/Http/Controllers/Api/V1/ExternalMetadataController.php
index d0d54e4b..658a9091 100644
--- a/app/Http/Controllers/Api/V1/ExternalMetadataController.php
+++ b/app/Http/Controllers/Api/V1/ExternalMetadataController.php
@@ -4,34 +4,21 @@ namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Models\Metadata;
+use App\Services\External\LrcLibService;
use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Http;
class ExternalMetadataController extends Controller {
+ public function __construct(protected LrcLibService $lrcLibService) {}
+
public function importLyrics(Request $request, $id) {
$metadata = Metadata::FindOrFail($id);
- $data = [
- 'artist_name' => explode(' - ', $metadata->description)[0],
- 'track_name' => $metadata->title,
- // 'album_name' => $request->query('album_name'),
- 'duration' => $metadata->duration,
- ];
- $response = Http::get('https://lrclib.net/api/get', $data);
- return response()->json(['lrclib' => $response->json(), 'payload' => $data]);
+ return response()->json($this->lrcLibService->importLyrics($metadata));
}
public function searchLyrics(Request $request, $id) {
$metadata = Metadata::FindOrFail($id);
- $data = [
- 'artist_name' => explode(' - ', $metadata->description)[0],
- 'track_name' => $metadata->title,
- // 'album_name' => $request->query('album_name'),
- // 'duration' => $metadata->duration,
- ];
- // $response = Http::get('https://lrclib.net/api/get', $data);
- $response = Http::get('https://lrclib.net/api/search?q=' . implode('+', $data));
- return response()->json(['lrclib' => $response->json(), 'payload' => $data]);
+ return response()->json($this->lrcLibService->searchLyrics($metadata, $request));
}
}
diff --git a/app/Http/Controllers/Api/V1/MetadataController.php b/app/Http/Controllers/Api/V1/MetadataController.php
index 750929eb..e8967eab 100644
--- a/app/Http/Controllers/Api/V1/MetadataController.php
+++ b/app/Http/Controllers/Api/V1/MetadataController.php
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
+use App\Http\Requests\LyricsUpdateRequest;
use App\Http\Requests\MetadataStoreRequest;
use App\Http\Requests\MetadataUpdateRequest;
use App\Http\Resources\MetadataResource;
@@ -72,6 +73,9 @@ class MetadataController extends Controller {
public function update(MetadataUpdateRequest $request, Metadata $metadata) {
try {
$validated = $request->validated();
+
+ if (empty($metadata->video)) throw new \Exception('Media does not exist');
+
$validated['editor_id'] = Auth::id();
$metadata->update($validated);
@@ -82,4 +86,21 @@ class MetadataController extends Controller {
return $this->error($request, 'Unable to edit video metadata. Error: ' . $th->getMessage(), 500);
}
}
+
+ public function updateLyrics(LyricsUpdateRequest $request, Metadata $metadata) {
+ try {
+ $validated = $request->validated();
+
+ if (empty($metadata->video)) throw new \Exception('Song does not exist');
+
+ unset($validated['track']);
+
+ $validated['editor_id'] = Auth::id();
+ $metadata->update($validated);
+
+ return response()->json(new VideoResource($metadata->video), 200);
+ } catch (\Throwable $th) {
+ return $this->error($request, 'Unable to edit song. Error: ' . $th->getMessage(), 500);
+ }
+ }
}
diff --git a/app/Http/Requests/LyricsUpdateRequest.php b/app/Http/Requests/LyricsUpdateRequest.php
new file mode 100644
index 00000000..2ff75af5
--- /dev/null
+++ b/app/Http/Requests/LyricsUpdateRequest.php
@@ -0,0 +1,29 @@
+<?php
+
+namespace App\Http\Requests;
+
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Support\Facades\Auth;
+
+class LyricsUpdateRequest extends FormRequest {
+ /**
+ * Determine if the user is authorized to make this request.
+ */
+ public function authorize(): bool {
+ return Auth::check();
+ }
+
+ /**
+ * Get the validation rules that apply to the request.
+ *
+ * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
+ */
+ public function rules(): array {
+ return [
+ 'track' => 'required|max:255',
+ 'artist' => 'nullable|max:255',
+ 'album' => 'nullable|max:255',
+ 'lyrics' => 'nullable',
+ ];
+ }
+}
diff --git a/app/Services/External/LrcLibService.php b/app/Services/External/LrcLibService.php
new file mode 100644
index 00000000..dd213089
--- /dev/null
+++ b/app/Services/External/LrcLibService.php
@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Services\External;
+
+use App\Models\Metadata;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Http;
+
+class LrcLibService {
+ public function importLyrics(Metadata $metadata): array {
+ $query = array_filter([
+ 'track_name' => $metadata->title,
+ 'artist_name' => explode(' - ', $metadata->description)[0],
+ 'album_name' => $metadata->album,
+ 'duration' => $metadata->duration,
+ ], fn ($value) => $value !== null && $value !== '');
+
+ $response = Http::get('https://lrclib.net/api/get', $query);
+
+ return ['lrclib' => $response->json(), 'payload' => $query];
+ }
+
+ public function searchLyrics(Metadata $metadata, Request $request): array {
+ $query = array_filter([
+ 'track_name' => $request->query('track') ?? $metadata->title,
+ 'artist_name' => $request->query('artist') ?? explode(' - ', $metadata->description)[0],
+ 'album_name' => $request->query('album'),
+ ], fn ($value) => $value !== null && $value !== '');
+
+ $response = Http::get('https://lrclib.net/api/search', $query);
+
+ return ['lrclib' => $response->json(), 'payload' => $query];
+ }
+}
diff --git a/database/factories/CategoryFactory.php b/database/factories/CategoryFactory.php
new file mode 100644
index 00000000..90b23346
--- /dev/null
+++ b/database/factories/CategoryFactory.php
@@ -0,0 +1,22 @@
+<?php
+
+namespace Database\Factories;
+
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Category>
+ */
+class CategoryFactory extends Factory {
+ /**
+ * Define the model's default state.
+ *
+ * @return array<string, mixed>
+ */
+ public function definition(): array {
+ return [
+ 'name' => $this->faker->word(),
+ 'media_content' => false
+ ];
+ }
+}
diff --git a/database/factories/FolderFactory.php b/database/factories/FolderFactory.php
new file mode 100644
index 00000000..084879c0
--- /dev/null
+++ b/database/factories/FolderFactory.php
@@ -0,0 +1,24 @@
+<?php
+
+namespace Database\Factories;
+
+use App\Models\Category;
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Folder>
+ */
+class FolderFactory extends Factory {
+ /**
+ * Define the model's default state.
+ *
+ * @return array<string, mixed>
+ */
+ public function definition(): array {
+ return [
+ 'category_id' => Category::factory(),
+ 'name' => $this->faker->sentence(2),
+ 'path' => $this->faker->unique()->word(), // or a real-looking folder path
+ ];
+ }
+}
diff --git a/database/factories/MetadataFactory.php b/database/factories/MetadataFactory.php
new file mode 100644
index 00000000..36e2399d
--- /dev/null
+++ b/database/factories/MetadataFactory.php
@@ -0,0 +1,28 @@
+<?php
+
+namespace Database\Factories;
+
+use App\Models\Video;
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Metadata>
+ */
+class MetadataFactory extends Factory {
+ /**
+ * Define the model's default state.
+ *
+ * @return array<string, mixed>
+ */
+ public function definition(): array {
+ // $video = Video::factory()->create();
+ return [
+ 'composite_id' => "{$this->faker->word}/{$this->faker->word}",
+ // 'video_id' => $video->id,
+ 'title' => $this->faker->sentence(3),
+ 'description' => 'Fake Artist - something',
+ 'album' => $this->faker->word,
+ 'duration' => $this->faker->numberBetween(60, 500),
+ ];
+ }
+}
diff --git a/database/factories/SeriesFactory.php b/database/factories/SeriesFactory.php
new file mode 100644
index 00000000..d4978221
--- /dev/null
+++ b/database/factories/SeriesFactory.php
@@ -0,0 +1,23 @@
+<?php
+
+namespace Database\Factories;
+
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Series>
+ */
+class SeriesFactory extends Factory
+{
+ /**
+ * Define the model's default state.
+ *
+ * @return array<string, mixed>
+ */
+ public function definition(): array
+ {
+ return [
+ //
+ ];
+ }
+}
diff --git a/database/factories/VideoFactory.php b/database/factories/VideoFactory.php
new file mode 100644
index 00000000..afc24980
--- /dev/null
+++ b/database/factories/VideoFactory.php
@@ -0,0 +1,25 @@
+<?php
+
+namespace Database\Factories;
+
+use App\Models\Folder;
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Video>
+ */
+class VideoFactory extends Factory {
+ /**
+ * Define the model's default state.
+ *
+ * @return array<string, mixed>
+ */
+ public function definition(): array {
+ return [
+ 'folder_id' => Folder::factory(),
+ 'name' => $this->faker->sentence(3),
+ 'path' => $this->faker->unique()->filePath(),
+ 'date' => $this->faker->date()
+ ];
+ }
+}
diff --git a/routes/api.php b/routes/api.php
index c7c9dd53..011f8f4e 100755
--- a/routes/api.php
+++ b/routes/api.php
@@ -42,6 +42,8 @@ Route::group(['middleware' => ['auth:sanctum']], function () {
Route::resource('/series', SeriesController::class)->only(['index', 'store', 'update']);
Route::resource('/tags', TagController::class)->only(['index', 'store']);
+ Route::patch('/metadata/{metadata}/lyrics', [MetadataController::class, 'updateLyrics']);
+
// Users
Route::resource('/profiles', ProfileController::class)->only(['show', 'store', 'update']);
Route::resource('/records', RecordController::class)->only(['index', 'store', 'destroy']);
diff --git a/tests/Feature/ExternalMetadataControllerTest.php b/tests/Feature/ExternalMetadataControllerTest.php
new file mode 100644
index 00000000..a673a55b
--- /dev/null
+++ b/tests/Feature/ExternalMetadataControllerTest.php
@@ -0,0 +1,49 @@
+<?php
+
+namespace Tests\Feature;
+
+use App\Models\Metadata;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Http;
+use Tests\TestCase;
+
+class ExternalMetadataControllerTest extends TestCase {
+ use RefreshDatabase;
+
+ public function test_import_lyrics_returns_expected_payload() {
+ $metadata = Metadata::factory()->create([
+ 'title' => 'Test Title',
+ 'description' => 'Test Artist - Something',
+ 'album' => 'Test Album',
+ 'duration' => 120,
+ ]);
+
+ Http::fake([
+ 'https://lrclib.net/api/get*' => Http::response(['syncedLyrics' => 'lyrics text'], 200),
+ ]);
+
+ $this->getJson("/api/metadata/{$metadata->id}/lyrics/import")
+ ->assertStatus(200)
+ ->assertJsonStructure([
+ 'lrclib' => ['syncedLyrics'],
+ 'payload' => ['track_name', 'artist_name', 'album_name', 'duration']
+ ]);
+ }
+
+ public function test_search_lyrics_with_custom_query() {
+ $metadata = Metadata::factory()->create();
+
+ Http::fake([
+ 'https://lrclib.net/api/search*' => Http::response(['lrclib' => [['id' => 123]], 'payload' => []], 200),
+ ]);
+
+ $this->getJson("/api/metadata/{$metadata->id}/lyrics/search?artist=Test+Artist")
+ ->assertStatus(200)
+ ->assertJsonPath('lrclib.lrclib.0.id', 123);
+ }
+
+ public function test_import_fails_for_missing_metadata() {
+ $this->getJson("/api/metadata/99999/lyrics/import")
+ ->assertStatus(404);
+ }
+}
diff --git a/tests/Feature/MetadataControllerTest.php b/tests/Feature/MetadataControllerTest.php
new file mode 100644
index 00000000..6043fc50
--- /dev/null
+++ b/tests/Feature/MetadataControllerTest.php
@@ -0,0 +1,96 @@
+<?php
+
+namespace Tests\Feature;
+
+use App\Http\Requests\MetadataUpdateRequest;
+use App\Models\Metadata;
+use App\Models\User;
+use App\Models\Video;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Auth;
+use Tests\TestCase;
+
+class MetadataControllerTest extends TestCase {
+ use RefreshDatabase;
+
+ protected function authenticateUser() {
+ $user = User::factory()->create();
+ $this->actingAs($user);
+ return $user;
+ }
+
+ public function test_show_returns_metadata_resource() {
+ $this->authenticateUser();
+
+ $metadata = Metadata::factory()->create();
+ $this->getJson("/api/metadata/{$metadata->id}")
+ ->assertStatus(200)
+ ->assertJsonFragment(['id' => $metadata->id]);
+ }
+
+ public function test_store_creates_metadata_or_updates_existing() {
+ $this->authenticateUser();
+
+ $video = Video::factory()->create();
+ $payload = [
+ 'video_id' => $video->id,
+ 'title' => 'Test Title',
+ 'description' => 'Artist - Track',
+ 'duration' => 120,
+ 'video_tags' => [],
+ 'deleted_tags' => [],
+ ];
+
+ $this->postJson('/api/metadata', $payload)
+ ->assertStatus(200)
+ ->assertJsonPath('data.id', "{$video->id}");
+ }
+
+ public function test_update_edits_metadata_and_returns_updated_video() {
+ $this->authenticateUser();
+
+ $metadata = Metadata::factory()->create(['video_id' => Video::factory()]);
+ $payload = [
+ 'title' => 'Updated Title',
+ 'description' => 'Updated Description',
+ 'duration' => 999,
+ 'video_tags' => [],
+ 'deleted_tags' => [],
+ ];
+ $this->patchJson("/api/metadata/{$metadata->id}", $payload)
+ ->assertStatus(200)
+ ->assertJsonPath('data.metadata.title', 'Updated Title');
+ }
+
+ public function test_update_lyrics_works_and_ignores_track_field() {
+ $this->authenticateUser();
+
+ $metadata = Metadata::factory()->create(['video_id' => Video::factory()]);
+ $payload = [
+ 'lyrics' => 'Synced lyrics here',
+ 'album' => 'Test Album',
+ 'artist' => 'Test Artist',
+ 'track' => 'Should be ignored',
+ ];
+
+ $this->patchJson("/api/metadata/{$metadata->id}/lyrics", $payload)
+ ->assertStatus(200)
+ ->assertJsonFragment(['album' => 'Test Album']);
+ }
+
+ public function test_update_lyrics_returns_error_without_associated_video() {
+ $this->authenticateUser();
+
+ $metadata = Metadata::factory()->create();
+ $payload = [
+ 'lyrics' => 'Synced lyrics here',
+ 'album' => 'Test Album',
+ 'artist' => 'Test Artist',
+ 'track' => 'Should be ignored',
+ ];
+
+ $this->patchJson("/api/metadata/{$metadata->id}/lyrics", $payload)
+ ->assertStatus(500)
+ ->assertJsonPath('message', 'Unable to edit song. Error: Song does not exist');
+ }
+}
diff --git a/tests/Unit/LrcLibServiceTest.php b/tests/Unit/LrcLibServiceTest.php
new file mode 100644
index 00000000..6ee5710b
--- /dev/null
+++ b/tests/Unit/LrcLibServiceTest.php
@@ -0,0 +1,62 @@
+<?php
+
+namespace Tests\Unit;
+
+use App\Models\Metadata;
+use App\Services\External\LrcLibService;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Str;
+use Tests\TestCase;
+
+class LrcLibServiceTest extends TestCase {
+ public function test_import_lyrics_makes_correct_http_request() {
+ Http::fake([
+ 'https://lrclib.net/api/get*' => Http::response(['syncedLyrics' => 'Lyrics'], 200),
+ ]);
+
+ $metadata = Metadata::factory()->make([
+ 'title' => 'Test Song',
+ 'description' => 'Test Artist - Something',
+ 'album' => null,
+ 'duration' => 123,
+ ]);
+
+ $service = new LrcLibService;
+ $response = $service->importLyrics($metadata);
+
+ Http::assertSent(function ($request) {
+ return Str::startsWith($request->url(), 'https://lrclib.net/api/get') &&
+ $request['track_name'] === 'Test Song' &&
+ $request['artist_name'] === 'Test Artist' &&
+ $request['duration'] === 123 && empty($request['album']);
+ });
+
+ $this->assertEquals('Lyrics', $response['lrclib']['syncedLyrics']);
+ }
+
+ public function test_search_lyrics_uses_query_overrides() {
+ Http::fake([
+ 'https://lrclib.net/api/search*' => Http::response(['results' => []], 200),
+ ]);
+
+ $metadata = Metadata::factory()->make([
+ 'title' => 'Test Song',
+ 'description' => 'Wrong Artist',
+ ]);
+
+ $request = request()->merge([
+ 'track' => 'Overridden Song',
+ 'artist' => 'Correct Artist',
+ ]);
+
+ $service = new LrcLibService;
+ $response = $service->searchLyrics($metadata, $request);
+
+ Http::assertSent(function ($request) {
+ return $request['track_name'] === 'Overridden Song' &&
+ $request['artist_name'] === 'Correct Artist';
+ });
+
+ $this->assertArrayHasKey('lrclib', $response);
+ }
+}