Nachrichten-Plugin 1.0.0: Direktnachrichten, Gruppen, Anhänge, GIFs, Emojis

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-27 16:34:53 +00:00
commit 2844452002
55 changed files with 5448 additions and 0 deletions

317
src/Chat.php Normal file
View file

@ -0,0 +1,317 @@
<?php
namespace Inhaus\Plugins\Chat;
use App\Models\User;
use App\Plugins\PluginAccess;
use App\Support\BlockedFiles;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inhaus\Plugins\Chat\Models\Attachment;
use Inhaus\Plugins\Chat\Models\Conversation;
use Inhaus\Plugins\Chat\Models\Message;
use Inhaus\Plugins\Chat\Models\Participant;
use Inhaus\Plugins\Chat\Models\Reaction;
/**
* Nachrichten: Direktgespräche und Gruppen. Die Administration kann Gespräche nicht mitlesen –
* Zugriff haben nur die Mitglieder.
*/
class Chat
{
public const DISK = 'local';
public const MAX_FILES = 10;
public function __construct(private readonly Realtime $realtime, private readonly Notifier $notifier) {}
public function canReach(User $user): bool
{
return $user->is_active && app(PluginAccess::class)->allows('chat', $user);
}
/** Direktgespräch mit einer Person – gibt es schon eins, wird es wieder sichtbar */
public function direct(User $me, User $other): Conversation
{
if ($me->is($other) || ! $this->canReach($other)) {
throw ValidationException::withMessages(['user' => 'Mit dieser Person ist kein Chat möglich.']);
}
return DB::transaction(function () use ($me, $other) {
$conversation = Conversation::query()->firstOrCreate(
['direct_key' => Conversation::directKey($me->id, $other->id)],
['type' => 'direct', 'created_by' => $me->id],
);
if ($conversation->wasRecentlyCreated) {
foreach ([$me, $other] as $user) {
$conversation->participants()->create(['user_id' => $user->id, 'role' => 'member', 'joined_at' => now()]);
}
} else {
// Nur bei mir wieder einblenden – beim Gegenüber erst mit der nächsten Nachricht
$conversation->participants()->where('user_id', $me->id)->update(['left_at' => null]);
}
return $conversation;
});
}
/**
* @param list<int> $userIds
*/
public function createGroup(User $creator, string $name, array $userIds): Conversation
{
$members = $this->reachable($userIds, $creator);
if ($members->isEmpty()) {
throw ValidationException::withMessages(['members' => 'Bitte mindestens eine weitere Person hinzufügen.']);
}
$conversation = DB::transaction(function () use ($creator, $name, $members) {
$conversation = Conversation::query()->create(['type' => 'group', 'name' => $name, 'created_by' => $creator->id]);
$conversation->participants()->create(['user_id' => $creator->id, 'role' => 'admin', 'joined_at' => now()]);
foreach ($members as $member) {
$conversation->participants()->create(['user_id' => $member->id, 'role' => 'member', 'joined_at' => now()]);
}
return $conversation;
});
$this->system($conversation, $creator, "{$creator->name} hat die Gruppe „{$name}“ erstellt.");
return $conversation;
}
/**
* @param list<int> $userIds
*/
public function addMembers(Conversation $conversation, User $actor, array $userIds): void
{
$this->ensureAdmin($conversation, $actor);
$added = [];
foreach ($this->reachable($userIds, $actor) as $user) {
$existing = $conversation->participants()->where('user_id', $user->id)->first();
if ($existing && $existing->left_at === null) {
continue;
}
Participant::query()->updateOrInsert(
['conversation_id' => $conversation->id, 'user_id' => $user->id],
['role' => 'member', 'joined_at' => now(), 'left_at' => null, 'last_read_message_id' => $conversation->last_message_id],
);
$added[] = $user->name;
}
if ($added) {
$this->system($conversation, $actor, $actor->name.' hat '.implode(', ', $added).' hinzugefügt.');
}
}
/** Entfernen (Gruppen-Admins) oder selbst austreten */
public function removeMember(Conversation $conversation, User $actor, User $user): void
{
abort_unless($conversation->isGroup(), 422);
if (! $actor->is($user)) {
$this->ensureAdmin($conversation, $actor);
}
$participant = $conversation->participant($user);
if (! $participant) {
return;
}
$participant->forceFill(['left_at' => now(), 'role' => 'member'])->save();
// Letzte Admin-Person weg: die am längsten dabei ist, übernimmt
if (! $conversation->participants()->whereNull('left_at')->where('role', 'admin')->exists()) {
$next = $conversation->participants()->whereNull('left_at')->orderBy('joined_at')->first();
$next?->forceFill(['role' => 'admin'])->save();
}
$this->system($conversation, $actor, $actor->is($user) ? "{$user->name} hat die Gruppe verlassen." : "{$actor->name} hat {$user->name} entfernt.");
}
public function rename(Conversation $conversation, User $actor, string $name): void
{
$this->ensureAdmin($conversation, $actor);
$conversation->update(['name' => $name]);
$this->system($conversation, $actor, "{$actor->name} hat die Gruppe in „{$name}“ umbenannt.");
}
public function setAdmin(Conversation $conversation, User $actor, User $user, bool $admin): void
{
$this->ensureAdmin($conversation, $actor);
$conversation->participant($user)?->forceFill(['role' => $admin ? 'admin' : 'member'])->save();
$conversation->touch();
$this->realtime->notify($conversation);
}
/** Direktgespräch aus der eigenen Liste entfernen – kommt mit der nächsten Nachricht zurück */
public function hide(Conversation $conversation, User $user): void
{
$conversation->participant($user)?->forceFill(['left_at' => now()])->save();
}
/**
* @param list<UploadedFile> $files
*/
public function send(Conversation $conversation, User $user, ?string $body, ?string $gifUrl = null, array $files = [], ?int $replyTo = null): Message
{
$body = filled($body) ? trim($body) : null;
if ($body === null && $gifUrl === null && $files === []) {
throw ValidationException::withMessages(['body' => 'Die Nachricht ist leer.']);
}
if ($replyTo && ! $conversation->messages()->whereKey($replyTo)->exists()) {
$replyTo = null;
}
$message = DB::transaction(function () use ($conversation, $user, $body, $gifUrl, $files, $replyTo) {
$message = $conversation->messages()->create([
'user_id' => $user->id,
'kind' => $gifUrl ? 'gif' : 'text',
'body' => $body,
'gif_url' => $gifUrl,
'reply_to_id' => $replyTo,
]);
foreach ($files as $file) {
$this->storeAttachment($message, $file);
}
$conversation->forceFill(['last_message_id' => $message->id, 'last_message_at' => $message->created_at])->save();
$conversation->participants()->where('user_id', $user->id)->update(['last_read_message_id' => $message->id]);
// Ausgeblendete Direktgespräche tauchen wieder auf
if (! $conversation->isGroup()) {
$conversation->participants()->update(['left_at' => null]);
}
return $message;
});
$this->realtime->notify($conversation);
$this->notifier->newMessage($conversation, $message, $user);
return $message;
}
public function edit(Message $message, User $user, string $body): void
{
abort_unless($message->user_id === $user->id && $message->deleted_at === null && $message->kind === 'text', 403);
$message->update(['body' => trim($body), 'edited_at' => now()]);
$this->realtime->notify($message->conversation);
}
public function delete(Message $message, User $user): void
{
abort_unless($message->user_id === $user->id, 403);
foreach ($message->attachments as $attachment) {
Storage::disk(self::DISK)->delete($attachment->path);
}
$message->attachments()->delete();
$message->reactions()->delete();
$message->update(['body' => null, 'gif_url' => null, 'deleted_at' => now()]);
$this->realtime->notify($message->conversation);
}
public function react(Message $message, User $user, string $emoji): void
{
abort_unless(in_array($emoji, Reaction::EMOJIS, true) && $message->deleted_at === null, 422);
$existing = Reaction::query()->where(['message_id' => $message->id, 'user_id' => $user->id, 'emoji' => $emoji]);
$existing->exists() ? $existing->delete() : Reaction::query()->insert(['message_id' => $message->id, 'user_id' => $user->id, 'emoji' => $emoji]);
$message->touch();
$this->realtime->notify($message->conversation);
}
public function markRead(Conversation $conversation, User $user, int $messageId): void
{
$conversation->participants()->where('user_id', $user->id)
->where(fn ($q) => $q->whereNull('last_read_message_id')->orWhere('last_read_message_id', '<', $messageId))
->update(['last_read_message_id' => min($messageId, (int) $conversation->last_message_id)]);
}
/**
* Ungelesene Nachrichten je Gespräch.
*
* @return array<int, int>
*/
public function unread(User $user): array
{
return DB::table('chat_participants as p')
->join('chat_messages as m', 'm.conversation_id', '=', 'p.conversation_id')
->where('p.user_id', $user->id)->whereNull('p.left_at')
->whereColumn('m.id', '>', DB::raw('COALESCE(p.last_read_message_id, 0)'))
->where(fn ($q) => $q->where('m.user_id', '!=', $user->id)->orWhereNull('m.user_id'))
->where('m.kind', '!=', 'system')->whereNull('m.deleted_at')
->groupBy('p.conversation_id')
->selectRaw('p.conversation_id, count(*) as c')
->pluck('c', 'p.conversation_id')->map(fn ($c) => (int) $c)->all();
}
public function member(Conversation $conversation, User $user): Participant
{
$participant = $conversation->participant($user);
abort_unless($participant !== null && $this->canReach($user), 404);
return $participant;
}
private function ensureAdmin(Conversation $conversation, User $user): void
{
abort_unless($conversation->isGroup() && $this->member($conversation, $user)->isAdmin(), 403);
}
private function system(Conversation $conversation, User $actor, string $text): void
{
$message = $conversation->messages()->create(['user_id' => $actor->id, 'kind' => 'system', 'body' => $text]);
$conversation->forceFill(['last_message_id' => $message->id, 'last_message_at' => $message->created_at])->save();
$this->realtime->notify($conversation);
}
/**
* @param list<int> $ids
* @return Collection<int, User>
*/
private function reachable(array $ids, User $actor)
{
return User::query()->whereKey(array_slice(array_unique(array_map('intval', $ids)), 0, 200))->whereKeyNot($actor->id)->get()
->filter(fn (User $u) => $this->canReach($u))->values();
}
private function storeAttachment(Message $message, UploadedFile $file): void
{
$name = Str::limit(preg_replace('/[^\pL\pN ._()-]+/u', '_', $file->getClientOriginalName()) ?: 'Datei', 150, '');
$extension = strtolower($file->guessExtension() ?: $file->getClientOriginalExtension());
if (in_array($extension, BlockedFiles::EXTENSIONS, true) || in_array(strtolower($file->getClientOriginalExtension()), BlockedFiles::EXTENSIONS, true)) {
throw ValidationException::withMessages(['files' => "Dateien dieses Typs („{$name}“) sind nicht erlaubt."]);
}
$mime = $file->getMimeType() ?: 'application/octet-stream';
$path = $file->storeAs('chat/'.$message->conversation_id, Str::random(32).($extension ? '.'.$extension : ''), self::DISK);
$size = in_array($mime, Attachment::IMAGE_TYPES, true) ? @getimagesize($file->getRealPath()) : false;
$message->attachments()->create([
'path' => $path,
'name' => $name,
'mime' => $mime,
'size' => $file->getSize(),
'width' => $size[0] ?? null,
'height' => $size[1] ?? null,
]);
}
}

