inhaus-plugin-chat/src/Gifs.php
Friederich Loheide 5f71c3e250 Nachrichten 1.1.0: Schnittstelle für die App, Verbindung prüfen
- /api/v1/chat: config, Gruppenchats, verlassen, bearbeiten, löschen, Reaktionen,
  „Gibt es Neues?“, „schreibt …“, GIFs, Echtzeit-Anmeldung und Anhänge mit Token
- Anhang-Adressen zeigen bei API-Aufrufen auf die API (Token statt Sitzung)
- Backend: „Echtzeit prüfen“ und „GIPHY prüfen“ melden sofort, ob die Zugangsdaten stimmen
- README: Schritt-für-Schritt-Einrichtung für pusher.com und GIPHY

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 20:10:35 +00:00

118 lines
4.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Inhaus\Plugins\Chat;
use App\Support\Settings;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Inhaus\Plugins\Chat\Models\Gif;
use Throwable;
/**
* GIFs: eigene Sammlung (Backend) und – wenn ein Schlüssel eingetragen ist – die Suche bei GIPHY.
* Bei GIPHY gehen Suchbegriffe an den Dienst, die Bilder lädt der Browser von dort.
*/
class Gifs
{
public const DISK = 'uploads';
public const FOLDER = 'chat-gifs';
public function __construct(private readonly Settings $settings) {}
public function giphyEnabled(): bool
{
return filled($this->settings->get('chat.giphy_key'));
}
/**
* @return list<array{url: string, preview: string, width: ?int, height: ?int, title: string, source: string}>
*/
public function search(string $query): array
{
$query = trim(mb_substr($query, 0, 50));
$own = Gif::query()
->when($query !== '', fn ($q) => $q->where(fn ($q) => $q->where('title', 'like', '%'.addcslashes($query, '%_\\').'%')->orWhere('tags', 'like', '%'.addcslashes($query, '%_\\').'%')))
->latest()->limit(30)->get()
->map(fn (Gif $g) => ['url' => $this->ownUrl($g->path), 'preview' => $this->ownUrl($g->path), 'width' => $g->width, 'height' => $g->height, 'title' => $g->title, 'source' => 'own'])
->all();
return [...$own, ...$this->giphy($query)];
}
public function isAllowedUrl(string $url): bool
{
// Eigene Sammlung: nur GIFs, die es dort wirklich gibt
if (str_starts_with($url, $this->ownUrl('').'/')) {
return Gif::query()->where('path', self::FOLDER.'/'.basename(parse_url($url, PHP_URL_PATH) ?: ''))->exists();
}
return $this->giphyEnabled() && (bool) preg_match('#^https://media[0-9]?\.giphy\.com/media/[A-Za-z0-9]+/[A-Za-z0-9_.-]+\.(gif|webp)(\?[A-Za-z0-9=&_.-]*)?$#', $url);
}
public function ownUrl(string $path): string
{
return $path === '' ? Storage::disk(self::DISK)->url(self::FOLDER) : Storage::disk(self::DISK)->url($path);
}
/**
* Schlüssel prüfen (Backend) – ein Abruf der Trends.
*
* @return array{ok: bool, message: string}
*/
public function checkGiphy(): array
{
if (! $this->giphyEnabled()) {
return ['ok' => false, 'message' => 'Es ist kein GIPHY-Schlüssel gespeichert.'];
}
try {
$response = Http::timeout(5)->acceptJson()->get('https://api.giphy.com/v1/gifs/trending', [
'api_key' => Crypt::decryptString((string) $this->settings->get('chat.giphy_key')),
'limit' => 1,
]);
} catch (Throwable $e) {
return ['ok' => false, 'message' => 'GIPHY ist nicht erreichbar: '.mb_substr($e->getMessage(), 0, 160)];
}
return match (true) {
$response->successful() => ['ok' => true, 'message' => 'Der Schlüssel funktioniert – die GIF-Suche im Chat findet jetzt auch GIPHY.'],
in_array($response->status(), [401, 403], true) => ['ok' => false, 'message' => 'GIPHY lehnt den Schlüssel ab – bitte prüfen.'],
$response->status() === 429 => ['ok' => false, 'message' => 'Der Schlüssel funktioniert, das Kontingent ist aber gerade aufgebraucht (Beta-Schlüssel: 100 Abrufe pro Stunde).'],
default => ['ok' => false, 'message' => 'Unerwartete Antwort von GIPHY (HTTP '.$response->status().').'],
};
}
/**
* @return list<array<string, mixed>>
*/
private function giphy(string $query): array
{
if (! $this->giphyEnabled()) {
return [];
}
try {
$key = Crypt::decryptString((string) $this->settings->get('chat.giphy_key'));
$response = Http::timeout(5)->acceptJson()->get('https://api.giphy.com/v1/gifs/'.($query === '' ? 'trending' : 'search'), array_filter([
'api_key' => $key,
'q' => $query ?: null,
'limit' => 24,
'rating' => $this->settings->get('chat.giphy_rating', 'g'),
'lang' => 'de',
]));
} catch (Throwable) {
return [];
}
return collect((array) $response->json('data'))->map(fn ($gif) => [
'url' => (string) data_get($gif, 'images.fixed_height.url'),
'preview' => (string) (data_get($gif, 'images.fixed_height_small.url') ?: data_get($gif, 'images.fixed_height.url')),
'width' => (int) data_get($gif, 'images.fixed_height.width') ?: null,
'height' => (int) data_get($gif, 'images.fixed_height.height') ?: null,
'title' => (string) data_get($gif, 'title', ''),
'source' => 'giphy',
])->filter(fn ($gif) => $this->isAllowedUrl($gif['url']))->values()->all();
}
}