aboutsummaryrefslogtreecommitdiff
path: root/app/Http/Controllers/MusicController.php
blob: 5e31d864e74becc79111bcb8978f6d20138e538f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\View\View;

class MusicController extends Controller
{
    public function getCurrentTrack() {
        // If it's already cached just return that
        if (Cache::has('current_track')) {
            return Cache::get('current_track');
        }

        $response = Http::withQueryParameters([
            'method' => 'user.getrecenttracks',
            'user' => Config::get('services.lastfm.user'),
            'format' => 'json',
            'nowplaying' => 'true',
            'api_key' => Config::get('services.lastfm.key')
        ])->get('https://ws.audioscrobbler.com/2.0/');
        $data = $response->json();
        error_log($response->body());
        $track_data = $data["recenttracks"]["track"][0];
        $current_track = [
            'title' => $track_data["name"],
            'artist' => $track_data["artist"]["#text"],
            'url' => $track_data["url"],
        ];
        Cache::put('current_track', $current_track, now()->addSeconds(15));
        return $current_track;
    }

    public function getTopTracks() {
        // If it's already cached just return that
        if (Cache::has('top_tracks')) {
            return Cache::get('top_tracks');
        }

        $response = Http::withQueryParameters([
            'method' => 'user.gettoptracks',
            'user' => Config::get('services.lastfm.user'),
            'format' => 'json',
            'period' => '1month',
            'limit' => 10,
            'api_key' => Config::get('services.lastfm.key')
        ])->get('https://ws.audioscrobbler.com/2.0/');
        $data = $response->json();
        $topTracks = [];
        foreach ($data["toptracks"]["track"] as $track) {
            $topTracks[] = [
                'title' => $track["name"],
                'artist' => $track["artist"]["name"],
                'url' => $track["url"],
                'plays' => $track["playcount"],
            ];
        }
        Cache::put('top_tracks', $topTracks, now()->addSeconds(15));
        return $topTracks;
    }
    public function show() : View {
        return view('music')
            ->with('current_track', $this->getCurrentTrack())
            ->with('top_tracks', $this->getTopTracks());
    }
}