38
src/ChatPlugin.php Normal file
View file

@ -0,0 +1,38 @@
<?php
namespace Inhaus\Plugins\Chat;
use App\Layout\HeaderItems;
use App\Models\User;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Support\Facades\Storage;
/**
* Nachrichten: Direktnachrichten und Gruppenchats mit Anhängen, GIFs und Emojis.
*/
class ChatPlugin extends Plugin
{
public function register(): void
{
$this->app->singleton(Chat::class);
$this->app->make(Navigation::class)->add('chat', 'Nachrichten', '/chat', active: 'chat.*', sort: 15);
$abilities = $this->app->make(Abilities::class);
$abilities->define('chat.groups.create', 'Gruppenchats anlegen', 'Nachrichten', portal: true);
$abilities->define('chat.manage', 'Nachrichten einrichten: GIFs, GIPHY, Echtzeit', 'Nachrichten');
// Sprechblase mit Zahl der ungelesenen Nachrichten neben der Glocke
$this->app->make(HeaderItems::class)->add('chat', 'chat::Unread', fn (User $user) => [
'unread' => array_sum(app(Chat::class)->unread($user)),
], sort: 10);
}
public function uninstall(): void
{
// Beim Entfernen des Plugins auch alle Anhänge löschen (die Tabellen entfernt das Portal)
Storage::disk(Chat::DISK)->deleteDirectory('chat');
Storage::disk(Gifs::DISK)->deleteDirectory(Gifs::FOLDER);
}
}

