aboutsummaryrefslogtreecommitdiff
path: root/app/View/Components/DiscordStatus.php
blob: fac06ae2840dfcb57407e8b336d3114e1dfdec77 (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
<?php

namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\View\Component;

class DiscordStatus extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Returns current Discord presence from Lanyard API
     * @return array|mixed
     */
    public function getDiscordPresence(): mixed {
        // If it's already cached just return that
        if (Cache::has('discord_presence')) {
            return Cache::get('discord_presence');
        }

        $response = Http::get('https://api.lanyard.rest/v1/users/' . Config::get('services.lanyard.user_id'));
        $data = $response->json();
        $presence = $data["data"];
        Cache::put('discord_presence', $presence, now()->addSeconds(60));
        return $presence;
    }

    public function getOnlineStatus(): array {
        $presence = $this->getDiscordPresence();
        return match ($presence["discord_status"]) {
            "online", "dnd" => [
                "text" => "online",
                "color" => "#02c83a"
            ],
            "idle" => [
                "text" => "away",
                "color" => "#d77c20"
            ],
            default => [
                "text" => "offline",
                "color" => "#ca3329"
            ],
        };
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.discord-status', [
            'status' => $this->getOnlineStatus(),
        ]);
    }
}