113 lines
2.9 KiB
PHP
113 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use App\Models\Song;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Inertia\Inertia;
|
|
use Inertia\Response;
|
|
use Illuminate\Support\Facades\Gate;
|
|
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
|
|
|
class SongController extends Controller
|
|
{ use AuthorizesRequests;
|
|
public function index(Request $request): Response
|
|
{
|
|
return Inertia::render('Songs/Index', [
|
|
'songs' => Song::where('user_id', auth()->id())->paginate(10),
|
|
]);
|
|
}
|
|
|
|
public function store(Request $request): JsonResponse
|
|
{
|
|
Gate::authorize("create", Song::class);
|
|
|
|
$validated = $request->validate([
|
|
'song' => 'max:108826630',
|
|
]);
|
|
$song = new Song();
|
|
$song->user_id = auth()->id();
|
|
|
|
$file = $request->song;
|
|
$path = $file->store('songs');
|
|
$song->title = $file->getClientOriginalName();
|
|
$song->path = $path;
|
|
$song->artist = $file->getClientOriginalName();
|
|
|
|
$ret = $song->save();
|
|
|
|
return response()->json([
|
|
'data' => $ret ? "Guardado " . $song->title : 'sin archivo'
|
|
]);
|
|
}
|
|
/**
|
|
* @param int $id
|
|
*/
|
|
public function update(Request $request, $id)
|
|
{
|
|
// Actualizar cancion
|
|
$song = Song::find($id);
|
|
$this->authorize("update", $song);
|
|
|
|
$validated = $request->validate([
|
|
'title' => 'required|string',
|
|
'artist' => 'required|string',
|
|
]);
|
|
|
|
$song->title = $validated['title'];
|
|
$song->artist = $validated['artist'];
|
|
$song->save();
|
|
|
|
return response()->json([
|
|
'data' => 'Updated successfully'
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @param int $id
|
|
*/
|
|
public function destroy($id)
|
|
{
|
|
$song = Song::find($id);
|
|
$user = User::find(auth()->id());
|
|
|
|
//Gate::authorize('delete', $user , $song);
|
|
$this->authorize('delete', $song);
|
|
|
|
if ($song) {
|
|
// Delete the related file
|
|
if (Storage::exists($song->path)) {
|
|
Storage::delete($song->path);
|
|
}
|
|
Song::destroy($id);
|
|
}
|
|
return response()->noContent(200);
|
|
}
|
|
/**
|
|
* @param int $id
|
|
*/
|
|
public function stream($id)
|
|
{
|
|
$song = Song::find($id);
|
|
|
|
// Stream specified song
|
|
$this->authorize('view', $song);
|
|
|
|
if ($song && Storage::exists($song->path)) {
|
|
$file = Storage::path($song->path);
|
|
return response()->stream(function () use ($file) {
|
|
$stream = fopen($file, 'rb');
|
|
fpassthru($stream);
|
|
fclose($stream);
|
|
}, 200, [
|
|
'Content-Type' => 'audio/mpeg',
|
|
'Content-Disposition' => 'inline; filename="' . $file . '"',
|
|
'Accept-Ranges' => 'bytes',
|
|
]);
|
|
}
|
|
}
|
|
}
|