View file

@ -0,0 +1,153 @@
<?php
namespace Inhaus\Plugins\Chat\Filament\Pages;
use App\Support\Audit;
use App\Support\Settings;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Validation\ValidationException;
use UnitEnum;
/**
* Nachrichten: GIPHY, Echtzeit (Pusher-kompatibel) und Größe von Anhängen.
*/
class ChatSettings extends Page
{
protected string $view = 'filament.pages.settings-form';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedChatBubbleLeftRight;
protected static string|UnitEnum|null $navigationGroup = 'Portal';
protected static ?int $navigationSort = 40;
protected static ?string $navigationLabel = 'Nachrichten';
protected static ?string $title = 'Nachrichten';
protected static ?string $slug = 'nachrichten';
/** @var array<string, mixed>|null */
public ?array $data = [];
public static function canAccess(): bool
{
return auth()->user()?->can('chat.manage') ?? false;
}
public function mount(Settings $settings): void
{
$this->form->fill([
'max_upload_mb' => (int) $settings->get('chat.max_upload_mb', 25),
'giphy_key' => null,
'giphy_rating' => $settings->get('chat.giphy_rating', 'g'),
'realtime_enabled' => (bool) $settings->get('chat.realtime.enabled'),
'realtime_app_id' => $settings->get('chat.realtime.app_id'),
'realtime_key' => $settings->get('chat.realtime.key'),
'realtime_secret' => null,
'realtime_host' => $settings->get('chat.realtime.host'),
'realtime_port' => $settings->get('chat.realtime.port'),
'realtime_scheme' => $settings->get('chat.realtime.scheme', 'https'),
'realtime_cluster' => $settings->get('chat.realtime.cluster', 'mt1'),
]);
}
public function form(Schema $schema): Schema
{
$settings = app(Settings::class);
$realtime = fn (Get $get) => (bool) $get('realtime_enabled');
return $schema->components([
Section::make('Allgemein')->schema([
Text::make('Direktnachrichten dürfen alle schreiben; Gruppen anlegen nur, wer das Recht „Gruppenchats anlegen“ hat (Rollen). Die Administration kann Gespräche nicht mitlesen.'),
TextInput::make('max_upload_mb')->label('Größe je Anhang (MB)')->numeric()->minValue(1)->maxValue(200)->required()
->helperText('Der Server begrenzt Uploads zusätzlich (upload_max_filesize: '.ini_get('upload_max_filesize').').'),
]),
Section::make('GIFs')->columns(2)->schema([
Text::make('Die eigene GIF-Sammlung pflegen Sie unter „Chat-GIFs“ – sie bleibt im Haus. Zusätzlich lässt sich die Suche bei GIPHY einschalten: Dann gehen Suchbegriffe an GIPHY, und die Bilder werden von dort geladen.')->columnSpanFull(),
TextInput::make('giphy_key')->label('GIPHY API-Schlüssel')->password()->revealable()->maxLength(100)->autocomplete('new-password')
->helperText(filled($settings->get('chat.giphy_key')) ? 'Gespeichert. Leer lassen, um ihn zu behalten.' : 'Kostenlos unter developers.giphy.com. Leer = GIPHY aus.'),
Select::make('giphy_rating')->label('Jugendschutz')->native(false)->selectablePlaceholder(false)
->options(['g' => 'G – für alle', 'pg' => 'PG', 'pg-13' => 'PG-13']),
]),
Section::make('Echtzeit (optional)')->columns(2)->schema([
Text::make('Ohne Einrichtung fragt der Chat alle paar Sekunden nach neuen Nachrichten – das funktioniert überall. Mit einem Pusher-kompatiblen Dienst (Laravel Reverb, Soketi oder pusher.com) kommen Nachrichten sofort. Über den Dienst geht nur ein Signal „es gibt Neues“, keine Inhalte.')->columnSpanFull(),
Toggle::make('realtime_enabled')->label('Echtzeit einschalten')->live()->columnSpanFull(),
TextInput::make('realtime_app_id')->label('App-ID')->maxLength(100)->required($realtime)->visible($realtime),
TextInput::make('realtime_key')->label('Key')->maxLength(100)->required($realtime)->visible($realtime),
TextInput::make('realtime_secret')->label('Secret')->password()->revealable()->maxLength(200)->autocomplete('new-password')->visible($realtime)
->helperText(filled($settings->get('chat.realtime.secret')) ? 'Gespeichert. Leer lassen, um es zu behalten.' : null),
TextInput::make('realtime_host')->label('Server (leer = pusher.com)')->maxLength(200)->visible($realtime)->placeholder('ws.example.org'),
TextInput::make('realtime_port')->label('Port')->numeric()->visible($realtime)->placeholder('443'),
Select::make('realtime_scheme')->label('Verbindung')->options(['https' => 'Verschlüsselt (https/wss)', 'http' => 'Unverschlüsselt (nur intern)'])->native(false)->selectablePlaceholder(false)->visible($realtime),
TextInput::make('realtime_cluster')->label('Cluster (nur pusher.com)')->maxLength(20)->visible($realtime)->placeholder('eu'),
]),
])->statePath('data');
}
public function save(Settings $settings): void
{
$s = $this->form->getState();
$enabled = (bool) $s['realtime_enabled'];
if ($enabled && blank($s['realtime_secret']) && blank($settings->get('chat.realtime.secret'))) {
throw ValidationException::withMessages(['data.realtime_secret' => 'Bitte das Secret eingeben.']);
}
// Secret gilt nur für denselben Server
if ($enabled && blank($s['realtime_secret']) && ($s['realtime_host'] ?? null) !== $settings->get('chat.realtime.host')) {
throw ValidationException::withMessages(['data.realtime_secret' => 'Der Server wurde geändert – bitte das Secret erneut eingeben.']);
}
$values = [
'chat.max_upload_mb' => (int) $s['max_upload_mb'],
'chat.giphy_rating' => $s['giphy_rating'] ?? 'g',
'chat.realtime.enabled' => $enabled,
'chat.realtime.app_id' => $s['realtime_app_id'] ?? null,
'chat.realtime.key' => $s['realtime_key'] ?? null,
'chat.realtime.host' => $s['realtime_host'] ?? null,
'chat.realtime.port' => $s['realtime_port'] ?? null,
'chat.realtime.scheme' => $s['realtime_scheme'] ?? 'https',
'chat.realtime.cluster' => $s['realtime_cluster'] ?? 'mt1',
];
if (filled($s['giphy_key'])) {
$values['chat.giphy_key'] = Crypt::encryptString(trim($s['giphy_key']));
}
if (filled($s['realtime_secret'])) {
$values['chat.realtime.secret'] = Crypt::encryptString(trim($s['realtime_secret']));
}
$settings->setMany($values);
$this->data['giphy_key'] = $this->data['realtime_secret'] = null;
Audit::log('chat.settings_updated', ['realtime' => $enabled, 'giphy' => filled($settings->get('chat.giphy_key'))]);
Notification::make()->success()->title('Gespeichert')->send();
}
protected function getHeaderActions(): array
{
return [
Action::make('forgetGiphy')->label('GIPHY ausschalten')->color('gray')
->visible(fn () => filled(app(Settings::class)->get('chat.giphy_key')))
->requiresConfirmation()
->action(function () {
app(Settings::class)->set('chat.giphy_key', null);
Notification::make()->success()->title('GIPHY ausgeschaltet')->send();
}),
];
}
}

