Compare commits

..

2 commits
v1.0.0 ... main

Author SHA1 Message Date
7a4832001f Nachrichten 1.2.0: Nutzt die Vorlage „füllt den Bildschirm“ (ab Inhaus 0.50 ohne Fußzeile)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 05:37:41 +00:00
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
11 changed files with 209 additions and 28 deletions

View file

@ -35,17 +35,52 @@ Voraussetzung: Inhaus **0.39.0** oder neuer.
## Echtzeit (optional)
Ohne Einrichtung fragt der Chat alle 3 Sekunden (im Hintergrund seltener) nach Neuem – das läuft auf jedem Webspace.
Für sofortige Zustellung einen Pusher-kompatiblen Dienst eintragen:
Für sofortige Zustellung braucht es einen Pusher-kompatiblen Dienst. Über ihn geht nur das Signal „es gibt Neues“,
nie Nachrichteninhalte. Auf einem reinen Webspace (ohne dauerhaft laufende Prozesse) ist **pusher.com** der
einfachste Weg:
- **pusher.com**: App anlegen, App-ID, Key, Secret und Cluster eintragen, Server leer lassen.
- **Laravel Reverb / Soketi** (eigener Server): App-ID, Key, Secret, Server (z. B. `ws.example.org`), Port (443).
Der Server muss vom Browser (WebSocket) und vom Portal (HTTP) aus erreichbar sein.
1. Kostenloses Konto unter <https://dashboard.pusher.com> anlegen („Channels“, Sandbox-Tarif:
200 000 Signale/Tag, 100 gleichzeitige Verbindungen – für die meisten Häuser genug).
2. „Create app“: Name z. B. „Inhaus“, Cluster **eu** (Server in der EU), Frontend „Vanilla JS“, Backend „Laravel“.
3. Unter „App Keys“ stehen `app_id`, `key`, `secret` und `cluster`.
4. Im Backend unter **Portal → Nachrichten → Echtzeit** einschalten, App-ID, Key, Secret und Cluster (`eu`)
eintragen, **Server leer lassen**, speichern.
5. Oben auf **„Echtzeit prüfen“** klicken – „Verbindung steht“ heißt: fertig.
Alternativ ein eigener Server mit **Laravel Reverb** oder **Soketi**: App-ID, Key, Secret, Server
(z. B. `ws.example.org`) und Port (443) eintragen. Der Server muss vom Browser bzw. der App (WebSocket) und
vom Portal (HTTP) aus erreichbar sein. Die Inhaus-App nutzt dieselbe Einrichtung automatisch.
## GIPHY (optional)
Die eigene GIF-Sammlung (Backend → Chat-GIFs) funktioniert ohne Einrichtung. Für die Suche bei GIPHY:
1. Unter <https://developers.giphy.com/dashboard/> anmelden, „Create an App“ → **API** (nicht SDK) wählen.
2. Den angezeigten API-Key im Backend unter **Portal → Nachrichten → GIFs** eintragen und speichern.
3. Oben auf **„GIPHY prüfen“** klicken.
Ein neuer Schlüssel ist ein Beta-Schlüssel (100 Abrufe pro Stunde); für mehr bei GIPHY ein „Production“-Upgrade
beantragen. Suchbegriffe gehen dabei an GIPHY, die GIFs lädt der Browser von dort.
## Schnittstelle für die App
Unter `/api/v1/chat/…` (Token nötig): `GET conversations`, `POST direct {user_id}`,
`GET conversations/{id}/messages?vor=`, `POST conversations/{id}/messages {body, gif_url, reply_to, files[]}`,
`POST conversations/{id}/read {message_id}`, `GET unread`.
Unter `/api/v1/chat/…` (Token nötig), dieselben Regeln wie im Portal:
| Methode | Pfad | Zweck |
|---|---|---|
| GET | `config` | eigene Person, `can_create_groups`, `giphy`, `realtime` (ohne Secret), `reactions`, `max_upload_mb` |
| GET | `conversations` | Gesprächsliste |
| POST | `direct {user_id}` / `groups {name, members[]}` | Direktnachricht öffnen / Gruppenchat anlegen (Recht nötig) |
| DELETE | `conversations/{id}` | Gespräch verlassen |
| GET | `conversations/{id}/messages?vor=` | 40 Nachrichten, ältere mit `vor` |
| POST | `conversations/{id}/messages {body, gif_url, reply_to, files[]}` | senden (JSON oder multipart) |
| POST | `conversations/{id}/read {message_id}` / `typing` | gelesen / „schreibt …“ |
| PUT / DELETE | `messages/{id}` | bearbeiten / löschen |
| POST | `messages/{id}/reaction {emoji}` | Reaktion umschalten |
| GET | `updates?seit=&offen=&nach=` | „Gibt es Neues?“ – wie im Portal |
| GET | `unread`, `gifs?q=` | ungelesene Nachrichten, GIF-Suche |
| POST | `realtime/auth {socket_id, channel_name}` | Anmeldung am privaten Echtzeit-Kanal |
| GET | `attachments/{id}` | Anhang (Adressen in den Antworten zeigen bei API-Aufrufen hierher) |
## Entwicklung