View file

@ -0,0 +1,79 @@
<?php
namespace Inhaus\Plugins\Chat\Filament\Resources\Gifs;
use App\Filament\Components\SafeUpload;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Inhaus\Plugins\Chat\Filament\Resources\Gifs\Pages\ManageGifs;
use Inhaus\Plugins\Chat\Gifs;
use Inhaus\Plugins\Chat\Models\Gif;
use UnitEnum;
/**
* Eigene GIF-Sammlung für den Chat – bleibt im Haus, ohne externen Dienst.
*/
class GifResource extends Resource
{
protected static ?string $model = Gif::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedGif;
protected static string|UnitEnum|null $navigationGroup = 'Portal';
protected static ?int $navigationSort = 41;
protected static ?string $navigationLabel = 'Chat-GIFs';
protected static ?string $modelLabel = 'GIF';
protected static ?string $pluralModelLabel = 'GIFs';
protected static ?string $slug = 'chat-gifs';
public static function canAccess(): bool
{
return auth()->user()?->can('chat.manage') ?? false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
SafeUpload::apply(FileUpload::make('path'))
->label('GIF')
->disk(Gifs::DISK)->directory(Gifs::FOLDER)->visibility('public')
->acceptedFileTypes(['image/gif', 'image/webp'])
->maxSize(8 * 1024)
->required()
->columnSpanFull(),
TextInput::make('title')->label('Titel')->required()->maxLength(100)->placeholder('z. B. Daumen hoch'),
TextInput::make('tags')->label('Suchbegriffe')->maxLength(300)->placeholder('super, danke, klasse'),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('created_at', 'desc')
->columns([
ImageColumn::make('path')->label('')->disk(Gifs::DISK)->height(56),
TextColumn::make('title')->label('Titel')->searchable(),
TextColumn::make('tags')->label('Suchbegriffe')->color('gray')->searchable(),
])
->recordActions([EditAction::make(), DeleteAction::make()]);
}
public static function getPages(): array
{
return ['index' => ManageGifs::route('/')];
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace Inhaus\Plugins\Chat\Filament\Resources\Gifs\Pages;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ManageRecords;
use Inhaus\Plugins\Chat\Filament\Resources\Gifs\GifResource;
class ManageGifs extends ManageRecords
{
protected static string $resource = GifResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()->label('GIF hinzufügen')];
}
}

90
src/Gifs.php Normal file
View file

@ -0,0 +1,90 @@
<?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);
}
/**
* @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();
}
}

View file

@ -0,0 +1,135 @@
<?php
namespace Inhaus\Plugins\Chat\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Support\Settings;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Chat\Chat;
use Inhaus\Plugins\Chat\Gifs;
use Inhaus\Plugins\Chat\Models\Conversation;
use Inhaus\Plugins\Chat\Models\Reaction;
use Inhaus\Plugins\Chat\Presenter;
use Inhaus\Plugins\Chat\Realtime;
/**
* Die Chat-Seite und die Gesprächsliste: Direktgespräche beginnen, Gruppen verwalten.
*/
class ConversationController extends Controller
{
public function __construct(private readonly Chat $chat) {}
public function page(Request $request, Gifs $gifs, Realtime $realtime, ?Conversation $conversation = null): Response
{
$user = $request->user();
if ($conversation) {
$this->chat->member($conversation, $user);
}
return Inertia::render('chat::Index', [
'me' => Presenter::person($user),
'conversations' => $this->list($user),
'activeId' => $conversation?->id,
'canCreateGroups' => $user->can('chat.groups.create'),
'giphy' => $gifs->giphyEnabled(),
'realtime' => $realtime->clientConfig(),
'reactions' => Reaction::EMOJIS,
'maxUploadMb' => (int) app(Settings::class)->get('chat.max_upload_mb', 25),
]);
}
public function index(Request $request): JsonResponse
{
return response()->json(['conversations' => $this->list($request->user())]);
}
public function direct(Request $request): JsonResponse
{
$data = $request->validate(['user_id' => ['required', 'integer']]);
$other = User::query()->findOrFail($data['user_id']);
$conversation = $this->chat->direct($request->user(), $other);
return response()->json(['id' => $conversation->id, 'conversations' => $this->list($request->user())]);
}
public function createGroup(Request $request): JsonResponse
{
Gate::authorize('chat.groups.create');
$data = $request->validate([
'name' => ['required', 'string', 'max:100'],
'members' => ['required', 'array', 'min:1', 'max:200'],
'members.*' => ['integer'],
], [], ['name' => 'Name', 'members' => 'Mitglieder']);
$conversation = $this->chat->createGroup($request->user(), trim($data['name']), $data['members']);
return response()->json(['id' => $conversation->id, 'conversations' => $this->list($request->user())], 201);
}
public function update(Request $request, Conversation $conversation): JsonResponse
{
$data = $request->validate(['name' => ['sometimes', 'required', 'string', 'max:100'], 'muted' => ['sometimes', 'boolean']]);
$participant = $this->chat->member($conversation, $request->user());
if (isset($data['name']) && $data['name'] !== $conversation->name) {
$this->chat->rename($conversation, $request->user(), trim($data['name']));
}
if (array_key_exists('muted', $data)) {
$participant->forceFill(['muted' => $data['muted']])->save();
}
return response()->json(['conversations' => $this->list($request->user())]);
}
public function addMembers(Request $request, Conversation $conversation): JsonResponse
{
$data = $request->validate(['members' => ['required', 'array', 'min:1', 'max:200'], 'members.*' => ['integer']]);
$this->chat->addMembers($conversation, $request->user(), $data['members']);
return response()->json(['conversations' => $this->list($request->user())]);
}
public function removeMember(Request $request, Conversation $conversation, User $user): JsonResponse
{
$this->chat->removeMember($conversation, $request->user(), $user);
return response()->json(['conversations' => $this->list($request->user())]);
}
public function setAdmin(Request $request, Conversation $conversation, User $user): JsonResponse
{
$data = $request->validate(['admin' => ['required', 'boolean']]);
$this->chat->setAdmin($conversation, $request->user(), $user, $data['admin']);
return response()->json(['conversations' => $this->list($request->user())]);
}
/** Gruppe verlassen bzw. Direktgespräch ausblenden */
public function leave(Request $request, Conversation $conversation): JsonResponse
{
$this->chat->member($conversation, $request->user());
$conversation->isGroup()
? $this->chat->removeMember($conversation, $request->user(), $request->user())
: $this->chat->hide($conversation, $request->user());
return response()->json(['conversations' => $this->list($request->user())]);
}
/**
* @return list<array<string, mixed>>
*/
private function list(User $user): array
{
$conversations = Conversation::query()->for($user)->with('members')
->orderByRaw('last_message_at IS NULL')->orderByDesc('last_message_at')->limit(200)->get();
return Presenter::conversations($conversations, $user, $this->chat->unread($user));
}
}

View file

@ -0,0 +1,181 @@
<?php
namespace Inhaus\Plugins\Chat\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Inhaus\Plugins\Chat\Chat;
use Inhaus\Plugins\Chat\Gifs;
use Inhaus\Plugins\Chat\Models\Attachment;
use Inhaus\Plugins\Chat\Models\Conversation;
use Inhaus\Plugins\Chat\Models\Message;
use Inhaus\Plugins\Chat\Notifier;
use Inhaus\Plugins\Chat\Presenter;
use Inhaus\Plugins\Chat\Realtime;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Nachrichten eines Gesprächs: laden, senden, bearbeiten, reagieren – und „Gibt es Neues?“.
*/
class MessageController extends Controller
{
public const PAGE = 40;
public function __construct(private readonly Chat $chat) {}
public function index(Request $request, Conversation $conversation): JsonResponse
{
$this->chat->member($conversation, $request->user());
$before = $request->integer('vor');
$messages = $conversation->messages()->with(['user', 'attachments', 'reactions', 'replyTo.user'])
->when($before, fn ($q) => $q->where('id', '<', $before))
->orderByDesc('id')->limit(self::PAGE)->get()->reverse()->values();
return response()->json([
'messages' => Presenter::messages($messages, $request->user()),
'more' => $messages->count() === self::PAGE,
]);
}
public function store(Request $request, Conversation $conversation, Gifs $gifs): JsonResponse
{
$this->chat->member($conversation, $request->user());
$max = (int) app(Settings::class)->get('chat.max_upload_mb', 25) * 1024;
$data = $request->validate([
'body' => ['nullable', 'string', 'max:'.Message::MAX_LENGTH],
'gif_url' => ['nullable', 'string', 'max:500'],
'reply_to' => ['nullable', 'integer'],
'files' => ['nullable', 'array', 'max:'.Chat::MAX_FILES],
'files.*' => ['file', 'max:'.$max],
], ['files.*.max' => 'Eine Datei ist größer als '.($max / 1024).' MB.'], ['body' => 'Nachricht', 'files' => 'Dateien']);
if (filled($data['gif_url'] ?? null) && ! $gifs->isAllowedUrl($data['gif_url'])) {
throw ValidationException::withMessages(['gif_url' => 'Dieses GIF ist nicht erlaubt.']);
}
$message = $this->chat->send($conversation, $request->user(), $data['body'] ?? null, $data['gif_url'] ?? null, $request->file('files', []), $data['reply_to'] ?? null);
$message->load(['user', 'attachments', 'reactions', 'replyTo.user']);
return response()->json(['message' => Presenter::messages(collect([$message]), $request->user())[0]], 201);
}
public function update(Request $request, Message $message): JsonResponse
{
$this->chat->member($message->conversation, $request->user());
$data = $request->validate(['body' => ['required', 'string', 'max:'.Message::MAX_LENGTH]]);
$this->chat->edit($message, $request->user(), $data['body']);
return response()->json(['ok' => true]);
}
public function destroy(Request $request, Message $message): JsonResponse
{
$this->chat->member($message->conversation, $request->user());
$this->chat->delete($message, $request->user());
return response()->json(['ok' => true]);
}
public function react(Request $request, Message $message): JsonResponse
{
$this->chat->member($message->conversation, $request->user());
$data = $request->validate(['emoji' => ['required', 'string', 'max:16']]);
$this->chat->react($message, $request->user(), $data['emoji']);
return response()->json(['ok' => true]);
}
public function read(Request $request, Conversation $conversation): JsonResponse
{
$this->chat->member($conversation, $request->user());
$data = $request->validate(['message_id' => ['required', 'integer']]);
$this->chat->markRead($conversation, $request->user(), $data['message_id']);
return response()->json(['unread' => array_sum($this->chat->unread($request->user()))]);
}
public function typing(Request $request, Conversation $conversation): JsonResponse
{
$this->chat->member($conversation, $request->user());
Cache::put("chat:typing:{$conversation->id}:{$request->user()->id}", $request->user()->first_name ?: $request->user()->name, 6);
$ids = array_unique([...Cache::get("chat:typing:{$conversation->id}", []), $request->user()->id]);
Cache::put("chat:typing:{$conversation->id}", array_slice($ids, -20), 60);
return response()->json(['ok' => true]);
}
/**
* „Gibt es Neues?“ – neue und geänderte Nachrichten im offenen Gespräch, bei Änderungen die
* Gesprächsliste, dazu wer gerade schreibt.
*/
public function updates(Request $request): JsonResponse
{
$data = $request->validate(['seit' => ['nullable', 'date'], 'offen' => ['nullable', 'integer'], 'nach' => ['nullable', 'integer']]);
$user = $request->user();
$now = CarbonImmutable::now();
$since = isset($data['seit']) ? CarbonImmutable::parse($data['seit'])->subSeconds(2) : $now->subMinute();
$open = isset($data['offen']) ? Conversation::query()->for($user)->find($data['offen']) : null;
Notifier::markActive($user, $open?->id);
$messages = $open ? $open->messages()->with(['user', 'attachments', 'reactions', 'replyTo.user'])
->where(fn ($q) => $q->where('id', '>', (int) ($data['nach'] ?? 0))->orWhere('updated_at', '>=', $since))
->orderBy('id')->limit(200)->get() : collect();
$changed = Conversation::query()->for($user)->where(fn ($q) => $q->where('last_message_at', '>=', $since)->orWhere('updated_at', '>=', $since))->exists();
$typing = $open ? collect(Cache::get("chat:typing:{$open->id}", []))->reject(fn ($id) => $id === $user->id)
->map(fn ($id) => Cache::get("chat:typing:{$open->id}:{$id}"))->filter()->values()->all() : [];
return response()->json([
'cursor' => $now->toIso8601String(),
'messages' => Presenter::messages($messages, $user),
'conversations' => $changed ? app(ConversationController::class)->index($request)->getData(true)['conversations'] : null,
'typing' => $typing,
'unread' => array_sum($this->chat->unread($user)),
]);
}
public function unread(Request $request): JsonResponse
{
return response()->json(['unread' => array_sum($this->chat->unread($request->user()))]);
}
/** Anhänge nur für Mitglieder – Bilder im Browser, alles andere als Download */
public function attachment(Request $request, Attachment $attachment): StreamedResponse
{
$this->chat->member($attachment->message->conversation, $request->user());
$disk = Storage::disk(Chat::DISK);
abort_unless($disk->exists($attachment->path), 404);
$headers = [
'X-Content-Type-Options' => 'nosniff',
'Content-Security-Policy' => "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
'Cache-Control' => 'private, max-age=86400',
];
return $attachment->isImage() && ! $request->boolean('download')
? $disk->response($attachment->path, $attachment->name, [...$headers, 'Content-Type' => $attachment->mime], 'inline')
: $disk->download($attachment->path, $attachment->name, [...$headers, 'Content-Type' => 'application/octet-stream']);
}
public function gifs(Request $request, Gifs $gifs): JsonResponse
{
$data = $request->validate(['q' => ['nullable', 'string', 'max:50']]);
return response()->json(['gifs' => $gifs->search((string) ($data['q'] ?? '')), 'giphy' => $gifs->giphyEnabled()]);
}
/** Anmeldung am privaten Echtzeit-Kanal (Pusher-Protokoll) */
public function realtimeAuth(Request $request, Realtime $realtime): JsonResponse
{
$auth = $realtime->authorize($request->user()->id, (string) $request->input('socket_id'), (string) $request->input('channel_name'));
return $auth ? response()->json($auth) : response()->json(['message' => 'Nicht erlaubt.'], 403);
}
}