2
dist/pages/Index.js vendored

File diff suppressed because one or more lines are too long

View file

@ -1,7 +1,7 @@
{
"slug": "chat",
"name": "Nachrichten",
"version": "1.0.0",
"version": "1.2.0",
"description": "Direktnachrichten und Gruppenchats im Portal – mit Anhängen, Bildern, GIFs (eigene Sammlung und optional GIPHY), Emojis, Reaktionen, Antworten und Gelesen-Status. Gruppen anlegen nur mit Recht; auf Wunsch Echtzeit über einen Pusher-kompatiblen Dienst.",
"author": "Loheide",
"namespace": "Inhaus\\Plugins\\Chat\\",

View file

@ -91,7 +91,7 @@ function onRead({ id, unread }) {
</script>
<template>
<AppLayout title="Nachrichten">
<AppLayout title="Nachrichten" width="app" :header="false">
<div class="ih:-mx-4 ih:-my-6 ih:flex ih:h-[calc(100dvh-4rem)] ih:overflow-hidden ih:border-y ih:bg-card ih:lg:mx-0 ih:lg:my-0 ih:lg:h-[calc(100dvh-8.5rem)] ih:lg:rounded-xl ih:lg:border ih:lg:shadow-xs">
<aside class="ih:w-full ih:shrink-0 ih:border-r ih:lg:block ih:lg:w-80 ih:xl:w-96" :class="active ? 'ih:hidden' : 'ih:block'">
<ConversationList :conversations="list" :active-id="activeId" :can-create-groups="canCreateGroups" @open="open" @new-chat="dialog = 'chat'" @new-group="dialog = 'group'" />

View file

@ -5,11 +5,22 @@ use Inhaus\Plugins\Chat\Http\Controllers\ConversationController;
use Inhaus\Plugins\Chat\Http\Controllers\MessageController;
// /api/v1/chat … für die Inhaus-App (Token nötig) – dieselben Regeln wie im Portal
Route::prefix('chat')->group(function () {
Route::get('/conversations', [ConversationController::class, 'index']);
Route::post('/direct', [ConversationController::class, 'direct'])->middleware('throttle:30,1');
Route::get('/conversations/{conversation}/messages', [MessageController::class, 'index']);
Route::post('/conversations/{conversation}/messages', [MessageController::class, 'store'])->middleware('throttle:60,1');
Route::post('/conversations/{conversation}/read', [MessageController::class, 'read']);
Route::get('/unread', [MessageController::class, 'unread']);
Route::prefix('chat')->name('chat.app.')->group(function () {
Route::get('/config', [ConversationController::class, 'config'])->name('config');
Route::get('/conversations', [ConversationController::class, 'index'])->name('conversations');
Route::post('/direct', [ConversationController::class, 'direct'])->middleware('throttle:30,1')->name('direct');
Route::post('/groups', [ConversationController::class, 'createGroup'])->middleware('throttle:10,1')->name('groups');
Route::delete('/conversations/{conversation}', [ConversationController::class, 'leave'])->name('leave');
Route::get('/conversations/{conversation}/messages', [MessageController::class, 'index'])->name('messages');
Route::post('/conversations/{conversation}/messages', [MessageController::class, 'store'])->middleware('throttle:60,1')->name('send');
Route::post('/conversations/{conversation}/read', [MessageController::class, 'read'])->name('read');
Route::post('/conversations/{conversation}/typing', [MessageController::class, 'typing'])->middleware('throttle:60,1')->name('typing');
Route::put('/messages/{message}', [MessageController::class, 'update'])->name('edit');
Route::delete('/messages/{message}', [MessageController::class, 'destroy'])->name('delete');
Route::post('/messages/{message}/reaction', [MessageController::class, 'react'])->middleware('throttle:60,1')->name('react');
Route::get('/updates', [MessageController::class, 'updates'])->middleware('throttle:120,1')->name('updates');
Route::get('/unread', [MessageController::class, 'unread'])->name('unread');
Route::get('/gifs', [MessageController::class, 'gifs'])->middleware('throttle:60,1')->name('gifs');
Route::post('/realtime/auth', [MessageController::class, 'realtimeAuth'])->middleware('throttle:30,1')->name('realtime');
Route::get('/attachments/{attachment}', [MessageController::class, 'attachment'])->name('attachment');
});

View file

@ -18,6 +18,8 @@ use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Validation\ValidationException;
use Inhaus\Plugins\Chat\Gifs;
use Inhaus\Plugins\Chat\Realtime;
use UnitEnum;
/**
@ -138,9 +140,23 @@ class ChatSettings extends Page
Notification::make()->success()->title('Gespeichert')->send();
}
/**
* @param array{ok: bool, message: string} $result
*/
private function report(array $result): void
{
Notification::make()->{$result['ok'] ? 'success' : 'danger'}()->title($result['ok'] ? 'Verbindung steht' : 'Das klappt noch nicht')->body($result['message'])->send();
}
protected function getHeaderActions(): array
{
return [
Action::make('checkRealtime')->label('Echtzeit prüfen')->color('gray')->icon(Heroicon::OutlinedSignal)
->visible(fn () => app(Realtime::class)->enabled())
->action(fn () => $this->report(app(Realtime::class)->check())),
Action::make('checkGiphy')->label('GIPHY prüfen')->color('gray')->icon(Heroicon::OutlinedGif)
->visible(fn () => app(Gifs::class)->giphyEnabled())
->action(fn () => $this->report(app(Gifs::class)->checkGiphy())),
Action::make('forgetGiphy')->label('GIPHY ausschalten')->color('gray')
->visible(fn () => filled(app(Settings::class)->get('chat.giphy_key')))
->requiresConfirmation()

View file

@ -56,6 +56,34 @@ class Gifs
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>>
*/

View file

@ -44,6 +44,19 @@ class ConversationController extends Controller
]);
}
/** Einstellungen für die App (entspricht den Seitendaten im Portal) */
public function config(Request $request, Gifs $gifs, Realtime $realtime): JsonResponse
{
return response()->json([
'me' => Presenter::person($request->user()),
'can_create_groups' => $request->user()->can('chat.groups.create'),
'giphy' => $gifs->giphyEnabled(),
'realtime' => $realtime->clientConfig(),
'reactions' => Reaction::EMOJIS,
'max_upload_mb' => (int) app(Settings::class)->get('chat.max_upload_mb', 25),
]);
}
public function index(Request $request): JsonResponse
{
return response()->json(['conversations' => $this->list($request->user())]);

View file

@ -14,6 +14,12 @@ class Presenter
/**
* @return array<string, mixed>
*/
/** Die App lädt Anhänge mit ihrem Token über die API, der Browser über die Sitzung */
public static function attachmentUrl(Attachment $attachment): string
{
return request()->is('api/*') ? route('chat.app.attachment', $attachment) : route('chat.attachment', $attachment);
}
public static function person(?User $user): ?array
{
return $user ? ['id' => $user->id, 'name' => $user->name, 'first_name' => $user->first_name, 'initials' => $user->initials, 'avatar_url' => $user->avatarUrl(96), 'job_title' => $user->job_title] : null;
@ -100,7 +106,7 @@ class Presenter
'image' => $a->isImage(),
'width' => $a->width,
'height' => $a->height,
'url' => route('chat.attachment', $a),
'url' => self::attachmentUrl($a),
])->all(),
'reactions' => $m->reactions->groupBy('emoji')->map(fn ($group, $emoji) => [
'emoji' => $emoji,

View file

@ -77,6 +77,32 @@ class Realtime
return ['auth' => $this->settings->get('chat.realtime.key').':'.hash_hmac('sha256', $socketId.':'.$channel, $this->secret())];
}
/**
* Verbindung prüfen (Backend): fragt beim Dienst die offenen Kanäle ab – klappt das,
* stimmen Server, App-ID, Key und Secret.
*
* @return array{ok: bool, message: string}
*/
public function check(): array
{
if (! $this->enabled()) {
return ['ok' => false, 'message' => 'Echtzeit ist nicht eingeschaltet oder unvollständig eingerichtet.'];
}
try {
$response = Http::timeout(5)->acceptJson()->get($this->signedUrl('GET', '/apps/'.$this->settings->get('chat.realtime.app_id').'/channels'));
} catch (Throwable $e) {
return ['ok' => false, 'message' => 'Der Dienst ist nicht erreichbar: '.mb_substr($e->getMessage(), 0, 160)];
}
return match (true) {
$response->successful() => ['ok' => true, 'message' => 'Verbindung steht – Nachrichten kommen jetzt sofort an.'],
in_array($response->status(), [401, 403], true) => ['ok' => false, 'message' => 'Der Dienst lehnt die Anmeldung ab – bitte Key und Secret prüfen.'],
$response->status() === 404 => ['ok' => false, 'message' => 'Diese App-ID kennt der Dienst nicht.'],
default => ['ok' => false, 'message' => 'Unerwartete Antwort des Dienstes (HTTP '.$response->status().').'],
};
}
/**
* @param list<string> $channels
* @param array<string, mixed> $data
@ -84,24 +110,30 @@ class Realtime
private function trigger(array $channels, string $event, array $data): void
{
$body = json_encode(['name' => $event, 'channels' => $channels, 'data' => json_encode($data)]);
$path = '/apps/'.$this->settings->get('chat.realtime.app_id').'/events';
$query = [
'auth_key' => (string) $this->settings->get('chat.realtime.key'),
'auth_timestamp' => (string) time(),
'auth_version' => '1.0',
'body_md5' => md5($body),
];
ksort($query);
$query['auth_signature'] = hash_hmac('sha256', "POST\n{$path}\n".http_build_query($query), $this->secret());
try {
Http::timeout(3)->withBody($body, 'application/json')->post($this->baseUrl().$path.'?'.http_build_query($query));
Http::timeout(3)->withBody($body, 'application/json')->post($this->signedUrl('POST', '/apps/'.$this->settings->get('chat.realtime.app_id').'/events', $body));
} catch (Throwable $e) {
// Echtzeit ist nur eine Beschleunigung – die Oberfläche fragt ohnehin regelmäßig nach
report($e);
}
}
/** Adresse mit Signatur nach dem Pusher-HTTP-Protokoll */
private function signedUrl(string $method, string $path, ?string $body = null): string
{
$query = [
'auth_key' => (string) $this->settings->get('chat.realtime.key'),
'auth_timestamp' => (string) time(),
'auth_version' => '1.0',
...($body === null ? [] : ['body_md5' => md5($body)]),
];
ksort($query);
$query['auth_signature'] = hash_hmac('sha256', "{$method}\n{$path}\n".http_build_query($query), $this->secret());
return $this->baseUrl().$path.'?'.http_build_query($query);
}
private function baseUrl(): string
{
$scheme = $this->settings->get('chat.realtime.scheme') ?: 'https';

View file

@ -13,10 +13,12 @@ use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Inertia\Testing\AssertableInertia as Assert;
use Inhaus\Plugins\Chat\Gifs;
use Inhaus\Plugins\Chat\Models\Conversation;
use Inhaus\Plugins\Chat\Models\Gif;
use Inhaus\Plugins\Chat\Models\Message;
use Inhaus\Plugins\Chat\Realtime;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
/**
@ -206,4 +208,42 @@ class ChatTest extends TestCase
->assertOk()->assertJsonPath('auth', 'k:'.hash_hmac('sha256', '123.456:'.Realtime::channel($ada->id), 's3cret'));
$this->actingAs($ada)->postJson('/chat/api/echtzeit/anmelden', ['socket_id' => '123.456', 'channel_name' => Realtime::channel($bob->id)])->assertForbidden();
}
public function test_connection_checks_for_realtime_and_giphy(): void
{
$realtime = app(Realtime::class);
$this->assertFalse($realtime->check()['ok']);
app(Settings::class)->setMany(['chat.realtime.enabled' => true, 'chat.realtime.app_id' => '42', 'chat.realtime.key' => 'k', 'chat.realtime.secret' => Crypt::encryptString('s3cret'), 'chat.realtime.host' => 'ws.example.org']);
Http::fake(['ws.example.org/apps/42/channels*' => Http::sequence()->push(['channels' => []])->push(['error' => 'Invalid signature'], 401)]);
$this->assertTrue($realtime->check()['ok']);
$this->assertStringContainsString('Key und Secret', $realtime->check()['message']);
Http::assertSent(fn ($r) => $r->method() === 'GET' && str_contains($r->url(), 'auth_signature=') && ! str_contains($r->url(), 'body_md5'));
$gifs = app(Gifs::class);
$this->assertFalse($gifs->checkGiphy()['ok']);
app(Settings::class)->set('chat.giphy_key', Crypt::encryptString('gk'));
Http::fake(['api.giphy.com/*' => Http::sequence()->push(['data' => []])->push(['message' => 'Unauthorized'], 401)]);
$this->assertTrue($gifs->checkGiphy()['ok']);
$this->assertFalse($gifs->checkGiphy()['ok']);
}
public function test_app_api_with_token(): void
{
[$ada, $bob] = User::factory()->count(2)->create()->all();
Sanctum::actingAs($ada);
$this->getJson('/api/v1/chat/config')->assertOk()->assertJsonPath('me.id', $ada->id)->assertJsonPath('realtime', null)->assertJsonPath('can_create_groups', false);
$id = $this->postJson('/api/v1/chat/direct', ['user_id' => $bob->id])->assertOk()->json('id');
$url = $this->post("/api/v1/chat/conversations/{$id}/messages", ['body' => 'Hallo aus der App', 'files' => [UploadedFile::fake()->image('foto.jpg', 40, 40)]], ['Accept' => 'application/json'])
->assertCreated()->json('message.attachments.0.url');
$this->assertStringContainsString('/api/v1/chat/attachments/', $url);
$this->get($url)->assertOk();
$this->getJson('/api/v1/chat/updates?offen='.$id)->assertOk()->assertJsonPath('messages.0.body', 'Hallo aus der App');
$this->getJson('/api/v1/chat/conversations')->assertJsonPath('conversations.0.person.id', $bob->id);
Sanctum::actingAs(User::factory()->create());
$this->get($url)->assertNotFound();
}
}