30
src/Models/Attachment.php Normal file
View file

@ -0,0 +1,30 @@
<?php
namespace Inhaus\Plugins\Chat\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['message_id', 'path', 'name', 'mime', 'size', 'width', 'height'])]
class Attachment extends Model
{
public const IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
protected $table = 'chat_attachments';
public $timestamps = false;
/**
* @return BelongsTo<Message, $this>
*/
public function message(): BelongsTo
{
return $this->belongsTo(Message::class);
}
public function isImage(): bool
{
return in_array($this->mime, self::IMAGE_TYPES, true);
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Inhaus\Plugins\Chat\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['type', 'name', 'direct_key', 'created_by', 'last_message_id', 'last_message_at'])]
class Conversation extends Model
{
protected $table = 'chat_conversations';
protected function casts(): array
{
return ['last_message_at' => 'datetime'];
}
/**
* Aktuelle Mitglieder (ohne Ausgetretene).
*
* @return BelongsToMany<User, $this>
*/
public function members(): BelongsToMany
{
return $this->belongsToMany(User::class, 'chat_participants')
->withPivot(['role', 'last_read_message_id', 'muted', 'joined_at', 'left_at'])
->wherePivotNull('left_at');
}
/**
* @return HasMany<Participant, $this>
*/
public function participants(): HasMany
{
return $this->hasMany(Participant::class);
}
/**
* @return HasMany<Message, $this>
*/
public function messages(): HasMany
{
return $this->hasMany(Message::class);
}
public function isGroup(): bool
{
return $this->type === 'group';
}
public function participant(User $user): ?Participant
{
return $this->participants()->where('user_id', $user->id)->whereNull('left_at')->first();
}
/**
* Gespräche, in denen die Person Mitglied ist.
*
* @param Builder<Conversation> $query
*/
public function scopeFor(Builder $query, User $user): void
{
$query->whereHas('participants', fn ($q) => $q->where('user_id', $user->id)->whereNull('left_at'));
}
public static function directKey(int $a, int $b): string
{
return min($a, $b).':'.max($a, $b);
}
}

27
src/Models/Gif.php Normal file
View file

@ -0,0 +1,27 @@
<?php
namespace Inhaus\Plugins\Chat\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Inhaus\Plugins\Chat\Gifs;
#[Fillable(['path', 'title', 'tags', 'width', 'height'])]
class Gif extends Model
{
protected $table = 'chat_gifs';
protected static function booted(): void
{
// Maße für die Vorschau im Chat merken; Datei beim Löschen mit entfernen
static::saving(function (Gif $gif): void {
if ($gif->isDirty('path') && $gif->path && Storage::disk(Gifs::DISK)->exists($gif->path)) {
$size = @getimagesize(Storage::disk(Gifs::DISK)->path($gif->path));
$gif->width = $size[0] ?? null;
$gif->height = $size[1] ?? null;
}
});
static::deleted(fn (Gif $gif) => Storage::disk(Gifs::DISK)->delete($gif->path));
}
}

62
src/Models/Message.php Normal file
View file

@ -0,0 +1,62 @@
<?php
namespace Inhaus\Plugins\Chat\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['conversation_id', 'user_id', 'kind', 'body', 'gif_url', 'reply_to_id', 'edited_at', 'deleted_at', 'created_at'])]
class Message extends Model
{
public const MAX_LENGTH = 5000;
protected $table = 'chat_messages';
protected function casts(): array
{
return ['edited_at' => 'datetime', 'deleted_at' => 'datetime'];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* @return BelongsTo<Conversation, $this>
*/
public function conversation(): BelongsTo
{
return $this->belongsTo(Conversation::class);
}
/**
* @return BelongsTo<Message, $this>
*/
public function replyTo(): BelongsTo
{
return $this->belongsTo(Message::class, 'reply_to_id');
}
/**
* @return HasMany<Attachment, $this>
*/
public function attachments(): HasMany
{
return $this->hasMany(Attachment::class);
}
/**
* @return HasMany<Reaction, $this>
*/
public function reactions(): HasMany
{
return $this->hasMany(Reaction::class);
}
}

View file

@ -0,0 +1,53 @@
<?php
namespace Inhaus\Plugins\Chat\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['conversation_id', 'user_id', 'role', 'last_read_message_id', 'notified_message_id', 'muted', 'joined_at', 'left_at'])]
class Participant extends Model
{
protected $table = 'chat_participants';
public $timestamps = false;
public $incrementing = false;
protected $primaryKey = null;
protected function casts(): array
{
return ['muted' => 'boolean', 'joined_at' => 'datetime', 'left_at' => 'datetime'];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* @return BelongsTo<Conversation, $this>
*/
public function conversation(): BelongsTo
{
return $this->belongsTo(Conversation::class);
}
public function isAdmin(): bool
{
return $this->role === 'admin';
}
/** Zusammengesetzter Schlüssel – Änderungen immer über diese Abfrage */
protected function setKeysForSaveQuery($query): Builder
{
return $query->where('conversation_id', $this->conversation_id)->where('user_id', $this->user_id);
}
}

20
src/Models/Reaction.php Normal file
View file

@ -0,0 +1,20 @@
<?php
namespace Inhaus\Plugins\Chat\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
#[Fillable(['message_id', 'user_id', 'emoji'])]
class Reaction extends Model
{
public const EMOJIS = ['👍', '❤️', '😂', '😮', '😢', '🙏'];
protected $table = 'chat_reactions';
public $timestamps = false;
public $incrementing = false;
protected $primaryKey = null;
}

53
src/Notifier.php Normal file
View file

@ -0,0 +1,53 @@
<?php
namespace Inhaus\Plugins\Chat;
use App\Models\User;
use App\Notifications\PortalNotification;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Inhaus\Plugins\Chat\Models\Conversation;
use Inhaus\Plugins\Chat\Models\Message;
use Inhaus\Plugins\Chat\Models\Participant;
/**
* Glocke und Push bei neuen Nachrichten – je Gespräch höchstens einmal, bis die Person
* es gelesen hat, und nicht, während sie das Gespräch gerade offen hat.
*/
class Notifier
{
public static function markActive(User $user, ?int $conversationId): void
{
if ($conversationId) {
Cache::put("chat:open:{$user->id}", $conversationId, 20);
}
}
public function newMessage(Conversation $conversation, Message $message, User $sender): void
{
$recipients = $conversation->participants()->with('user')->whereNull('left_at')->where('user_id', '!=', $sender->id)->where('muted', false)
->where(fn ($q) => $q->whereNull('notified_message_id')->orWhereColumn('notified_message_id', '<=', 'last_read_message_id'))
->get();
$text = match (true) {
$message->kind === 'gif' => 'GIF',
filled($message->body) => Str::limit($message->body, 100),
default => 'Datei',
};
foreach ($recipients as $participant) {
/** @var Participant $participant */
if (! $participant->user?->is_active || Cache::get("chat:open:{$participant->user_id}") === $conversation->id) {
continue;
}
$participant->forceFill(['notified_message_id' => $message->id])->save();
$participant->user->notify(new PortalNotification(
$conversation->isGroup() ? "{$sender->name} in „{$conversation->name}“" : "Nachricht von {$sender->name}",
$text,
'/chat/'.$conversation->id,
'message-circle',
));
}
}
}

112
src/Presenter.php Normal file
View file

@ -0,0 +1,112 @@
<?php
namespace Inhaus\Plugins\Chat;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Inhaus\Plugins\Chat\Models\Attachment;
use Inhaus\Plugins\Chat\Models\Conversation;
use Inhaus\Plugins\Chat\Models\Message;
class Presenter
{
/**
* @return array<string, mixed>
*/
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;
}
/**
* @param Collection<int, Conversation> $conversations mit members und lastMessage.user
* @param array<int, int> $unread
* @return list<array<string, mixed>>
*/
public static function conversations(Collection $conversations, User $me, array $unread): array
{
$last = Message::query()->with('user')->whereIn('id', $conversations->pluck('last_message_id')->filter())->get()->keyBy('id');
return $conversations->map(function (Conversation $c) use ($me, $unread, $last) {
$others = $c->members->reject(fn (User $u) => $u->is($me))->values();
$mine = $c->members->firstWhere('id', $me->id);
$message = $last[$c->last_message_id] ?? null;
return [
'id' => $c->id,
'type' => $c->type,
'name' => $c->isGroup() ? $c->name : ($others->first()?->name ?? 'Unbekannt'),
'person' => $c->isGroup() ? null : self::person($others->first()),
'members' => $c->members->map(fn (User $u) => [...self::person($u), 'admin' => $u->pivot->role === 'admin'])->values()->all(),
'is_admin' => $mine?->pivot->role === 'admin',
'muted' => (bool) $mine?->pivot->muted,
'unread' => $unread[$c->id] ?? 0,
'last_read_id' => $mine?->pivot->last_read_message_id,
// Bis hierhin haben alle anderen gelesen („gelesen“ unter eigenen Nachrichten)
'others_read_id' => $others->isEmpty() ? null : $others->min(fn (User $u) => (int) $u->pivot->last_read_message_id),
'last_message_at' => $c->last_message_at?->toIso8601String(),
'preview' => $message ? self::preview($message, $me, $c->isGroup()) : null,
];
})->values()->all();
}
private static function preview(Message $message, User $me, bool $group): string
{
$text = match (true) {
$message->deleted_at !== null => 'Nachricht gelöscht',
$message->kind === 'system' => (string) $message->body,
$message->kind === 'gif' => 'GIF',
filled($message->body) => Str::limit(preg_replace('/\s+/u', ' ', $message->body), 80),
default => '📎 Datei',
};
if ($message->kind === 'system') {
return $text;
}
$who = $message->user_id === $me->id ? 'Sie' : ($group ? ($message->user?->first_name ?: $message->user?->name) : null);
return $who ? "{$who}: {$text}" : $text;
}
/**
* @param Collection<int, Message> $messages mit user, attachments, reactions, replyTo.user
* @return list<array<string, mixed>>
*/
public static function messages(Collection $messages, User $me): array
{
return $messages->map(fn (Message $m) => [
'id' => $m->id,
'conversation_id' => $m->conversation_id,
'kind' => $m->kind,
'user' => self::person($m->user),
'mine' => $m->user_id === $me->id,
'body' => $m->deleted_at ? null : $m->body,
'gif_url' => $m->deleted_at ? null : $m->gif_url,
'deleted' => $m->deleted_at !== null,
'edited' => $m->edited_at !== null,
'created_at' => $m->created_at?->toIso8601String(),
'reply_to' => $m->replyTo ? [
'id' => $m->replyTo->id,
'name' => $m->replyTo->user?->name,
'text' => $m->replyTo->deleted_at ? 'Nachricht gelöscht' : Str::limit((string) ($m->replyTo->body ?: ($m->replyTo->gif_url ? 'GIF' : 'Datei')), 100),
] : null,
'attachments' => $m->attachments->map(fn (Attachment $a) => [
'id' => $a->id,
'name' => $a->name,
'mime' => $a->mime,
'size' => $a->size,
'image' => $a->isImage(),
'width' => $a->width,
'height' => $a->height,
'url' => route('chat.attachment', $a),
])->all(),
'reactions' => $m->reactions->groupBy('emoji')->map(fn ($group, $emoji) => [
'emoji' => $emoji,
'count' => $group->count(),
'mine' => $group->contains('user_id', $me->id),
])->values()->all(),
])->values()->all();
}
}

122
src/Realtime.php Normal file
View file

@ -0,0 +1,122 @@
<?php
namespace Inhaus\Plugins\Chat;
use App\Support\Settings;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Inhaus\Plugins\Chat\Models\Conversation;
use Throwable;
/**
* Echtzeit über einen Pusher-kompatiblen Dienst (Laravel Reverb, Soketi oder Pusher) –
* optional. Ohne Einrichtung fragt die Oberfläche alle paar Sekunden nach.
*
* Über den Dienst geht nur ein Signal „in Gespräch X gibt es Neues“ – nie Nachrichteninhalte.
* Die Oberfläche holt die Nachrichten danach wie gewohnt vom Portal.
*/
class Realtime
{
public function __construct(private readonly Settings $settings) {}
public function enabled(): bool
{
return (bool) $this->settings->get('chat.realtime.enabled') && filled($this->settings->get('chat.realtime.key')) && filled($this->settings->get('chat.realtime.secret'));
}
/**
* Für die Oberfläche (ohne Geheimnis).
*
* @return array{key: string, host: ?string, port: int, tls: bool, cluster: string}|null
*/
public function clientConfig(): ?array
{
if (! $this->enabled()) {
return null;
}
return [
'key' => (string) $this->settings->get('chat.realtime.key'),
'host' => $this->settings->get('chat.realtime.host') ?: null,
'port' => (int) ($this->settings->get('chat.realtime.port') ?: 443),
'tls' => ($this->settings->get('chat.realtime.scheme') ?: 'https') === 'https',
'cluster' => (string) ($this->settings->get('chat.realtime.cluster') ?: 'mt1'),
];
}
public static function channel(int $userId): string
{
return 'private-chat-user-'.$userId;
}
/** Alle Mitglieder benachrichtigen, dass es Neues gibt */
public function notify(Conversation $conversation): void
{
if (! $this->enabled()) {
return;
}
$channels = $conversation->participants()->whereNull('left_at')->pluck('user_id')->map(fn ($id) => self::channel($id))->all();
foreach (array_chunk($channels, 100) as $chunk) {
$this->trigger($chunk, 'update', ['conversation' => $conversation->id]);
}
}
/**
* Anmeldung an einem privaten Kanal (Pusher-Protokoll): nur am eigenen.
*
* @return array{auth: string}|null
*/
public function authorize(int $userId, string $socketId, string $channel): ?array
{
if (! $this->enabled() || $channel !== self::channel($userId) || ! preg_match('/^\d+\.\d+$/', $socketId)) {
return null;
}
return ['auth' => $this->settings->get('chat.realtime.key').':'.hash_hmac('sha256', $socketId.':'.$channel, $this->secret())];
}
/**
* @param list<string> $channels
* @param array<string, mixed> $data
*/
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));
} catch (Throwable $e) {
// Echtzeit ist nur eine Beschleunigung – die Oberfläche fragt ohnehin regelmäßig nach
report($e);
}
}
private function baseUrl(): string
{
$scheme = $this->settings->get('chat.realtime.scheme') ?: 'https';
$host = $this->settings->get('chat.realtime.host') ?: 'api-'.($this->settings->get('chat.realtime.cluster') ?: 'mt1').'.pusher.com';
$port = $this->settings->get('chat.realtime.port');
return $scheme.'://'.$host.($port ? ':'.$port : '');
}
private function secret(): string
{
try {
return Crypt::decryptString((string) $this->settings->get('chat.realtime.secret'));
} catch (Throwable) {
return '';
}
}
}