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:
commit
2844452002
55 changed files with 5448 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
node_modules/
|
||||
*.zip
|
||||
65
README.md
Normal file
65
README.md
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
# Nachrichten – Chat-Plugin für Inhaus
|
||||
|
||||
Direktnachrichten und Gruppenchats im Mitarbeiterportal.
|
||||
|
||||
- **Direktnachrichten** an alle Kolleginnen und Kollegen (Personensuche), **Gruppenchats** für alle mit dem Recht
|
||||
„Gruppenchats anlegen“ (unter Rollen vergeben). Gruppen-Admins benennen um, fügen hinzu, entfernen, ernennen Admins.
|
||||
- **Anhänge** (Bilder, PDFs, Office …; Einfügen aus der Zwischenablage, Ziehen & Ablegen), **GIFs**, **Emojis**,
|
||||
**Reaktionen**, **Antworten** auf einzelne Nachrichten, **Bearbeiten** und **Löschen** eigener Nachrichten.
|
||||
- **Ungelesen-Zähler** als Sprechblase neben der Glocke, „Neu“-Trenner, „gelesen“ unter eigenen Nachrichten,
|
||||
„schreibt gerade …“. Stummschalten je Gespräch.
|
||||
- **Benachrichtigung** (Glocke und Push, auch in der Inhaus-App) – je Gespräch einmal, bis es gelesen ist, und nicht,
|
||||
während das Gespräch offen ist.
|
||||
- Handy- und Desktop-Ansicht, Tastatur (Enter sendet, Umschalt+Enter neue Zeile, Esc bricht ab), Screenreader-Hinweise.
|
||||
|
||||
Voraussetzung: Inhaus **0.39.0** oder neuer.
|
||||
|
||||
## Installation
|
||||
|
||||
1. Neuestes Release herunterladen: `chat-<version>.zip` unter
|
||||
https://git.loheide.cloud/friloo/inhaus-plugin-chat/releases
|
||||
2. Backend → **Plugins** → hochladen → aktivieren. Updates erscheinen danach automatisch unter „Plugins“.
|
||||
3. Unter **Rollen** das Recht **„Gruppenchats anlegen“** an die passenden Rollen vergeben (z. B. Teamleitungen).
|
||||
4. Optional unter **Portal → Nachrichten**: GIPHY, Echtzeit, Größe von Anhängen; unter **Portal → Chat-GIFs** die
|
||||
eigene GIF-Sammlung (Recht „Nachrichten einrichten“).
|
||||
|
||||
## Datenschutz
|
||||
|
||||
- Gespräche sehen nur ihre Mitglieder – **auch die Administration kann nicht mitlesen**. Anhänge liegen außerhalb des
|
||||
öffentlichen Ordners und werden nur an Mitglieder ausgeliefert.
|
||||
- **GIPHY** ist aus, bis ein Schlüssel eingetragen ist. Dann gehen Suchbegriffe an GIPHY und die Bilder werden von dort
|
||||
geladen. Die eigene Sammlung bleibt im Haus.
|
||||
- **Echtzeit**: Über den Dienst geht nur das Signal „es gibt Neues“ – keine Inhalte.
|
||||
- Beim Entfernen des Plugins mit „Daten löschen“ verschwinden alle Nachrichten und Anhänge.
|
||||
|
||||
## 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:
|
||||
|
||||
- **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.
|
||||
|
||||
## 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`.
|
||||
|
||||
## Entwicklung
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run build # dist/ – wird mit ins Repository eingecheckt
|
||||
npm run package # baut und erzeugt chat-<version>.zip
|
||||
```
|
||||
|
||||
Tests laufen in einer Inhaus-Installation, in der das Plugin unter `plugins/chat` liegt (Kopie oder Symlink):
|
||||
|
||||
```bash
|
||||
vendor-dev/bin/phpunit plugins/chat/tests
|
||||
```
|
||||
|
||||
Release: Version in `plugin.json` erhöhen, `npm run package`, Tag `vX.Y.Z` setzen und
|
||||
`tea release create --tag vX.Y.Z --asset chat-X.Y.Z.zip`.
|
||||
29
bin/package
Executable file
29
bin/package
Executable file
|
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Baut chat-<version>.zip zum Hochladen unter Administration → Plugins.
|
||||
* Enthält alles außer Quelltexten fürs Frontend-Build und node_modules.
|
||||
*/
|
||||
$root = dirname(__DIR__);
|
||||
$manifest = json_decode(file_get_contents("{$root}/plugin.json"), true);
|
||||
$target = "{$root}/chat-{$manifest['version']}.zip";
|
||||
$skip = ['node_modules', '.git', 'inhaus-sdk', 'package.json', 'package-lock.json', 'vite.config.js', basename($target)];
|
||||
|
||||
@unlink($target);
|
||||
$zip = new ZipArchive;
|
||||
$zip->open($target, ZipArchive::CREATE);
|
||||
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS));
|
||||
|
||||
foreach ($files as $file) {
|
||||
$relative = substr($file->getPathname(), strlen($root) + 1);
|
||||
|
||||
if (in_array(explode(DIRECTORY_SEPARATOR, $relative)[0], $skip, true) || str_ends_with($relative, '.zip')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$zip->addFile($file->getPathname(), 'chat/'.$relative);
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
echo "Paket: {$target}\n";
|
||||
91
database/migrations/2026_10_21_000001_create_chat_tables.php
Normal file
91
database/migrations/2026_10_21_000001_create_chat_tables.php
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('chat_conversations', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('type', 10); // direct | group
|
||||
$table->string('name', 100)->nullable();
|
||||
// Direktnachrichten: „kleinere-ID:größere-ID“ – je Paar genau ein Gespräch
|
||||
$table->string('direct_key', 50)->nullable()->unique();
|
||||
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->unsignedBigInteger('last_message_id')->nullable();
|
||||
$table->timestamp('last_message_at')->nullable()->index();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('chat_participants', function (Blueprint $table) {
|
||||
$table->foreignId('conversation_id')->constrained('chat_conversations')->cascadeOnDelete();
|
||||
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('role', 10)->default('member'); // member | admin
|
||||
$table->unsignedBigInteger('last_read_message_id')->nullable();
|
||||
$table->unsignedBigInteger('notified_message_id')->nullable();
|
||||
$table->boolean('muted')->default(false);
|
||||
$table->timestamp('joined_at')->nullable();
|
||||
$table->timestamp('left_at')->nullable();
|
||||
|
||||
$table->primary(['conversation_id', 'user_id']);
|
||||
$table->index(['user_id', 'left_at']);
|
||||
});
|
||||
|
||||
Schema::create('chat_messages', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('conversation_id')->constrained('chat_conversations')->cascadeOnDelete();
|
||||
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
|
||||
$table->string('kind', 10)->default('text'); // text | gif | system
|
||||
$table->text('body')->nullable();
|
||||
$table->string('gif_url', 500)->nullable();
|
||||
$table->foreignId('reply_to_id')->nullable()->constrained('chat_messages')->nullOnDelete();
|
||||
$table->timestamp('edited_at')->nullable();
|
||||
$table->timestamp('deleted_at')->nullable();
|
||||
// updated_at: auch bei Reaktionen – so holt die Abfrage geänderte Nachrichten nach
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['conversation_id', 'id']);
|
||||
$table->index(['conversation_id', 'updated_at']);
|
||||
});
|
||||
|
||||
Schema::create('chat_attachments', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('message_id')->constrained('chat_messages')->cascadeOnDelete();
|
||||
$table->string('path', 300);
|
||||
$table->string('name', 200);
|
||||
$table->string('mime', 100);
|
||||
$table->unsignedBigInteger('size');
|
||||
$table->unsignedInteger('width')->nullable();
|
||||
$table->unsignedInteger('height')->nullable();
|
||||
});
|
||||
|
||||
Schema::create('chat_reactions', function (Blueprint $table) {
|
||||
$table->foreignId('message_id')->constrained('chat_messages')->cascadeOnDelete();
|
||||
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('emoji', 16);
|
||||
|
||||
$table->primary(['message_id', 'user_id', 'emoji']);
|
||||
});
|
||||
|
||||
// Eigene GIF-Sammlung (von der Administration hochgeladen)
|
||||
Schema::create('chat_gifs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('path', 300);
|
||||
$table->string('title', 100);
|
||||
$table->string('tags', 300)->nullable();
|
||||
$table->unsignedInteger('width')->nullable();
|
||||
$table->unsignedInteger('height')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
foreach (['chat_gifs', 'chat_reactions', 'chat_attachments', 'chat_messages', 'chat_participants', 'chat_conversations'] as $table) {
|
||||
Schema::dropIfExists($table);
|
||||
}
|
||||
}
|
||||
};
|
||||
2
dist/assets/style-BXBiFiq8.css
vendored
Normal file
2
dist/assets/style-BXBiFiq8.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
dist/chunks/createLucideIcon-CYyWUN7r.js
vendored
Normal file
1
dist/chunks/createLucideIcon-CYyWUN7r.js
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
import{h as e,inject as t}from"vue";var n={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`},r=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim();function i(e){return e!=null}function a(e,t={}){let a=t.attributeNames??{},o=e=>a[e]??e,s=e.size??e.width??n.width,c=e.size??e.height??n.height,l=e.aliases?.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>`lucide-${e}`)??[],u=[...e.name?[`lucide-${e.name}`]:[],...l],d=t.className?.split(` `).filter(Boolean)??[],f=t.includeDefaultClasses===!1?r(...d):r(`lucide`,...u,...d),p=t.absoluteStrokeWidth?Number(t.strokeWidth??n[`stroke-width`])*Number(e.size??e.width??n.width)/Number(t.size??t.width??n.width):t.strokeWidth??n[`stroke-width`];return[`svg`,{...Object.entries(n).reduce((e,[t,n])=>(e[o(t)]=n,e),{}),...`color`in t&&t.color&&{[o(`stroke`)]:t.color},...`size`in t&&i(t.size)&&{[o(`width`)]:t.size,[o(`height`)]:t.size},...`width`in t&&i(t.width)&&{[o(`width`)]:t.width},...`height`in t&&i(t.height)&&{[o(`height`)]:t.height},[o(`stroke-width`)]:p,...f&&{[o(`class`)]:f},[o(`viewBox`)]:`0 0 ${s} ${c}`,...t.hasA11yProp===!1?{[o(`aria-hidden`)]:`true`}:{},...`attributes`in t&&t.attributes},e.node.map(e=>{let[n,r,i]=e,a=t.nonScalingStroke?{[o(`vector-effect`)]:`non-scaling-stroke`,...r}:r;return i?[n,a,i]:[n,a]})]}var o=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},s=e=>e===``,c=e=>e?.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),l=Symbol(`lucide-icons`);function u(){return t(l,{})}var d=({name:t,iconNode:n,"icon-node":r,icon:i={name:t&&c(t),node:n??r??[],size:24,aliases:[]},absoluteStrokeWidth:l,"absolute-stroke-width":d,nonScalingStroke:f,"non-scaling-stroke":p,strokeWidth:m,"stroke-width":h,size:g,width:_=g,height:v=g,color:y,...b},{slots:x})=>{let{size:S,color:C,strokeWidth:w=2,absoluteStrokeWidth:T=!1,nonScalingStroke:E=!1,class:D=``}=u(),O=s(l)||s(d)||l===!0||d===!0||T===!0,k=s(f)||s(p)||f===!0||p===!0||E===!0;delete b.class;let A=x.default?.(),[,j,M=[]]=a(i,{color:y??C,width:_??g??S,height:v??g??S,strokeWidth:m??h??w,absoluteStrokeWidth:O,nonScalingStroke:k,className:D,hasA11yProp:A!=null&&A.length>0||o(b),attributes:b});return e(`svg`,j,[...M.map(([t,n])=>e(t,n)),...A??[]])};function f(t,n=[]){let r=typeof t==`string`?{name:t,node:n}:t;return(t,{slots:n})=>e(d,{...t,icon:r},n.default?{default:n.default}:void 0)}export{f as t};
|
||||
2
dist/chunks/pusher-DXDYBH7H.js
vendored
Normal file
2
dist/chunks/pusher-DXDYBH7H.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
dist/chunks/rolldown-runtime-CbXtAM7H.js
vendored
Normal file
1
dist/chunks/rolldown-runtime-CbXtAM7H.js
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));export{c as n,o as t};
|
||||
1
dist/header/Unread.js
vendored
Normal file
1
dist/header/Unread.js
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
import{t as e}from"../chunks/createLucideIcon-CYyWUN7r.js";import{createCommentVNode as t,createElementBlock as n,createVNode as r,onBeforeUnmount as i,onMounted as a,openBlock as o,ref as s,toDisplayString as c,unref as l}from"vue";import{http as u}from"@inhaus/ui";var d=e({name:`message-circle`,size:24,node:[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`,key:`1sd12s`}]]}),f=[`aria-label`,`title`],p={key:0,class:`ih:absolute ih:top-0.5 ih:right-0.5 ih:grid ih:h-4 ih:min-w-4 ih:place-items-center ih:rounded-full ih:bg-brand ih:px-1 ih:text-[10px] ih:font-semibold ih:text-brand-foreground ih:tabular-nums`,"aria-hidden":`true`},m={__name:`Unread`,props:{unread:{type:Number,default:0}},setup(e){let m=s(e.unread),h,g=e=>m.value=e.detail;async function _(){document.visibilityState===`visible`&&!location.pathname.startsWith(`/chat`)&&(m.value=(await u.get(`/chat/api/ungelesen`).catch(()=>({unread:m.value}))).unread)}return a(()=>{window.addEventListener(`inhaus-chat:unread`,g),h=setInterval(_,3e4)}),i(()=>{window.removeEventListener(`inhaus-chat:unread`,g),clearInterval(h)}),(e,i)=>(o(),n(`a`,{href:`/chat`,class:`ih:relative ih:grid ih:size-9 ih:place-items-center ih:rounded-md ih:text-muted-foreground ih:transition-colors ih:hover:bg-accent ih:hover:text-foreground`,"aria-label":m.value?`Nachrichten, ${m.value} ungelesen`:`Nachrichten`,title:m.value?`${m.value} ungelesene Nachrichten`:`Nachrichten`},[r(l(d),{class:`ih:size-5`}),m.value?(o(),n(`span`,p,c(m.value>99?`99+`:m.value),1)):t(``,!0)],8,f))}};export{m as default};
|
||||
9
dist/inhaus.json
vendored
Normal file
9
dist/inhaus.json
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"components": {
|
||||
"header/Unread": "header/Unread.js",
|
||||
"pages/Index": "pages/Index.js"
|
||||
},
|
||||
"css": [
|
||||
"assets/style-BXBiFiq8.css"
|
||||
]
|
||||
}
|
||||
2
dist/pages/Index.js
vendored
Normal file
2
dist/pages/Index.js
vendored
Normal file
File diff suppressed because one or more lines are too long
63
inhaus-sdk/theme.css
Normal file
63
inhaus-sdk/theme.css
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
/*
|
||||
* Automatisch erzeugt (scripts/generate-sdk-shims.mjs) – Design-Tokens des Portals.
|
||||
* In der style.css eines Plugins: @import "../../inhaus-sdk/theme.css";
|
||||
* Farben, Ecken und Schrift folgen so dem Erscheinungsbild der Installation.
|
||||
*
|
||||
* Tailwind-Klassen in Plugins tragen das Präfix „ih:“ (z. B. ih:grid, ih:lg:grid-cols-2, ih:bg-brand).
|
||||
* So kann das CSS eines Plugins nie die Klassen des Portals überschreiben.
|
||||
* Nur Hilfsklassen – Grundstile (Preflight) bringt das Portal selbst mit.
|
||||
*/
|
||||
@import "tailwindcss/theme" layer(theme) prefix(ih);
|
||||
@import "tailwindcss/utilities" layer(utilities);
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--font-sans: var(--font-body);
|
||||
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) * 1.5);
|
||||
--radius-2xl: calc(var(--radius) * 2);
|
||||
/* „Pille“: voll gerundet – außer bei „Eckig“ im Erscheinungsbild (dann 0) */
|
||||
--radius-pill: calc(var(--radius) * 1000);
|
||||
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
|
||||
--color-brand: var(--brand);
|
||||
--color-brand-foreground: var(--brand-foreground);
|
||||
--color-brand-text: var(--brand-text);
|
||||
--color-accent2: var(--accent2);
|
||||
--color-accent2-foreground: var(--accent2-foreground);
|
||||
--color-accent2-text: var(--accent2-text);
|
||||
--color-brand-soft: var(--brand-soft);
|
||||
--color-brand-soft-foreground: var(--brand-soft-foreground);
|
||||
--color-brand-50: var(--brand-50);
|
||||
--color-brand-100: var(--brand-100);
|
||||
--color-brand-200: var(--brand-200);
|
||||
--color-brand-300: var(--brand-300);
|
||||
--color-brand-400: var(--brand-400);
|
||||
--color-brand-500: var(--brand-500);
|
||||
--color-brand-600: var(--brand-600);
|
||||
--color-brand-700: var(--brand-700);
|
||||
--color-brand-800: var(--brand-800);
|
||||
--color-brand-900: var(--brand-900);
|
||||
--color-brand-950: var(--brand-950);
|
||||
}
|
||||
127
inhaus-sdk/vite.js
Normal file
127
inhaus-sdk/vite.js
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
/**
|
||||
* Vite-Voreinstellung für Inhaus-Plugins (Plugin-SDK).
|
||||
*
|
||||
* // vite.config.js im Plugin
|
||||
* import { defineConfig } from 'vite';
|
||||
* import { inhausPlugin } from './inhaus-sdk/vite.js';
|
||||
* export default defineConfig(inhausPlugin());
|
||||
*
|
||||
* Baut jede Vue-Datei unter resources/js/{pages,widgets,blocks,profile,profile-panels,editorial,header}/
|
||||
* als eigenes ES-Modul nach dist/ und schreibt dist/inhaus.json. Vue, Inertia und @inhaus/ui
|
||||
* bleiben extern – das Portal stellt sie per Import Map bereit.
|
||||
*/
|
||||
import { existsSync, globSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import postcss from 'postcss';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
|
||||
export const KINDS = ['pages', 'widgets', 'blocks', 'profile', 'profile-panels', 'editorial', 'header'];
|
||||
export const EXTERNAL = ['vue', '@inertiajs/vue3', '@inhaus/ui'];
|
||||
|
||||
export function inhausPlugin({ root = process.cwd() } = {}) {
|
||||
const input = {};
|
||||
|
||||
for (const kind of KINDS) {
|
||||
for (const file of globSync(`resources/js/${kind}/**/*.vue`, { cwd: root })) {
|
||||
const name = file.replace(`resources/js/${kind}/`, '').replace(/\.vue$/, '');
|
||||
input[`${kind}/${name}`] = resolve(root, file);
|
||||
}
|
||||
}
|
||||
|
||||
if (existsSync(resolve(root, 'resources/css/style.css'))) {
|
||||
input.style = resolve(root, 'resources/css/style.css');
|
||||
}
|
||||
|
||||
if (Object.keys(input).length === 0) {
|
||||
throw new Error('Keine Oberfläche gefunden: Vue-Dateien gehören nach resources/js/<pages|widgets|blocks|profile|profile-panels|editorial|header>/.');
|
||||
}
|
||||
|
||||
return {
|
||||
plugins: [vue(), tailwindcss(), manifest(Object.keys(input)), strongerVariants()],
|
||||
// Plugins laufen unter /plugin-assets/<slug>/<version>/ – Pfade relativ halten
|
||||
base: './',
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
target: 'es2022',
|
||||
rollupOptions: {
|
||||
input,
|
||||
external: EXTERNAL,
|
||||
preserveEntrySignatures: 'strict',
|
||||
output: {
|
||||
format: 'es',
|
||||
entryFileNames: '[name].js',
|
||||
chunkFileNames: 'chunks/[name]-[hash].js',
|
||||
assetFileNames: 'assets/[name]-[hash][extname]',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** dist/inhaus.json: welche Komponente in welcher Datei steckt, welches CSS dazugehört */
|
||||
function manifest(entries) {
|
||||
return {
|
||||
name: 'inhaus-manifest',
|
||||
generateBundle(_, bundle) {
|
||||
const components = {};
|
||||
const css = [];
|
||||
|
||||
for (const file of Object.values(bundle)) {
|
||||
if (file.type === 'chunk' && file.isEntry && entries.includes(file.name) && file.name !== 'style') {
|
||||
components[file.name] = file.fileName;
|
||||
}
|
||||
|
||||
if (file.type === 'asset' && file.fileName.endsWith('.css')) {
|
||||
css.push(file.fileName);
|
||||
}
|
||||
}
|
||||
|
||||
// Leere Hülle des CSS-Einstiegs nicht ausliefern
|
||||
for (const [key, file] of Object.entries(bundle)) {
|
||||
if (file.type === 'chunk' && file.name === 'style') delete bundle[key];
|
||||
}
|
||||
|
||||
this.emitFile({ type: 'asset', fileName: 'inhaus.json', source: JSON.stringify({ components, css: [...new Set(css)] }, null, 4) });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mehrere Plugins bringen jeweils eigenes CSS mit, und dieselbe Hilfsklasse (z. B. ih:grid) kann in
|
||||
* mehreren Dateien stehen. Lädt ein anderes Plugin sein CSS später, würde dessen „ih:grid“ sonst
|
||||
* die Varianten dieses Plugins (ih:lg:hidden, ih:hover:…) überstimmen. Deshalb bekommen Regeln
|
||||
* mit Variante (Media Query, :hover …) eine doppelte Klasse – sie gewinnen so immer gegen
|
||||
* einfache Klassen, egal in welcher Reihenfolge die Dateien laden.
|
||||
*/
|
||||
export function strongerVariants() {
|
||||
const pseudo = /(?<!\\):/;
|
||||
const firstClass = /\.((?:\\.|[\w-])+)/;
|
||||
|
||||
return {
|
||||
name: 'inhaus-stronger-variants',
|
||||
enforce: 'post',
|
||||
generateBundle(_, bundle) {
|
||||
for (const file of Object.values(bundle)) {
|
||||
if (file.type !== 'asset' || !file.fileName.endsWith('.css')) continue;
|
||||
|
||||
const root = postcss.parse(String(file.source));
|
||||
|
||||
root.walkRules((rule) => {
|
||||
let conditional = false;
|
||||
|
||||
for (let parent = rule.parent; parent && parent.type !== 'root'; parent = parent.parent) {
|
||||
if (parent.type === 'atrule' && parent.name !== 'layer') conditional = true;
|
||||
}
|
||||
|
||||
rule.selectors = rule.selectors.map((selector) => (conditional || pseudo.test(selector.replace(/^[^.]*/, ''))) && firstClass.test(selector)
|
||||
? selector.replace(firstClass, (match) => match + match)
|
||||
: selector);
|
||||
});
|
||||
|
||||
file.source = root.toString();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
1728
package-lock.json
generated
Normal file
1728
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
22
package.json
Normal file
22
package.json
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"name": "inhaus-plugin-chat",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"dev": "vite build --watch",
|
||||
"package": "vite build && php bin/package"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@vitejs/plugin-vue": "^6.0.9",
|
||||
"postcss": "^8.5.28",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"vite": "^8.3.1",
|
||||
"vue": "^3.5.43"
|
||||
},
|
||||
"dependencies": {
|
||||
"@lucide/vue": "^1.48.0",
|
||||
"pusher-js": "^8.6.0"
|
||||
}
|
||||
}
|
||||
14
plugin.json
Normal file
14
plugin.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"slug": "chat",
|
||||
"name": "Nachrichten",
|
||||
"version": "1.0.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\\",
|
||||
"class": "Inhaus\\Plugins\\Chat\\ChatPlugin",
|
||||
"requires": {
|
||||
"core": ">=0.39.0",
|
||||
"php": ">=8.3"
|
||||
},
|
||||
"update_url": "https://git.loheide.cloud/api/v1/repos/friloo/inhaus-plugin-chat/releases/latest"
|
||||
}
|
||||
3
resources/css/style.css
Normal file
3
resources/css/style.css
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
/* Tailwind mit den Design-Tokens des Portals – Klassen mit Präfix „ih:“, z. B. ih:bg-brand, ih:text-muted-foreground, ih:rounded-lg */
|
||||
@import "../../inhaus-sdk/theme.css";
|
||||
@source "../js";
|
||||
17
resources/js/components/ChatAvatar.vue
Normal file
17
resources/js/components/ChatAvatar.vue
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<script setup>
|
||||
import { Users } from '@lucide/vue';
|
||||
import { PersonAvatar } from '@inhaus/ui';
|
||||
|
||||
/** Bild eines Gesprächs: Person bei Direktnachrichten, Symbol bei Gruppen */
|
||||
defineProps({
|
||||
conversation: { type: Object, required: true },
|
||||
size: { type: String, default: 'ih:size-10' },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PersonAvatar v-if="conversation.person" :person="conversation.person" :class="size" />
|
||||
<span v-else class="ih:grid ih:shrink-0 ih:place-items-center ih:rounded-full ih:bg-brand-soft ih:text-brand-text" :class="size" aria-hidden="true">
|
||||
<Users class="ih:size-[45%]" />
|
||||
</span>
|
||||
</template>
|
||||
199
resources/js/components/Composer.vue
Normal file
199
resources/js/components/Composer.vue
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
<script setup>
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { File as FileGlyph, Image as ImageGlyph, LoaderCircle, Paperclip, Pencil, SendHorizontal, Smile, X } from '@lucide/vue';
|
||||
import { toast } from '@inhaus/ui';
|
||||
import EmojiPicker from './EmojiPicker.vue';
|
||||
import GifPicker from './GifPicker.vue';
|
||||
import Popup from './Popup.vue';
|
||||
import { fileSize } from '../lib/format';
|
||||
|
||||
const props = defineProps({
|
||||
replyTo: { type: Object, default: null },
|
||||
editing: { type: Object, default: null },
|
||||
maxUploadMb: { type: Number, default: 25 },
|
||||
sending: { type: Boolean, default: false },
|
||||
});
|
||||
const emit = defineEmits(['send', 'save-edit', 'cancel', 'typing']);
|
||||
|
||||
const text = ref('');
|
||||
const files = ref([]);
|
||||
const input = ref(null);
|
||||
const fileInput = ref(null);
|
||||
const popup = ref(null); // 'emoji' | 'gif'
|
||||
const canSend = computed(() => !props.sending && (text.value.trim() || files.value.length));
|
||||
|
||||
// Beim Bearbeiten den Text übernehmen
|
||||
watch(() => props.editing, (message) => {
|
||||
text.value = message?.body ?? '';
|
||||
nextTick(focus);
|
||||
});
|
||||
watch(() => props.replyTo, (message) => message && nextTick(focus));
|
||||
|
||||
function focus() {
|
||||
input.value?.focus();
|
||||
resize();
|
||||
}
|
||||
|
||||
function resize() {
|
||||
const el = input.value;
|
||||
|
||||
if (!el) return;
|
||||
|
||||
el.style.height = 'auto';
|
||||
el.style.height = `${Math.min(el.scrollHeight, 180)}px`;
|
||||
}
|
||||
|
||||
let lastTyping = 0;
|
||||
function onInput() {
|
||||
resize();
|
||||
|
||||
if (Date.now() - lastTyping > 3000 && text.value.trim()) {
|
||||
lastTyping = Date.now();
|
||||
emit('typing');
|
||||
}
|
||||
}
|
||||
|
||||
function addFiles(list) {
|
||||
for (const file of list) {
|
||||
if (file.size > props.maxUploadMb * 1024 * 1024) {
|
||||
toast.error(`„${file.name}“ ist größer als ${props.maxUploadMb} MB.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (files.value.length >= 10) {
|
||||
toast.error('Höchstens 10 Dateien je Nachricht.');
|
||||
break;
|
||||
}
|
||||
|
||||
files.value.push({ file, url: file.type.startsWith('image/') ? URL.createObjectURL(file) : null });
|
||||
}
|
||||
|
||||
focus();
|
||||
}
|
||||
|
||||
function onPaste(event) {
|
||||
const pasted = [...(event.clipboardData?.files ?? [])];
|
||||
|
||||
if (pasted.length) {
|
||||
event.preventDefault();
|
||||
addFiles(pasted);
|
||||
}
|
||||
}
|
||||
|
||||
function removeFile(index) {
|
||||
const [removed] = files.value.splice(index, 1);
|
||||
removed?.url && URL.revokeObjectURL(removed.url);
|
||||
}
|
||||
|
||||
function submit() {
|
||||
if (props.editing) {
|
||||
text.value.trim() && emit('save-edit', text.value.trim());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!canSend.value) return;
|
||||
|
||||
emit('send', { body: text.value, files: files.value.map((f) => f.file) });
|
||||
files.value.forEach((f) => f.url && URL.revokeObjectURL(f.url));
|
||||
files.value = [];
|
||||
text.value = '';
|
||||
nextTick(resize);
|
||||
}
|
||||
|
||||
function onKeydown(event) {
|
||||
// Enter sendet, Umschalt+Enter macht eine neue Zeile
|
||||
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
|
||||
event.preventDefault();
|
||||
submit();
|
||||
}
|
||||
|
||||
if (event.key === 'Escape' && (props.editing || props.replyTo)) emit('cancel');
|
||||
}
|
||||
|
||||
function insertEmoji(emoji) {
|
||||
const el = input.value;
|
||||
const start = el?.selectionStart ?? text.value.length;
|
||||
const end = el?.selectionEnd ?? text.value.length;
|
||||
text.value = text.value.slice(0, start) + emoji + text.value.slice(end);
|
||||
nextTick(() => {
|
||||
el?.focus();
|
||||
el?.setSelectionRange(start + emoji.length, start + emoji.length);
|
||||
});
|
||||
}
|
||||
|
||||
function pickGif(gif) {
|
||||
popup.value = null;
|
||||
emit('send', { gifUrl: gif.url });
|
||||
}
|
||||
|
||||
const toggle = (name) => (popup.value = popup.value === name ? null : name);
|
||||
|
||||
defineExpose({ addFiles, focus });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="ih:border-t ih:bg-card ih:p-3">
|
||||
<!-- Antworten / Bearbeiten -->
|
||||
<div v-if="replyTo || editing" class="ih:mb-2 ih:flex ih:items-start ih:gap-2 ih:rounded-md ih:border-l-3 ih:border-brand ih:bg-muted ih:px-3 ih:py-1.5 ih:text-[13px]">
|
||||
<Pencil v-if="editing" class="ih:mt-0.5 ih:size-3.5 ih:shrink-0 ih:text-brand-text" />
|
||||
<span class="ih:min-w-0 ih:flex-1">
|
||||
<span class="ih:block ih:font-semibold">{{ editing ? 'Nachricht bearbeiten' : `Antwort an ${replyTo.user?.name ?? ''}` }}</span>
|
||||
<span v-if="replyTo" class="ih:line-clamp-1 ih:text-muted-foreground">{{ replyTo.body || (replyTo.gif_url ? 'GIF' : 'Datei') }}</span>
|
||||
</span>
|
||||
<button type="button" class="ih:rounded ih:p-0.5 ih:text-muted-foreground ih:hover:text-foreground" aria-label="Abbrechen" @click="emit('cancel')"><X class="ih:size-4" /></button>
|
||||
</div>
|
||||
|
||||
<!-- Ausgewählte Dateien -->
|
||||
<ul v-if="files.length" class="ih:mb-2 ih:flex ih:gap-2 ih:overflow-x-auto ih:pb-1">
|
||||
<li v-for="(f, i) in files" :key="i" class="ih:relative ih:shrink-0">
|
||||
<img v-if="f.url" :src="f.url" :alt="f.file.name" class="ih:size-16 ih:rounded-md ih:border ih:object-cover" />
|
||||
<span v-else class="ih:flex ih:h-16 ih:w-36 ih:items-center ih:gap-2 ih:rounded-md ih:border ih:bg-muted ih:px-2 ih:text-xs">
|
||||
<FileGlyph class="ih:size-5 ih:shrink-0 ih:text-muted-foreground" />
|
||||
<span class="ih:min-w-0"><span class="ih:block ih:truncate ih:font-medium">{{ f.file.name }}</span>{{ fileSize(f.file.size) }}</span>
|
||||
</span>
|
||||
<button type="button" class="ih:absolute ih:-top-1.5 ih:-right-1.5 ih:grid ih:size-5 ih:place-items-center ih:rounded-full ih:bg-foreground ih:text-background" :aria-label="`${f.file.name} entfernen`" @click="removeFile(i)"><X class="ih:size-3" /></button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="ih:relative ih:flex ih:items-end ih:gap-1">
|
||||
<Popup v-if="popup === 'emoji'" @close="popup = null"><EmojiPicker @pick="insertEmoji" /></Popup>
|
||||
<Popup v-if="popup === 'gif'" @close="popup = null"><GifPicker @pick="pickGif" /></Popup>
|
||||
|
||||
<template v-if="!editing">
|
||||
<button type="button" data-popup-toggle class="ih:grid ih:size-10 ih:shrink-0 ih:place-items-center ih:rounded-full ih:text-muted-foreground ih:hover:bg-muted ih:hover:text-foreground" :class="{ 'ih:bg-muted ih:text-foreground': popup === 'emoji' }" aria-label="Emoji einfügen" :aria-expanded="popup === 'emoji'" @click="toggle('emoji')"><Smile class="ih:size-5" /></button>
|
||||
<button type="button" data-popup-toggle class="ih:grid ih:h-10 ih:shrink-0 ih:place-items-center ih:rounded-full ih:px-2 ih:text-xs ih:font-bold ih:text-muted-foreground ih:hover:bg-muted ih:hover:text-foreground" :class="{ 'ih:bg-muted ih:text-foreground': popup === 'gif' }" aria-label="GIF senden" :aria-expanded="popup === 'gif'" @click="toggle('gif')">GIF</button>
|
||||
<button type="button" class="ih:grid ih:size-10 ih:shrink-0 ih:place-items-center ih:rounded-full ih:text-muted-foreground ih:hover:bg-muted ih:hover:text-foreground" aria-label="Datei anhängen" @click="fileInput?.click()"><Paperclip class="ih:size-5" /></button>
|
||||
<input ref="fileInput" type="file" multiple class="ih:hidden" @change="addFiles([...$event.target.files]); $event.target.value = ''" />
|
||||
</template>
|
||||
|
||||
<textarea
|
||||
ref="input"
|
||||
v-model="text"
|
||||
rows="1"
|
||||
maxlength="5000"
|
||||
:placeholder="editing ? 'Nachricht bearbeiten' : 'Nachricht schreiben'"
|
||||
aria-label="Nachricht"
|
||||
class="ih:max-h-[180px] ih:min-h-10 ih:flex-1 ih:resize-none ih:rounded-2xl ih:border ih:border-input ih:bg-background ih:px-4 ih:py-2 ih:text-[15px] ih:leading-snug ih:focus-visible:ring-3 ih:focus-visible:ring-ring/30 ih:focus-visible:outline-none"
|
||||
@input="onInput"
|
||||
@keydown="onKeydown"
|
||||
@paste="onPaste"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="ih:grid ih:size-10 ih:shrink-0 ih:place-items-center ih:rounded-full ih:bg-brand ih:text-brand-foreground ih:transition-opacity ih:disabled:opacity-40"
|
||||
:disabled="editing ? !text.trim() : !canSend"
|
||||
:aria-label="editing ? 'Speichern' : 'Senden'"
|
||||
@click="submit"
|
||||
>
|
||||
<LoaderCircle v-if="sending" class="ih:size-5 ih:animate-spin" />
|
||||
<SendHorizontal v-else class="ih:size-5" />
|
||||
</button>
|
||||
</div>
|
||||
<p class="ih:mt-1.5 ih:hidden ih:text-[11px] ih:text-muted-foreground ih:sm:block">
|
||||
<kbd class="ih:font-sans">Enter</kbd> senden · <kbd class="ih:font-sans">Umschalt + Enter</kbd> neue Zeile · Bilder lassen sich auch einfügen oder hierher ziehen
|
||||
<ImageGlyph class="ih:inline ih:size-3" />
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
105
resources/js/components/ConversationInfo.vue
Normal file
105
resources/js/components/ConversationInfo.vue
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
<script setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { Crown, EyeOff, LoaderCircle, LogOut, UserMinus, UserPlus } from '@lucide/vue';
|
||||
import { Button, Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, Input, PersonAvatar, Switch, toast } from '@inhaus/ui';
|
||||
import PeopleSelect from './PeopleSelect.vue';
|
||||
import { api } from '../lib/api';
|
||||
|
||||
/** Einstellungen eines Gesprächs: Stummschalten, Mitglieder (Gruppen), Verlassen bzw. Ausblenden */
|
||||
const props = defineProps({
|
||||
conversation: { type: Object, required: true },
|
||||
me: { type: Object, required: true },
|
||||
});
|
||||
const open = defineModel('open', { type: Boolean, default: false });
|
||||
const emit = defineEmits(['updated', 'left']);
|
||||
|
||||
const isGroup = computed(() => props.conversation.type === 'group');
|
||||
const name = ref('');
|
||||
const adding = ref([]);
|
||||
const busy = ref(false);
|
||||
|
||||
watch(open, (value) => {
|
||||
if (value) {
|
||||
name.value = props.conversation.name;
|
||||
adding.value = [];
|
||||
}
|
||||
});
|
||||
|
||||
async function run(action, message) {
|
||||
busy.value = true;
|
||||
|
||||
try {
|
||||
const data = await action();
|
||||
emit('updated', data.conversations);
|
||||
message && toast.success(message);
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const rename = () => run(() => api.updateConversation(props.conversation.id, { name: name.value.trim() }), 'Gruppe umbenannt');
|
||||
const mute = (muted) => run(() => api.updateConversation(props.conversation.id, { muted }), muted ? 'Stummgeschaltet – keine Benachrichtigungen mehr' : 'Benachrichtigungen wieder an');
|
||||
const add = () => run(() => api.addMembers(props.conversation.id, adding.value.map((p) => p.id)), 'Hinzugefügt').then(() => (adding.value = []));
|
||||
const removeMember = (member) => window.confirm(`${member.name} aus der Gruppe entfernen?`) && run(() => api.removeMember(props.conversation.id, member.id));
|
||||
const toggleAdmin = (member) => run(() => api.setAdmin(props.conversation.id, member.id, !member.admin));
|
||||
|
||||
async function leave() {
|
||||
if (!window.confirm(isGroup.value ? 'Gruppe verlassen? Sie sehen die Nachrichten danach nicht mehr.' : 'Gespräch aus Ihrer Liste entfernen? Mit der nächsten Nachricht erscheint es wieder.')) return;
|
||||
|
||||
await run(() => api.leave(props.conversation.id));
|
||||
open.value = false;
|
||||
emit('left');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<DialogContent class="ih:max-h-[85dvh] ih:overflow-y-auto ih:sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ conversation.name }}</DialogTitle>
|
||||
<DialogDescription>{{ isGroup ? `Gruppe mit ${conversation.members.length} Mitgliedern` : 'Direktnachricht' }}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="ih:grid ih:gap-5">
|
||||
<form v-if="isGroup && conversation.is_admin" class="ih:flex ih:gap-2" @submit.prevent="rename">
|
||||
<Input v-model="name" maxlength="100" aria-label="Name der Gruppe" />
|
||||
<Button type="submit" variant="outline" :disabled="busy || !name.trim() || name.trim() === conversation.name">Umbenennen</Button>
|
||||
</form>
|
||||
|
||||
<label class="ih:flex ih:items-center ih:justify-between ih:gap-3 ih:text-sm">
|
||||
<span><span class="ih:font-medium">Stummschalten</span><span class="ih:block ih:text-xs ih:text-muted-foreground">Keine Glocke und kein Push für dieses Gespräch.</span></span>
|
||||
<Switch :model-value="conversation.muted" :disabled="busy" @update:model-value="mute" />
|
||||
</label>
|
||||
|
||||
<section v-if="isGroup" class="ih:grid ih:gap-2">
|
||||
<h3 class="ih:text-sm ih:font-semibold">Mitglieder</h3>
|
||||
<ul class="ih:-mx-2 ih:grid">
|
||||
<li v-for="member in conversation.members" :key="member.id" class="ih:flex ih:items-center ih:gap-3 ih:rounded-md ih:px-2 ih:py-1.5 ih:hover:bg-muted/60">
|
||||
<PersonAvatar :person="member" class="ih:size-8 ih:text-[11px]" />
|
||||
<span class="ih:min-w-0 ih:flex-1 ih:text-sm">
|
||||
<span class="ih:font-medium">{{ member.name }}</span><span v-if="member.id === me.id" class="ih:text-muted-foreground"> (Sie)</span>
|
||||
<span v-if="member.admin" class="ih:ml-1.5 ih:inline-flex ih:items-center ih:gap-0.5 ih:text-xs ih:text-brand-text"><Crown class="ih:size-3" /> Admin</span>
|
||||
</span>
|
||||
<template v-if="conversation.is_admin && member.id !== me.id">
|
||||
<button type="button" class="ih:rounded ih:p-1.5 ih:text-muted-foreground ih:hover:bg-accent ih:hover:text-foreground" :title="member.admin ? 'Admin-Rechte entziehen' : 'Zum Admin machen'" :aria-label="member.admin ? `${member.name}: Admin-Rechte entziehen` : `${member.name} zum Admin machen`" @click="toggleAdmin(member)"><Crown class="ih:size-4" /></button>
|
||||
<button type="button" class="ih:rounded ih:p-1.5 ih:text-muted-foreground ih:hover:bg-accent ih:hover:text-destructive" :aria-label="`${member.name} entfernen`" @click="removeMember(member)"><UserMinus class="ih:size-4" /></button>
|
||||
</template>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-if="conversation.is_admin" class="ih:grid ih:gap-2 ih:rounded-md ih:border ih:p-3">
|
||||
<span class="ih:flex ih:items-center ih:gap-1.5 ih:text-sm ih:font-medium"><UserPlus class="ih:size-4" /> Personen hinzufügen</span>
|
||||
<PeopleSelect v-model="adding" multiple :exclude="conversation.members.map((m) => m.id)" />
|
||||
<Button v-if="adding.length" size="sm" class="ih:justify-self-start" :disabled="busy" @click="add"><LoaderCircle v-if="busy" class="ih:animate-spin" /> {{ adding.length }} hinzufügen</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Button variant="outline" class="ih:justify-self-start ih:text-destructive ih:hover:text-destructive" :disabled="busy" @click="leave">
|
||||
<component :is="isGroup ? LogOut : EyeOff" /> {{ isGroup ? 'Gruppe verlassen' : 'Aus der Liste entfernen' }}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
64
resources/js/components/ConversationList.vue
Normal file
64
resources/js/components/ConversationList.vue
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
<script setup>
|
||||
import { computed, ref } from 'vue';
|
||||
import { BellOff, MessageSquarePlus, Search, UsersRound } from '@lucide/vue';
|
||||
import { Button } from '@inhaus/ui';
|
||||
import ChatAvatar from './ChatAvatar.vue';
|
||||
import { listTime } from '../lib/format';
|
||||
|
||||
const props = defineProps({
|
||||
conversations: { type: Array, required: true },
|
||||
activeId: { type: Number, default: null },
|
||||
canCreateGroups: { type: Boolean, default: false },
|
||||
});
|
||||
const emit = defineEmits(['open', 'new-chat', 'new-group']);
|
||||
|
||||
const query = ref('');
|
||||
const filtered = computed(() => {
|
||||
const q = query.value.trim().toLowerCase();
|
||||
|
||||
return q ? props.conversations.filter((c) => [c.name, ...c.members.map((m) => m.name)].join(' ').toLowerCase().includes(q)) : props.conversations;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="ih:flex ih:h-full ih:min-h-0 ih:flex-col">
|
||||
<div class="ih:flex ih:items-center ih:gap-2 ih:border-b ih:p-3">
|
||||
<h1 class="ih:flex-1 ih:text-lg ih:font-semibold ih:tracking-tight">Nachrichten</h1>
|
||||
<Button v-if="canCreateGroups" variant="ghost" size="icon" title="Neue Gruppe" aria-label="Neue Gruppe" @click="emit('new-group')"><UsersRound /></Button>
|
||||
<Button size="icon" title="Neue Nachricht" aria-label="Neue Nachricht" @click="emit('new-chat')"><MessageSquarePlus /></Button>
|
||||
</div>
|
||||
<div class="ih:border-b ih:p-3">
|
||||
<div class="ih:relative">
|
||||
<Search class="ih:pointer-events-none ih:absolute ih:top-1/2 ih:left-2.5 ih:size-4 ih:-translate-y-1/2 ih:text-muted-foreground" />
|
||||
<input v-model="query" type="search" placeholder="Gespräche durchsuchen" aria-label="Gespräche durchsuchen" class="ih:h-9 ih:w-full ih:rounded-md ih:bg-muted ih:pr-3 ih:pl-8 ih:text-sm ih:focus-visible:ring-3 ih:focus-visible:ring-ring/30 ih:focus-visible:outline-none" />
|
||||
</div>
|
||||
</div>
|
||||
<ul class="ih:min-h-0 ih:flex-1 ih:overflow-y-auto" aria-label="Gespräche">
|
||||
<li v-for="c in filtered" :key="c.id">
|
||||
<button
|
||||
type="button"
|
||||
class="ih:flex ih:w-full ih:items-center ih:gap-3 ih:px-3 ih:py-2.5 ih:text-left ih:transition-colors"
|
||||
:class="c.id === activeId ? 'ih:bg-brand-soft' : 'ih:hover:bg-accent/60'"
|
||||
:aria-current="c.id === activeId ? 'true' : undefined"
|
||||
@click="emit('open', c.id)"
|
||||
>
|
||||
<ChatAvatar :conversation="c" size="ih:size-11" />
|
||||
<span class="ih:min-w-0 ih:flex-1">
|
||||
<span class="ih:flex ih:items-baseline ih:gap-2">
|
||||
<span class="ih:min-w-0 ih:flex-1 ih:truncate ih:text-sm" :class="c.unread ? 'ih:font-semibold' : 'ih:font-medium'">{{ c.name }}</span>
|
||||
<span class="ih:shrink-0 ih:text-[11px] ih:text-muted-foreground ih:tabular-nums">{{ listTime(c.last_message_at) }}</span>
|
||||
</span>
|
||||
<span class="ih:flex ih:items-center ih:gap-2">
|
||||
<span class="ih:min-w-0 ih:flex-1 ih:truncate ih:text-[13px]" :class="c.unread ? 'ih:text-foreground' : 'ih:text-muted-foreground'">{{ c.preview ?? (c.type === 'group' ? `${c.members.length} Mitglieder` : 'Noch keine Nachrichten') }}</span>
|
||||
<BellOff v-if="c.muted" class="ih:size-3.5 ih:shrink-0 ih:text-muted-foreground" aria-label="Stummgeschaltet" />
|
||||
<span v-if="c.unread" class="ih:grid ih:h-5 ih:min-w-5 ih:shrink-0 ih:place-items-center ih:rounded-full ih:bg-brand ih:px-1.5 ih:text-[11px] ih:font-semibold ih:text-brand-foreground ih:tabular-nums" :aria-label="`${c.unread} ungelesen`">{{ c.unread > 99 ? '99+' : c.unread }}</span>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
<li v-if="!filtered.length" class="ih:p-6 ih:text-center ih:text-sm ih:text-muted-foreground">
|
||||
{{ query ? 'Nichts gefunden.' : 'Noch keine Gespräche. Oben rechts eine neue Nachricht beginnen.' }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
28
resources/js/components/EmojiPicker.vue
Normal file
28
resources/js/components/EmojiPicker.vue
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import { EMOJI_GROUPS } from '../lib/emojis';
|
||||
|
||||
const emit = defineEmits(['pick']);
|
||||
const group = ref(0);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="ih:flex ih:border-b ih:px-1" role="tablist" aria-label="Emoji-Gruppen">
|
||||
<button
|
||||
v-for="(g, i) in EMOJI_GROUPS"
|
||||
:key="g.label"
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="group === i"
|
||||
:title="g.label"
|
||||
class="ih:grid ih:size-9 ih:place-items-center ih:text-lg ih:transition-opacity"
|
||||
:class="group === i ? 'ih:border-b-2 ih:border-brand' : 'ih:opacity-60 ih:hover:opacity-100'"
|
||||
@click="group = i"
|
||||
>{{ g.icon }}</button>
|
||||
</div>
|
||||
<div class="ih:grid ih:max-h-60 ih:grid-cols-8 ih:gap-0.5 ih:overflow-y-auto ih:p-2" role="tabpanel" :aria-label="EMOJI_GROUPS[group].label">
|
||||
<button v-for="emoji in EMOJI_GROUPS[group].emojis" :key="emoji" type="button" class="ih:grid ih:aspect-square ih:place-items-center ih:rounded ih:text-xl ih:hover:bg-accent" :aria-label="emoji" @click="emit('pick', emoji)">{{ emoji }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
51
resources/js/components/GifPicker.vue
Normal file
51
resources/js/components/GifPicker.vue
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
<script setup>
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
import { LoaderCircle, Search } from '@lucide/vue';
|
||||
import { api } from '../lib/api';
|
||||
|
||||
const emit = defineEmits(['pick']);
|
||||
const query = ref('');
|
||||
const gifs = ref([]);
|
||||
const giphy = ref(false);
|
||||
const loading = ref(false);
|
||||
let timer;
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
const data = await api.gifs(query.value);
|
||||
gifs.value = data.gifs;
|
||||
giphy.value = data.giphy;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(query, () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(load, 300);
|
||||
});
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="ih:border-b ih:p-2">
|
||||
<div class="ih:relative">
|
||||
<Search class="ih:pointer-events-none ih:absolute ih:top-1/2 ih:left-2.5 ih:size-4 ih:-translate-y-1/2 ih:text-muted-foreground" />
|
||||
<input v-model="query" type="search" placeholder="GIFs suchen" aria-label="GIFs suchen" autofocus class="ih:h-9 ih:w-full ih:rounded-md ih:bg-muted ih:pr-3 ih:pl-8 ih:text-sm ih:focus-visible:outline-none" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="ih:max-h-72 ih:overflow-y-auto ih:p-2">
|
||||
<div v-if="loading && !gifs.length" class="ih:grid ih:place-items-center ih:py-8"><LoaderCircle class="ih:size-5 ih:animate-spin ih:text-muted-foreground" /></div>
|
||||
<div v-else-if="gifs.length" class="ih:columns-2 ih:gap-1.5">
|
||||
<button v-for="gif in gifs" :key="gif.url" type="button" class="ih:mb-1.5 ih:block ih:w-full ih:overflow-hidden ih:rounded ih:bg-muted ih:hover:ring-2 ih:hover:ring-brand" :title="gif.title" @click="emit('pick', gif)">
|
||||
<img :src="gif.preview" :alt="gif.title" loading="lazy" class="ih:block ih:w-full" :style="gif.width && gif.height ? { aspectRatio: `${gif.width} / ${gif.height}` } : {}" />
|
||||
</button>
|
||||
</div>
|
||||
<p v-else class="ih:py-6 ih:text-center ih:text-sm ih:text-muted-foreground">{{ query ? 'Keine GIFs gefunden.' : 'Noch keine GIFs in der Sammlung.' }}</p>
|
||||
</div>
|
||||
<p v-if="giphy" class="ih:border-t ih:px-3 ih:py-1.5 ih:text-[10px] ih:text-muted-foreground">Mit Suche über GIPHY – Suchbegriffe gehen an GIPHY.</p>
|
||||
</div>
|
||||
</template>
|
||||
124
resources/js/components/MessageBubble.vue
Normal file
124
resources/js/components/MessageBubble.vue
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { CornerUpLeft, Download, Pencil, SmilePlus, Trash2 } from '@lucide/vue';
|
||||
import { FileIcon, PersonAvatar } from '@inhaus/ui';
|
||||
import { fileSize, linkify, messageTime, onlyEmoji } from '../lib/format';
|
||||
|
||||
const props = defineProps({
|
||||
message: { type: Object, required: true },
|
||||
showAuthor: { type: Boolean, default: true },
|
||||
showAvatar: { type: Boolean, default: true },
|
||||
group: { type: Boolean, default: false },
|
||||
reactions: { type: Array, required: true },
|
||||
read: { type: Boolean, default: false },
|
||||
});
|
||||
const emit = defineEmits(['react', 'reply', 'edit', 'delete', 'jump']);
|
||||
|
||||
const m = computed(() => props.message);
|
||||
const bigEmoji = computed(() => !m.value.attachments.length && !m.value.reply_to && onlyEmoji(m.value.body));
|
||||
const images = computed(() => m.value.attachments.filter((a) => a.image));
|
||||
const files = computed(() => m.value.attachments.filter((a) => !a.image));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Systemmeldung (Gruppe erstellt, Person hinzugefügt …) -->
|
||||
<div v-if="m.kind === 'system'" class="ih:my-3 ih:text-center">
|
||||
<span class="ih:inline-block ih:rounded-full ih:bg-muted ih:px-3 ih:py-1 ih:text-xs ih:text-muted-foreground">{{ m.body }}</span>
|
||||
</div>
|
||||
|
||||
<div v-else :id="`nachricht-${m.id}`" class="ih:group ih:flex ih:items-end ih:gap-2" :class="[m.mine ? 'ih:flex-row-reverse' : '', showAuthor ? 'ih:mt-3' : 'ih:mt-0.5']">
|
||||
<div v-if="group && !m.mine" class="ih:w-8 ih:shrink-0">
|
||||
<PersonAvatar v-if="showAvatar && m.user" :person="m.user" class="ih:size-8 ih:text-[11px]" />
|
||||
</div>
|
||||
|
||||
<div class="ih:flex ih:max-w-[min(34rem,80%)] ih:min-w-0 ih:flex-col" :class="m.mine ? 'ih:items-end' : 'ih:items-start'">
|
||||
<span v-if="group && !m.mine && showAuthor" class="ih:mb-0.5 ih:px-3 ih:text-xs ih:font-medium ih:text-muted-foreground">{{ m.user?.name ?? 'Gelöschtes Konto' }}</span>
|
||||
|
||||
<div class="ih:relative ih:flex ih:items-center ih:gap-1" :class="m.mine ? 'ih:flex-row-reverse' : ''">
|
||||
<!-- Blase -->
|
||||
<div
|
||||
v-if="m.deleted"
|
||||
class="ih:rounded-2xl ih:border ih:border-dashed ih:px-3 ih:py-2 ih:text-sm ih:text-muted-foreground ih:italic"
|
||||
>Nachricht gelöscht</div>
|
||||
<div
|
||||
v-else
|
||||
class="ih:min-w-0 ih:overflow-hidden ih:text-[15px] ih:leading-snug"
|
||||
:class="bigEmoji || m.kind === 'gif' ? '' : [m.mine ? 'ih:rounded-2xl ih:rounded-br-md ih:bg-brand ih:text-brand-foreground' : 'ih:rounded-2xl ih:rounded-bl-md ih:border ih:bg-card', images.length && !m.body ? '' : 'ih:px-3 ih:py-2']"
|
||||
>
|
||||
<button
|
||||
v-if="m.reply_to"
|
||||
type="button"
|
||||
class="ih:mb-1.5 ih:block ih:w-full ih:rounded-md ih:border-l-3 ih:px-2 ih:py-1 ih:text-left ih:text-[13px]"
|
||||
:class="m.mine ? 'ih:border-white/60 ih:bg-white/15' : 'ih:border-brand ih:bg-muted'"
|
||||
@click="emit('jump', m.reply_to.id)"
|
||||
>
|
||||
<span class="ih:block ih:font-semibold">{{ m.reply_to.name }}</span>
|
||||
<span class="ih:line-clamp-2 ih:opacity-80">{{ m.reply_to.text }}</span>
|
||||
</button>
|
||||
|
||||
<img v-if="m.kind === 'gif'" :src="m.gif_url" alt="GIF" loading="lazy" class="ih:max-h-60 ih:rounded-2xl" />
|
||||
|
||||
<div v-if="images.length" class="ih:grid ih:gap-0.5" :class="images.length > 1 ? 'ih:grid-cols-2' : ''">
|
||||
<a v-for="img in images" :key="img.id" :href="img.url" target="_blank" rel="noopener" class="ih:block ih:overflow-hidden ih:bg-muted" :title="img.name">
|
||||
<img :src="img.url" :alt="img.name" loading="lazy" class="ih:block ih:max-h-72 ih:w-full ih:object-cover" :style="img.width ? { aspectRatio: `${img.width} / ${img.height}` } : {}" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<a
|
||||
v-for="file in files"
|
||||
:key="file.id"
|
||||
:href="file.url"
|
||||
class="ih:my-1 ih:flex ih:items-center ih:gap-2.5 ih:rounded-lg ih:p-2 ih:no-underline"
|
||||
:class="m.mine ? 'ih:bg-white/15 ih:hover:bg-white/25' : 'ih:bg-muted ih:hover:bg-accent'"
|
||||
>
|
||||
<FileIcon :extension="file.name.split('.').pop()" class="ih:shrink-0" />
|
||||
<span class="ih:min-w-0 ih:flex-1">
|
||||
<span class="ih:block ih:truncate ih:text-sm ih:font-medium">{{ file.name }}</span>
|
||||
<span class="ih:block ih:text-xs ih:opacity-75">{{ fileSize(file.size) }}</span>
|
||||
</span>
|
||||
<Download class="ih:size-4 ih:shrink-0 ih:opacity-75" />
|
||||
</a>
|
||||
|
||||
<p v-if="m.body" class="ih:break-words ih:whitespace-pre-wrap" :class="[bigEmoji ? 'ih:text-4xl ih:leading-tight' : '', images.length ? 'ih:px-3 ih:py-2' : '']">
|
||||
<template v-for="(part, i) in linkify(m.body)" :key="i">
|
||||
<a v-if="part.href" :href="part.href" target="_blank" rel="noopener noreferrer" class="ih:underline ih:underline-offset-2">{{ part.text }}</a>
|
||||
<template v-else>{{ part.text }}</template>
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Aktionen beim Überfahren bzw. Fokus -->
|
||||
<div v-if="!m.deleted" class="ih:flex ih:shrink-0 ih:items-center ih:opacity-0 ih:transition-opacity ih:group-hover:opacity-100 ih:focus-within:opacity-100 ih:[@media(hover:none)]:opacity-100">
|
||||
<div class="ih:group/react ih:relative">
|
||||
<button type="button" class="ih:grid ih:size-7 ih:place-items-center ih:rounded-full ih:text-muted-foreground ih:hover:bg-muted" aria-label="Reagieren"><SmilePlus class="ih:size-4" /></button>
|
||||
<div class="ih:absolute ih:bottom-full ih:z-20 ih:hidden ih:gap-0.5 ih:rounded-full ih:border ih:bg-popover ih:p-1 ih:shadow-md ih:group-focus-within/react:flex ih:group-hover/react:flex" :class="m.mine ? 'ih:right-0' : 'ih:left-0'">
|
||||
<button v-for="emoji in reactions" :key="emoji" type="button" class="ih:grid ih:size-8 ih:place-items-center ih:rounded-full ih:text-lg ih:hover:bg-accent" :aria-label="`Mit ${emoji} reagieren`" @click="emit('react', emoji)">{{ emoji }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="ih:grid ih:size-7 ih:place-items-center ih:rounded-full ih:text-muted-foreground ih:hover:bg-muted" aria-label="Antworten" @click="emit('reply')"><CornerUpLeft class="ih:size-4" /></button>
|
||||
<template v-if="m.mine">
|
||||
<button v-if="m.body && m.kind === 'text'" type="button" class="ih:grid ih:size-7 ih:place-items-center ih:rounded-full ih:text-muted-foreground ih:hover:bg-muted" aria-label="Bearbeiten" @click="emit('edit')"><Pencil class="ih:size-4" /></button>
|
||||
<button type="button" class="ih:grid ih:size-7 ih:place-items-center ih:rounded-full ih:text-muted-foreground ih:hover:bg-muted ih:hover:text-destructive" aria-label="Löschen" @click="emit('delete')"><Trash2 class="ih:size-4" /></button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="m.reactions.length" class="ih:relative ih:z-10 ih:-mt-1.5 ih:flex ih:flex-wrap ih:gap-1 ih:px-2">
|
||||
<button
|
||||
v-for="r in m.reactions"
|
||||
:key="r.emoji"
|
||||
type="button"
|
||||
class="ih:flex ih:items-center ih:gap-1 ih:rounded-full ih:border ih:px-1.5 ih:text-xs ih:shadow-xs ih:tabular-nums"
|
||||
:class="r.mine ? 'ih:border-brand ih:bg-brand-soft' : 'ih:bg-card'"
|
||||
:aria-pressed="r.mine"
|
||||
:aria-label="`${r.emoji} ${r.count}`"
|
||||
@click="emit('react', r.emoji)"
|
||||
><span class="ih:text-sm">{{ r.emoji }}</span>{{ r.count > 1 ? r.count : '' }}</button>
|
||||
</div>
|
||||
|
||||
<span class="ih:mt-0.5 ih:px-1 ih:text-[11px] ih:text-muted-foreground ih:tabular-nums">
|
||||
{{ messageTime(m.created_at) }}<template v-if="m.edited"> · bearbeitet</template><template v-if="m.mine && read"> · gelesen</template>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
84
resources/js/components/NewChatDialog.vue
Normal file
84
resources/js/components/NewChatDialog.vue
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { LoaderCircle } from '@lucide/vue';
|
||||
import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Input, Label, toast } from '@inhaus/ui';
|
||||
import PeopleSelect from './PeopleSelect.vue';
|
||||
import { api } from '../lib/api';
|
||||
|
||||
/** Neue Direktnachricht bzw. neue Gruppe */
|
||||
const props = defineProps({
|
||||
group: { type: Boolean, default: false },
|
||||
me: { type: Object, required: true },
|
||||
});
|
||||
const open = defineModel('open', { type: Boolean, default: false });
|
||||
const emit = defineEmits(['created']);
|
||||
|
||||
const name = ref('');
|
||||
const people = ref([]);
|
||||
const busy = ref(false);
|
||||
|
||||
watch(open, (value) => {
|
||||
if (value) {
|
||||
name.value = '';
|
||||
people.value = [];
|
||||
}
|
||||
});
|
||||
|
||||
async function start(person) {
|
||||
if (props.group) return;
|
||||
|
||||
busy.value = true;
|
||||
|
||||
try {
|
||||
const data = await api.direct(person.id);
|
||||
open.value = false;
|
||||
emit('created', data);
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function createGroup() {
|
||||
busy.value = true;
|
||||
|
||||
try {
|
||||
const data = await api.createGroup(name.value.trim(), people.value.map((p) => p.id));
|
||||
open.value = false;
|
||||
emit('created', data);
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<DialogContent class="ih:sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ group ? 'Neue Gruppe' : 'Neue Nachricht' }}</DialogTitle>
|
||||
<DialogDescription>{{ group ? 'Name und Mitglieder wählen – Sie verwalten die Gruppe.' : 'An wen möchten Sie schreiben?' }}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div class="ih:grid ih:gap-4">
|
||||
<div v-if="group" class="ih:grid ih:gap-1.5">
|
||||
<Label for="chat-group-name">Name der Gruppe</Label>
|
||||
<Input id="chat-group-name" v-model="name" maxlength="100" placeholder="z. B. Station 3 – Frühdienst" />
|
||||
</div>
|
||||
<div class="ih:grid ih:gap-1.5">
|
||||
<Label v-if="group">Mitglieder</Label>
|
||||
<PeopleSelect v-model="people" :multiple="group" :exclude="[me.id]" autofocus @pick="start" />
|
||||
</div>
|
||||
<p v-if="busy && !group" class="ih:flex ih:items-center ih:gap-2 ih:text-sm ih:text-muted-foreground"><LoaderCircle class="ih:size-4 ih:animate-spin" /> Gespräch wird geöffnet …</p>
|
||||
</div>
|
||||
<DialogFooter v-if="group">
|
||||
<Button variant="ghost" @click="open = false">Abbrechen</Button>
|
||||
<Button :disabled="busy || !name.trim() || !people.length" @click="createGroup">
|
||||
<LoaderCircle v-if="busy" class="ih:animate-spin" /> Gruppe erstellen
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
98
resources/js/components/PeopleSelect.vue
Normal file
98
resources/js/components/PeopleSelect.vue
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { Search, X } from '@lucide/vue';
|
||||
import { PersonAvatar } from '@inhaus/ui';
|
||||
import { api } from '../lib/api';
|
||||
|
||||
/**
|
||||
* Personen suchen und auswählen – einzeln (Direktnachricht) oder mehrere (Gruppe).
|
||||
* v-model: Liste der Personen [{ id, name, … }]
|
||||
*/
|
||||
const props = defineProps({
|
||||
multiple: { type: Boolean, default: false },
|
||||
exclude: { type: Array, default: () => [] },
|
||||
placeholder: { type: String, default: 'Name oder E-Mail eingeben …' },
|
||||
autofocus: { type: Boolean, default: false },
|
||||
});
|
||||
const emit = defineEmits(['pick']);
|
||||
const selected = defineModel({ type: Array, default: () => [] });
|
||||
|
||||
const query = ref('');
|
||||
const results = ref([]);
|
||||
const active = ref(0);
|
||||
const loading = ref(false);
|
||||
let timer;
|
||||
|
||||
watch(query, (value) => {
|
||||
clearTimeout(timer);
|
||||
|
||||
if (value.trim().length < 2) {
|
||||
results.value = [];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
timer = setTimeout(async () => {
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
const ids = [...props.exclude, ...selected.value.map((p) => p.id)];
|
||||
results.value = (await api.people(value.trim())).people.filter((p) => !ids.includes(p.id));
|
||||
active.value = 0;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}, 200);
|
||||
});
|
||||
|
||||
function choose(person) {
|
||||
if (!person) return;
|
||||
|
||||
emit('pick', person);
|
||||
|
||||
if (props.multiple) selected.value = [...selected.value, person];
|
||||
query.value = '';
|
||||
results.value = [];
|
||||
}
|
||||
|
||||
const remove = (person) => (selected.value = selected.value.filter((p) => p.id !== person.id));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="ih:grid ih:gap-2">
|
||||
<div v-if="multiple && selected.length" class="ih:flex ih:flex-wrap ih:gap-1.5">
|
||||
<span v-for="person in selected" :key="person.id" class="ih:inline-flex ih:items-center ih:gap-1.5 ih:rounded-full ih:border ih:bg-card ih:py-0.5 ih:pr-1 ih:pl-0.5 ih:text-[13px]">
|
||||
<PersonAvatar :person="person" class="ih:size-6 ih:text-[10px]" />
|
||||
{{ person.name }}
|
||||
<button type="button" class="ih:rounded-full ih:p-0.5 ih:text-muted-foreground ih:hover:bg-muted ih:hover:text-foreground" :aria-label="`${person.name} entfernen`" @click="remove(person)"><X class="ih:size-3.5" /></button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="ih:relative">
|
||||
<Search class="ih:pointer-events-none ih:absolute ih:top-1/2 ih:left-2.5 ih:size-4 ih:-translate-y-1/2 ih:text-muted-foreground" />
|
||||
<input
|
||||
v-model="query"
|
||||
type="search"
|
||||
autocomplete="off"
|
||||
:autofocus="autofocus"
|
||||
:placeholder="placeholder"
|
||||
aria-label="Person suchen"
|
||||
class="ih:h-10 ih:w-full ih:rounded-md ih:border ih:border-input ih:bg-card ih:pr-3 ih:pl-8 ih:text-sm ih:shadow-xs ih:focus-visible:ring-3 ih:focus-visible:ring-ring/30 ih:focus-visible:outline-none"
|
||||
@keydown.down.prevent="active = Math.min(results.length - 1, active + 1)"
|
||||
@keydown.up.prevent="active = Math.max(0, active - 1)"
|
||||
@keydown.enter.prevent="choose(results[active])"
|
||||
/>
|
||||
</div>
|
||||
<ul v-if="results.length" class="ih:max-h-64 ih:overflow-y-auto ih:rounded-md ih:border ih:bg-popover ih:p-1" role="listbox">
|
||||
<li v-for="(person, i) in results" :key="person.id" role="option" :aria-selected="i === active">
|
||||
<button type="button" class="ih:flex ih:w-full ih:items-center ih:gap-2.5 ih:rounded ih:px-2 ih:py-1.5 ih:text-left ih:text-sm" :class="i === active ? 'ih:bg-accent' : 'ih:hover:bg-accent/60'" @click="choose(person)" @mouseenter="active = i">
|
||||
<PersonAvatar :person="person" class="ih:size-7 ih:text-[11px]" />
|
||||
<span class="ih:min-w-0 ih:flex-1">
|
||||
<span class="ih:block ih:truncate ih:font-medium">{{ person.name }}</span>
|
||||
<span v-if="person.job_title || person.department" class="ih:block ih:truncate ih:text-xs ih:text-muted-foreground">{{ [person.job_title, person.department].filter(Boolean).join(' · ') }}</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else-if="query.trim().length >= 2 && !loading" class="ih:px-1 ih:text-[13px] ih:text-muted-foreground">Niemand gefunden.</p>
|
||||
</div>
|
||||
</template>
|
||||
25
resources/js/components/Popup.vue
Normal file
25
resources/js/components/Popup.vue
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<script setup>
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
|
||||
/** Kleines Aufklapp-Fenster über der Eingabezeile; schließt bei Klick daneben und mit Esc */
|
||||
const emit = defineEmits(['close']);
|
||||
const root = ref(null);
|
||||
|
||||
const outside = (event) => root.value && !root.value.contains(event.target) && !event.target.closest?.('[data-popup-toggle]') && emit('close');
|
||||
const escape = (event) => event.key === 'Escape' && emit('close');
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('pointerdown', outside);
|
||||
document.addEventListener('keydown', escape);
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('pointerdown', outside);
|
||||
document.removeEventListener('keydown', escape);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="root" class="ih:absolute ih:bottom-full ih:left-0 ih:z-30 ih:mb-2 ih:w-[min(22rem,calc(100vw-2rem))] ih:overflow-hidden ih:rounded-lg ih:border ih:bg-popover ih:text-popover-foreground ih:shadow-lg" role="dialog">
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
308
resources/js/components/Thread.vue
Normal file
308
resources/js/components/Thread.vue
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
<script setup>
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue';
|
||||
import { ArrowDown, ArrowLeft, BellOff, Info, LoaderCircle, Upload } from '@lucide/vue';
|
||||
import { toast } from '@inhaus/ui';
|
||||
import ChatAvatar from './ChatAvatar.vue';
|
||||
import Composer from './Composer.vue';
|
||||
import MessageBubble from './MessageBubble.vue';
|
||||
import { api } from '../lib/api';
|
||||
import { dayLabel, sameDay } from '../lib/format';
|
||||
|
||||
const props = defineProps({
|
||||
conversation: { type: Object, required: true },
|
||||
me: { type: Object, required: true },
|
||||
reactions: { type: Array, required: true },
|
||||
maxUploadMb: { type: Number, default: 25 },
|
||||
typing: { type: Array, default: () => [] },
|
||||
});
|
||||
const emit = defineEmits(['back', 'info', 'changed', 'read']);
|
||||
|
||||
const messages = ref([]);
|
||||
const more = ref(false);
|
||||
const loading = ref(true);
|
||||
const loadingOlder = ref(false);
|
||||
const sending = ref(false);
|
||||
const replyTo = ref(null);
|
||||
const editing = ref(null);
|
||||
const scroller = ref(null);
|
||||
const composer = ref(null);
|
||||
const atBottom = ref(true);
|
||||
const newBelow = ref(0);
|
||||
const dragging = ref(false);
|
||||
// Erste ungelesene Nachricht beim Öffnen – dort steht der Trenner „Neu“
|
||||
const firstUnreadId = ref(null);
|
||||
|
||||
const isGroup = computed(() => props.conversation.type === 'group');
|
||||
const lastId = () => messages.value.at(-1)?.id ?? 0;
|
||||
const lastOwnId = computed(() => [...messages.value].reverse().find((m) => m.mine && !m.deleted && m.kind !== 'system')?.id);
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
messages.value = [];
|
||||
replyTo.value = editing.value = null;
|
||||
|
||||
try {
|
||||
const data = await api.messages(props.conversation.id);
|
||||
messages.value = data.messages;
|
||||
more.value = data.more;
|
||||
const readId = props.conversation.last_read_id ?? 0;
|
||||
firstUnreadId.value = props.conversation.unread ? data.messages.find((m) => m.id > readId && !m.mine && m.kind !== 'system')?.id ?? null : null;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
await nextTick();
|
||||
scrollTo(firstUnreadId.value ? document.getElementById(`nachricht-${firstUnreadId.value}`) : null);
|
||||
markRead();
|
||||
composer.value?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadOlder() {
|
||||
if (!more.value || loadingOlder.value || !messages.value.length) return;
|
||||
|
||||
loadingOlder.value = true;
|
||||
const el = scroller.value;
|
||||
const before = el.scrollHeight;
|
||||
|
||||
try {
|
||||
const data = await api.messages(props.conversation.id, messages.value[0].id);
|
||||
messages.value = [...data.messages, ...messages.value];
|
||||
more.value = data.more;
|
||||
await nextTick();
|
||||
el.scrollTop = el.scrollHeight - before; // Position halten
|
||||
} finally {
|
||||
loadingOlder.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function scrollTo(element) {
|
||||
const el = scroller.value;
|
||||
|
||||
if (!el) return;
|
||||
|
||||
element ? element.scrollIntoView({ block: 'center' }) : (el.scrollTop = el.scrollHeight);
|
||||
newBelow.value = 0;
|
||||
}
|
||||
|
||||
function onScroll() {
|
||||
const el = scroller.value;
|
||||
atBottom.value = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
|
||||
|
||||
if (atBottom.value) {
|
||||
newBelow.value = 0;
|
||||
markRead();
|
||||
}
|
||||
|
||||
if (el.scrollTop < 120) loadOlder();
|
||||
}
|
||||
|
||||
let readTimer;
|
||||
function markRead() {
|
||||
clearTimeout(readTimer);
|
||||
readTimer = setTimeout(async () => {
|
||||
const last = [...messages.value].reverse().find((m) => !m.mine);
|
||||
|
||||
if (!last || document.visibilityState !== 'visible' || !atBottom.value || !props.conversation.unread) return;
|
||||
|
||||
const data = await api.read(props.conversation.id, lastId());
|
||||
emit('read', { id: props.conversation.id, unread: data.unread });
|
||||
}, 400);
|
||||
}
|
||||
|
||||
/** Neue bzw. geänderte Nachrichten aus der Abfrage einarbeiten */
|
||||
async function merge(incoming) {
|
||||
const mine = incoming.filter((m) => m.conversation_id === props.conversation.id);
|
||||
|
||||
if (!mine.length) return;
|
||||
|
||||
const byId = new Map(messages.value.map((m) => [m.id, m]));
|
||||
let added = 0;
|
||||
|
||||
for (const message of mine) {
|
||||
if (byId.has(message.id)) Object.assign(byId.get(message.id), message);
|
||||
else if (message.id > lastId()) {
|
||||
messages.value.push(message);
|
||||
added += message.mine ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (!added) return;
|
||||
|
||||
const stick = atBottom.value;
|
||||
await nextTick();
|
||||
|
||||
if (stick) {
|
||||
scrollTo();
|
||||
markRead();
|
||||
} else {
|
||||
newBelow.value += added;
|
||||
}
|
||||
}
|
||||
|
||||
async function send(payload) {
|
||||
sending.value = true;
|
||||
|
||||
try {
|
||||
const { message } = await api.send(props.conversation.id, { ...payload, replyTo: replyTo.value?.id });
|
||||
replyTo.value = null;
|
||||
|
||||
if (!messages.value.some((m) => m.id === message.id)) messages.value.push(message);
|
||||
await nextTick();
|
||||
scrollTo();
|
||||
emit('changed');
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
sending.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveEdit(body) {
|
||||
const message = editing.value;
|
||||
|
||||
try {
|
||||
await api.edit(message.id, body);
|
||||
Object.assign(message, { body, edited: true });
|
||||
editing.value = null;
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(message) {
|
||||
if (!window.confirm('Nachricht für alle löschen?')) return;
|
||||
|
||||
await api.remove(message.id);
|
||||
Object.assign(message, { deleted: true, body: null, gif_url: null, attachments: [], reactions: [] });
|
||||
emit('changed');
|
||||
}
|
||||
|
||||
async function react(message, emoji) {
|
||||
// Sofort anzeigen, der Server bestätigt mit der nächsten Abfrage
|
||||
const existing = message.reactions.find((r) => r.emoji === emoji);
|
||||
|
||||
if (existing?.mine) {
|
||||
existing.count--;
|
||||
existing.mine = false;
|
||||
message.reactions = message.reactions.filter((r) => r.count > 0);
|
||||
} else if (existing) {
|
||||
existing.count++;
|
||||
existing.mine = true;
|
||||
} else {
|
||||
message.reactions.push({ emoji, count: 1, mine: true });
|
||||
}
|
||||
|
||||
await api.react(message.id, emoji).catch((error) => toast.error(error.message));
|
||||
}
|
||||
|
||||
function jump(id) {
|
||||
const element = document.getElementById(`nachricht-${id}`);
|
||||
|
||||
if (element) {
|
||||
element.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
||||
element.classList.add('ih:animate-pulse');
|
||||
setTimeout(() => element.classList.remove('ih:animate-pulse'), 1500);
|
||||
}
|
||||
}
|
||||
|
||||
function onDrop(event) {
|
||||
dragging.value = false;
|
||||
const files = [...(event.dataTransfer?.files ?? [])];
|
||||
files.length && composer.value?.addFiles(files);
|
||||
}
|
||||
|
||||
const showAuthor = (m, i) => {
|
||||
const prev = messages.value[i - 1];
|
||||
|
||||
return !prev || prev.kind === 'system' || prev.user?.id !== m.user?.id || !sameDay(prev.created_at, m.created_at) || new Date(m.created_at) - new Date(prev.created_at) > 5 * 60000;
|
||||
};
|
||||
const showAvatar = (m, i) => {
|
||||
const next = messages.value[i + 1];
|
||||
|
||||
return !next || next.kind === 'system' || next.user?.id !== m.user?.id || !sameDay(next.created_at, m.created_at);
|
||||
};
|
||||
|
||||
const subtitle = computed(() => {
|
||||
if (props.typing.length) return `${props.typing.join(', ')} ${props.typing.length === 1 ? 'schreibt' : 'schreiben'} …`;
|
||||
if (isGroup.value) return props.conversation.members.map((m) => m.first_name || m.name).join(', ');
|
||||
|
||||
return props.conversation.person?.job_title ?? '';
|
||||
});
|
||||
|
||||
watch(() => props.conversation.id, load);
|
||||
onMounted(load);
|
||||
|
||||
defineExpose({ merge, lastId });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="ih:relative ih:flex ih:h-full ih:min-h-0 ih:flex-col"
|
||||
:aria-label="`Gespräch mit ${conversation.name}`"
|
||||
@dragover.prevent="dragging = true"
|
||||
@dragleave.self="dragging = false"
|
||||
@drop.prevent="onDrop"
|
||||
>
|
||||
<header class="ih:flex ih:items-center ih:gap-3 ih:border-b ih:px-3 ih:py-2.5">
|
||||
<button type="button" class="ih:grid ih:size-9 ih:place-items-center ih:rounded-md ih:text-muted-foreground ih:hover:bg-accent ih:lg:hidden" aria-label="Zurück zur Übersicht" @click="emit('back')"><ArrowLeft class="ih:size-5" /></button>
|
||||
<ChatAvatar :conversation="conversation" />
|
||||
<div class="ih:min-w-0 ih:flex-1">
|
||||
<h2 class="ih:flex ih:items-center ih:gap-1.5 ih:truncate ih:font-semibold">
|
||||
<a v-if="conversation.person" :href="`/personen/${conversation.person.id}`" class="ih:truncate ih:hover:underline">{{ conversation.name }}</a>
|
||||
<span v-else class="ih:truncate">{{ conversation.name }}</span>
|
||||
<BellOff v-if="conversation.muted" class="ih:size-3.5 ih:shrink-0 ih:text-muted-foreground" aria-label="Stummgeschaltet" />
|
||||
</h2>
|
||||
<p class="ih:truncate ih:text-xs" :class="typing.length ? 'ih:text-brand-text' : 'ih:text-muted-foreground'" aria-live="polite">{{ subtitle }}</p>
|
||||
</div>
|
||||
<button type="button" class="ih:grid ih:size-9 ih:place-items-center ih:rounded-md ih:text-muted-foreground ih:hover:bg-accent" :aria-label="isGroup ? 'Gruppe: Mitglieder und Einstellungen' : 'Einstellungen zum Gespräch'" @click="emit('info')"><Info class="ih:size-5" /></button>
|
||||
</header>
|
||||
|
||||
<div ref="scroller" class="ih:min-h-0 ih:flex-1 ih:overflow-y-auto ih:bg-muted/30 ih:px-3 ih:py-4 ih:sm:px-5" role="log" aria-live="polite" aria-relevant="additions" @scroll.passive="onScroll">
|
||||
<div v-if="loading" class="ih:grid ih:h-full ih:place-items-center"><LoaderCircle class="ih:size-6 ih:animate-spin ih:text-muted-foreground" /></div>
|
||||
<template v-else>
|
||||
<div v-if="loadingOlder" class="ih:flex ih:justify-center ih:py-2"><LoaderCircle class="ih:size-4 ih:animate-spin ih:text-muted-foreground" /></div>
|
||||
<p v-if="!messages.length" class="ih:py-10 ih:text-center ih:text-sm ih:text-muted-foreground">Schreiben Sie die erste Nachricht.</p>
|
||||
<template v-for="(m, i) in messages" :key="m.id">
|
||||
<div v-if="i === 0 || !sameDay(messages[i - 1].created_at, m.created_at)" class="ih:my-4 ih:flex ih:justify-center">
|
||||
<span class="ih:rounded-full ih:bg-card ih:px-3 ih:py-1 ih:text-xs ih:font-medium ih:text-muted-foreground ih:shadow-xs">{{ dayLabel(m.created_at) }}</span>
|
||||
</div>
|
||||
<div v-if="m.id === firstUnreadId" class="ih:my-3 ih:flex ih:items-center ih:gap-3 ih:text-xs ih:font-semibold ih:text-brand-text">
|
||||
<span class="ih:h-px ih:flex-1 ih:bg-brand/40" />Neu<span class="ih:h-px ih:flex-1 ih:bg-brand/40" />
|
||||
</div>
|
||||
<MessageBubble
|
||||
:message="m"
|
||||
:group="isGroup"
|
||||
:show-author="showAuthor(m, i)"
|
||||
:show-avatar="showAvatar(m, i)"
|
||||
:reactions="reactions"
|
||||
:read="m.id === lastOwnId && !!conversation.others_read_id && conversation.others_read_id >= m.id"
|
||||
@react="react(m, $event)"
|
||||
@reply="replyTo = m; editing = null"
|
||||
@edit="editing = m; replyTo = null"
|
||||
@delete="remove(m)"
|
||||
@jump="jump"
|
||||
/>
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<button v-if="newBelow" type="button" class="ih:absolute ih:bottom-28 ih:left-1/2 ih:z-10 ih:flex ih:-translate-x-1/2 ih:items-center ih:gap-1.5 ih:rounded-full ih:bg-brand ih:px-3 ih:py-1.5 ih:text-xs ih:font-medium ih:text-brand-foreground ih:shadow-lg" @click="scrollTo(); markRead()">
|
||||
<ArrowDown class="ih:size-3.5" /> {{ newBelow }} {{ newBelow === 1 ? 'neue Nachricht' : 'neue Nachrichten' }}
|
||||
</button>
|
||||
|
||||
<Composer
|
||||
ref="composer"
|
||||
:reply-to="replyTo"
|
||||
:editing="editing"
|
||||
:sending="sending"
|
||||
:max-upload-mb="maxUploadMb"
|
||||
@send="send"
|
||||
@save-edit="saveEdit"
|
||||
@cancel="replyTo = null; editing = null"
|
||||
@typing="api.typing(conversation.id).catch(() => {})"
|
||||
/>
|
||||
|
||||
<div v-if="dragging" class="ih:pointer-events-none ih:absolute ih:inset-2 ih:z-20 ih:grid ih:place-items-center ih:rounded-xl ih:border-2 ih:border-dashed ih:border-brand ih:bg-brand-soft/80 ih:text-brand-text">
|
||||
<span class="ih:flex ih:items-center ih:gap-2 ih:font-medium"><Upload class="ih:size-5" /> Dateien hier ablegen</span>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
37
resources/js/header/Unread.vue
Normal file
37
resources/js/header/Unread.vue
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<script setup>
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { MessageCircle } from '@lucide/vue';
|
||||
import { http } from '@inhaus/ui';
|
||||
|
||||
/**
|
||||
* Sprechblase neben der Glocke: Zahl der ungelesenen Nachrichten. Auf der Chat-Seite meldet
|
||||
* der Chat selbst, sonst wird alle 30 Sekunden nachgefragt.
|
||||
*/
|
||||
const props = defineProps({ unread: { type: Number, default: 0 } });
|
||||
const count = ref(props.unread);
|
||||
let timer;
|
||||
|
||||
const update = (event) => (count.value = event.detail);
|
||||
|
||||
async function poll() {
|
||||
if (document.visibilityState === 'visible' && !location.pathname.startsWith('/chat')) {
|
||||
count.value = (await http.get('/chat/api/ungelesen').catch(() => ({ unread: count.value }))).unread;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('inhaus-chat:unread', update);
|
||||
timer = setInterval(poll, 30000);
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('inhaus-chat:unread', update);
|
||||
clearInterval(timer);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a href="/chat" class="ih:relative ih:grid ih:size-9 ih:place-items-center ih:rounded-md ih:text-muted-foreground ih:transition-colors ih:hover:bg-accent ih:hover:text-foreground" :aria-label="count ? `Nachrichten, ${count} ungelesen` : 'Nachrichten'" :title="count ? `${count} ungelesene Nachrichten` : 'Nachrichten'">
|
||||
<MessageCircle class="ih:size-5" />
|
||||
<span v-if="count" class="ih:absolute ih:top-0.5 ih:right-0.5 ih:grid ih:h-4 ih:min-w-4 ih:place-items-center ih:rounded-full ih:bg-brand ih:px-1 ih:text-[10px] ih:font-semibold ih:text-brand-foreground ih:tabular-nums" aria-hidden="true">{{ count > 99 ? '99+' : count }}</span>
|
||||
</a>
|
||||
</template>
|
||||
40
resources/js/lib/api.js
Normal file
40
resources/js/lib/api.js
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { http } from '@inhaus/ui';
|
||||
|
||||
/** JSON-Schnittstelle der Chat-Oberfläche (routes/web.php, Präfix /chat/api) */
|
||||
const base = '/chat/api';
|
||||
|
||||
export const api = {
|
||||
conversations: () => http.get(`${base}/gespraeche`),
|
||||
direct: (userId) => http.post(`${base}/direkt`, { user_id: userId }),
|
||||
createGroup: (name, members) => http.post(`${base}/gruppen`, { name, members }),
|
||||
updateConversation: (id, data) => http.put(`${base}/gespraeche/${id}`, data),
|
||||
leave: (id) => http.delete(`${base}/gespraeche/${id}`),
|
||||
addMembers: (id, members) => http.post(`${base}/gespraeche/${id}/mitglieder`, { members }),
|
||||
removeMember: (id, userId) => http.delete(`${base}/gespraeche/${id}/mitglieder/${userId}`),
|
||||
setAdmin: (id, userId, admin) => http.put(`${base}/gespraeche/${id}/mitglieder/${userId}`, { admin }),
|
||||
|
||||
messages: (id, before) => http.get(`${base}/gespraeche/${id}/nachrichten${before ? `?vor=${before}` : ''}`),
|
||||
send(id, { body, gifUrl, replyTo, files }) {
|
||||
const data = new FormData();
|
||||
if (body) data.append('body', body);
|
||||
if (gifUrl) data.append('gif_url', gifUrl);
|
||||
if (replyTo) data.append('reply_to', replyTo);
|
||||
(files ?? []).forEach((file) => data.append('files[]', file));
|
||||
|
||||
return http.post(`${base}/gespraeche/${id}/nachrichten`, data);
|
||||
},
|
||||
edit: (messageId, body) => http.put(`${base}/nachrichten/${messageId}`, { body }),
|
||||
remove: (messageId) => http.delete(`${base}/nachrichten/${messageId}`),
|
||||
react: (messageId, emoji) => http.post(`${base}/nachrichten/${messageId}/reaktion`, { emoji }),
|
||||
read: (id, messageId) => http.post(`${base}/gespraeche/${id}/gelesen`, { message_id: messageId }),
|
||||
typing: (id) => http.post(`${base}/gespraeche/${id}/tippt`),
|
||||
updates: (params) => http.get(`${base}/neues?${new URLSearchParams(Object.entries(params).filter(([, v]) => v !== null && v !== undefined))}`),
|
||||
unread: () => http.get(`${base}/ungelesen`),
|
||||
gifs: (q) => http.get(`${base}/gifs?q=${encodeURIComponent(q ?? '')}`),
|
||||
people: (q) => http.get(`/personen/suche?q=${encodeURIComponent(q)}`),
|
||||
};
|
||||
|
||||
/** Ungelesene an das Symbol in der Kopfzeile melden */
|
||||
export function announceUnread(count) {
|
||||
window.dispatchEvent(new CustomEvent('inhaus-chat:unread', { detail: count }));
|
||||
}
|
||||
11
resources/js/lib/emojis.js
Normal file
11
resources/js/lib/emojis.js
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
/** Emoji-Auswahl (Unicode) – kompakt, ohne externe Bibliothek */
|
||||
export const EMOJI_GROUPS = [
|
||||
{ label: 'Smileys', icon: '😀', emojis: '😀 😃 😄 😁 😆 😅 🤣 😂 🙂 🙃 😉 😊 😇 🥰 😍 🤩 😘 😗 😚 😋 😛 😜 🤪 😝 🤗 🤭 🤫 🤔 🤐 🤨 😐 😑 😶 😏 😒 🙄 😬 😌 😔 😪 😴 😷 🤒 🤕 🤢 🤧 🥵 🥶 🥴 😵 🤯 🤠 🥳 😎 🤓 🧐 😕 😟 🙁 😮 😯 😲 😳 🥺 😦 😧 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 🥱 😤 😡 😠 🤬'.split(' ') },
|
||||
{ label: 'Gesten', icon: '👍', emojis: '👍 👎 👌 🤌 ✌️ 🤞 🤟 🤘 🤙 👈 👉 👆 👇 ☝️ ✋ 🤚 🖐️ 🖖 👋 👏 🙌 👐 🤲 🤝 🙏 ✍️ 💪 🦾 👀 🧠 🫶 ❤️ 🧡 💛 💚 💙 💜 🖤 🤍 🤎 💔 ❣️ 💕 💞 💓 💗 💖 💘 💯 ✨ ⭐ 🌟 💥 🔥 🎉 🎊'.split(' ') },
|
||||
{ label: 'Menschen', icon: '🧑', emojis: '👶 🧒 👦 👧 🧑 👱 👨 🧔 👩 🧓 👴 👵 🙋 🙆 🙅 🤷 🤦 🙇 💁 🧑⚕️ 🧑🍳 🧑🔧 🧑🏫 🧑💻 🧑💼 🧑🔬 🧑🎨 🧑🚒 👮 🕵️ 💂 👷 🤴 👸 🧙 🧚 🦸 🏃 🚶 🧘 🏋️ 🚴 🤸 👯 💃 🕺 👪 🧑🤝🧑'.split(' ') },
|
||||
{ label: 'Natur', icon: '🌿', emojis: '🐶 🐱 🐭 🐹 🐰 🦊 🐻 🐼 🐨 🐯 🦁 🐮 🐷 🐸 🐵 🐔 🐧 🐦 🦆 🦉 🐴 🦄 🐝 🐞 🦋 🐢 🐍 🐙 🐠 🐬 🐳 🌵 🎄 🌲 🌳 🌴 🌱 🌿 🍀 🍁 🍂 🌷 🌹 🌻 🌼 🌸 🌞 🌝 🌙 ⭐ ☀️ 🌤️ ⛅ 🌧️ ⛈️ ❄️ ☃️ 🌈 🌊'.split(' ') },
|
||||
{ label: 'Essen', icon: '🍕', emojis: '🍏 🍎 🍐 🍊 🍋 🍌 🍉 🍇 🍓 🫐 🍒 🍑 🥭 🍍 🥥 🥝 🍅 🥑 🥦 🥕 🌽 🥔 🥐 🥖 🥨 🧀 🥚 🍳 🥞 🥓 🍔 🍟 🍕 🌭 🥪 🌮 🥗 🍝 🍜 🍲 🍣 🍰 🎂 🧁 🍩 🍪 🍫 🍬 🍭 🍦 ☕ 🍵 🧃 🥤 🍺 🍻 🥂 🍷'.split(' ') },
|
||||
{ label: 'Aktivitäten', icon: '⚽', emojis: '⚽ 🏀 🏈 ⚾ 🎾 🏐 🏓 🏸 🥅 ⛳ 🎣 🎽 🎿 ⛸️ 🥇 🥈 🥉 🏆 🏅 🎗️ 🎫 🎟️ 🎭 🎨 🎬 🎤 🎧 🎼 🎹 🥁 🎷 🎺 🎸 🎻 🎲 🧩 🎯 🎳 🎮 🎰'.split(' ') },
|
||||
{ label: 'Dinge', icon: '💡', emojis: '⌚ 📱 💻 ⌨️ 🖥️ 🖨️ 🖱️ 💾 📷 📞 ☎️ 📺 ⏰ ⏳ 💡 🔦 🕯️ 💰 💳 🧾 ✉️ 📧 📨 📦 📝 📁 📂 📅 📆 📌 📎 ✂️ 🔒 🔑 🔨 🛠️ 🧰 🩺 💊 💉 🩹 🧯 🛒 🎁 🎈 🏠 🏥 🏫 🚗 🚌 🚲 ✈️ 🚀 🕐'.split(' ') },
|
||||
{ label: 'Symbole', icon: '✅', emojis: '✅ ☑️ ✔️ ❌ ❎ ➕ ➖ ❓ ❗ ‼️ ⁉️ 💤 ⚠️ 🚫 ⛔ 🔴 🟠 🟡 🟢 🔵 🟣 ⚫ ⚪ 🔶 🔷 ▶️ ⏸️ ⏹️ 🔄 🔁 🆗 🆕 🆒 🆘 ℹ️ 🔔 🔕 📣 💬 💭 🗯️ ♻️ ⬆️ ⬇️ ⬅️ ➡️'.split(' ') },
|
||||
];
|
||||
62
resources/js/lib/format.js
Normal file
62
resources/js/lib/format.js
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
const time = new Intl.DateTimeFormat('de-DE', { hour: '2-digit', minute: '2-digit' });
|
||||
const weekday = new Intl.DateTimeFormat('de-DE', { weekday: 'short' });
|
||||
const short = new Intl.DateTimeFormat('de-DE', { day: '2-digit', month: '2-digit', year: '2-digit' });
|
||||
const long = new Intl.DateTimeFormat('de-DE', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
|
||||
|
||||
const startOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
|
||||
/** Zeit in der Gesprächsliste: heute Uhrzeit, diese Woche Wochentag, sonst Datum */
|
||||
export function listTime(iso) {
|
||||
if (!iso) return '';
|
||||
|
||||
const date = new Date(iso);
|
||||
const days = (startOfDay(new Date()) - startOfDay(date)) / 86400000;
|
||||
|
||||
if (days === 0) return time.format(date);
|
||||
if (days === 1) return 'Gestern';
|
||||
if (days < 7) return weekday.format(date);
|
||||
|
||||
return short.format(date);
|
||||
}
|
||||
|
||||
export const messageTime = (iso) => time.format(new Date(iso));
|
||||
|
||||
/** Trenner zwischen Tagen im Verlauf */
|
||||
export function dayLabel(iso) {
|
||||
const date = new Date(iso);
|
||||
const days = (startOfDay(new Date()) - startOfDay(date)) / 86400000;
|
||||
|
||||
if (days === 0) return 'Heute';
|
||||
if (days === 1) return 'Gestern';
|
||||
|
||||
return long.format(date);
|
||||
}
|
||||
|
||||
export const sameDay = (a, b) => startOfDay(new Date(a)) === startOfDay(new Date(b));
|
||||
|
||||
export function fileSize(bytes) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
||||
|
||||
return `${(bytes / 1024 / 1024).toFixed(1).replace('.', ',')} MB`;
|
||||
}
|
||||
|
||||
/** Text in Stücke zerlegen, Links erkennen – ohne v-html */
|
||||
export function linkify(text) {
|
||||
const parts = [];
|
||||
const pattern = /(https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)\]])/g;
|
||||
let last = 0;
|
||||
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
if (match.index > last) parts.push({ text: text.slice(last, match.index) });
|
||||
parts.push({ text: match[0], href: match[0] });
|
||||
last = match.index + match[0].length;
|
||||
}
|
||||
|
||||
if (last < text.length) parts.push({ text: text.slice(last) });
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** Nur Emojis (bis zu 3)? Dann groß darstellen */
|
||||
export const onlyEmoji = (text) => !!text && /^(\p{Extended_Pictographic}|\p{Emoji_Component}||️|\s){1,12}$/u.test(text) && [...text.replace(/\s/g, '')].length <= 8;
|
||||
78
resources/js/lib/sync.js
Normal file
78
resources/js/lib/sync.js
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import { api } from './api';
|
||||
|
||||
/**
|
||||
* Hält den Chat aktuell: fragt regelmäßig nach („Gibt es Neues?“) – häufig, solange die Seite
|
||||
* sichtbar ist, selten im Hintergrund. Ist Echtzeit eingerichtet, löst ein Signal des
|
||||
* Pusher-kompatiblen Dienstes die Abfrage sofort aus; das Nachfragen läuft dann nur noch als Rückfall.
|
||||
*/
|
||||
export function createSync({ realtime, userId, openId, lastId, onUpdate }) {
|
||||
let cursor = null;
|
||||
let timer = null;
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
let socket = null;
|
||||
|
||||
const interval = () => {
|
||||
const visible = document.visibilityState === 'visible';
|
||||
|
||||
if (socket?.connection?.state === 'connected') return visible ? 20000 : 60000;
|
||||
|
||||
return visible ? (document.hasFocus() ? 3000 : 6000) : 30000;
|
||||
};
|
||||
|
||||
async function tick() {
|
||||
if (running || stopped) return;
|
||||
|
||||
running = true;
|
||||
clearTimeout(timer);
|
||||
|
||||
try {
|
||||
const data = await api.updates({ seit: cursor, offen: openId(), nach: lastId() });
|
||||
cursor = data.cursor;
|
||||
onUpdate(data);
|
||||
} catch {
|
||||
// Netzwerk kurz weg – nächster Versuch folgt
|
||||
} finally {
|
||||
running = false;
|
||||
|
||||
if (!stopped) timer = setTimeout(tick, interval());
|
||||
}
|
||||
}
|
||||
|
||||
const wake = () => document.visibilityState === 'visible' && tick();
|
||||
document.addEventListener('visibilitychange', wake);
|
||||
window.addEventListener('focus', wake);
|
||||
|
||||
if (realtime) {
|
||||
import('pusher-js').then(({ default: Pusher }) => {
|
||||
if (stopped) return;
|
||||
|
||||
socket = new Pusher(realtime.key, {
|
||||
cluster: realtime.cluster,
|
||||
...(realtime.host ? { wsHost: realtime.host, wsPort: realtime.port, wssPort: realtime.port, forceTLS: realtime.tls, enabledTransports: ['ws', 'wss'] } : {}),
|
||||
channelAuthorization: {
|
||||
endpoint: '/chat/api/echtzeit/anmelden',
|
||||
headers: { 'X-XSRF-TOKEN': decodeURIComponent(document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/)?.[1] ?? ''), Accept: 'application/json' },
|
||||
},
|
||||
});
|
||||
socket.subscribe(`private-chat-user-${userId}`).bind('update', () => tick());
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
tick();
|
||||
|
||||
return {
|
||||
now: tick,
|
||||
reset() {
|
||||
cursor = null;
|
||||
tick();
|
||||
},
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
document.removeEventListener('visibilitychange', wake);
|
||||
window.removeEventListener('focus', wake);
|
||||
socket?.disconnect();
|
||||
},
|
||||
};
|
||||
}
|
||||
127
resources/js/pages/Index.vue
Normal file
127
resources/js/pages/Index.vue
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
<script setup>
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { MessagesSquare } from '@lucide/vue';
|
||||
import { AppLayout } from '@inhaus/ui';
|
||||
import ConversationInfo from '../components/ConversationInfo.vue';
|
||||
import ConversationList from '../components/ConversationList.vue';
|
||||
import NewChatDialog from '../components/NewChatDialog.vue';
|
||||
import Thread from '../components/Thread.vue';
|
||||
import { announceUnread, api } from '../lib/api';
|
||||
import { createSync } from '../lib/sync';
|
||||
|
||||
/**
|
||||
* Nachrichten: links die Gespräche, rechts der Verlauf. Auf dem Handy nacheinander.
|
||||
*/
|
||||
const props = defineProps({
|
||||
me: { type: Object, required: true },
|
||||
conversations: { type: Array, required: true },
|
||||
activeId: { type: Number, default: null },
|
||||
canCreateGroups: { type: Boolean, default: false },
|
||||
realtime: { type: Object, default: null },
|
||||
reactions: { type: Array, required: true },
|
||||
maxUploadMb: { type: Number, default: 25 },
|
||||
});
|
||||
|
||||
const list = ref(props.conversations);
|
||||
const activeId = ref(props.activeId);
|
||||
const typing = ref([]);
|
||||
const thread = ref(null);
|
||||
const dialog = ref(null); // 'chat' | 'group'
|
||||
const infoOpen = ref(false);
|
||||
|
||||
const active = computed(() => list.value.find((c) => c.id === activeId.value) ?? null);
|
||||
|
||||
function open(id, push = true) {
|
||||
activeId.value = id;
|
||||
typing.value = [];
|
||||
|
||||
if (push && location.pathname !== `/chat/${id ?? ''}`.replace(/\/$/, '')) {
|
||||
history.pushState({ chat: id }, '', id ? `/chat/${id}` : '/chat');
|
||||
}
|
||||
|
||||
sync?.now();
|
||||
}
|
||||
|
||||
const onPop = () => open(Number(location.pathname.split('/')[2]) || null, false);
|
||||
|
||||
function setList(conversations) {
|
||||
if (!conversations) return;
|
||||
|
||||
list.value = conversations;
|
||||
announceUnread(conversations.reduce((sum, c) => sum + (c.muted ? 0 : c.unread), 0));
|
||||
}
|
||||
|
||||
let sync = null;
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('popstate', onPop);
|
||||
sync = createSync({
|
||||
realtime: props.realtime,
|
||||
userId: props.me.id,
|
||||
openId: () => activeId.value,
|
||||
lastId: () => thread.value?.lastId() ?? 0,
|
||||
onUpdate(data) {
|
||||
setList(data.conversations);
|
||||
typing.value = data.typing ?? [];
|
||||
thread.value?.merge(data.messages ?? []);
|
||||
announceUnread(data.unread);
|
||||
},
|
||||
});
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('popstate', onPop);
|
||||
sync?.stop();
|
||||
});
|
||||
|
||||
function created(data) {
|
||||
setList(data.conversations);
|
||||
open(data.id);
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
setList((await api.conversations()).conversations);
|
||||
}
|
||||
|
||||
function onRead({ id, unread }) {
|
||||
const c = list.value.find((x) => x.id === id);
|
||||
|
||||
if (c) c.unread = 0;
|
||||
announceUnread(unread);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout title="Nachrichten">
|
||||
<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'" />
|
||||
</aside>
|
||||
|
||||
<main class="ih:min-w-0 ih:flex-1 ih:lg:block" :class="active ? 'ih:block' : 'ih:hidden'">
|
||||
<Thread
|
||||
v-if="active"
|
||||
ref="thread"
|
||||
:conversation="active"
|
||||
:me="me"
|
||||
:reactions="reactions"
|
||||
:typing="typing"
|
||||
:max-upload-mb="maxUploadMb"
|
||||
@back="open(null)"
|
||||
@info="infoOpen = true"
|
||||
@changed="refresh"
|
||||
@read="onRead"
|
||||
/>
|
||||
<div v-else class="ih:grid ih:h-full ih:place-items-center ih:p-8 ih:text-center">
|
||||
<div>
|
||||
<MessagesSquare class="ih:mx-auto ih:size-12 ih:text-muted-foreground/60" :stroke-width="1.5" />
|
||||
<p class="ih:mt-3 ih:font-medium">Wählen Sie ein Gespräch</p>
|
||||
<p class="ih:mt-1 ih:text-sm ih:text-muted-foreground">oder beginnen Sie eine neue Nachricht.</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<NewChatDialog :open="dialog !== null" :group="dialog === 'group'" :me="me" @update:open="(v) => !v && (dialog = null)" @created="created" />
|
||||
<ConversationInfo v-if="active" v-model:open="infoOpen" :conversation="active" :me="me" @updated="setList" @left="open(null)" />
|
||||
</AppLayout>
|
||||
</template>
|
||||
15
routes/api.php
Normal file
15
routes/api.php
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
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']);
|
||||
});
|
||||
36
routes/web.php
Normal file
36
routes/web.php
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inhaus\Plugins\Chat\Http\Controllers\ConversationController;
|
||||
use Inhaus\Plugins\Chat\Http\Controllers\MessageController;
|
||||
|
||||
Route::middleware('auth')->group(function () {
|
||||
Route::get('/chat', [ConversationController::class, 'page'])->name('chat.index');
|
||||
Route::get('/chat/{conversation}', [ConversationController::class, 'page'])->whereNumber('conversation')->name('chat.show');
|
||||
Route::get('/chat/dateien/{attachment}', [MessageController::class, 'attachment'])->name('chat.attachment');
|
||||
|
||||
// JSON-Schnittstelle der Chat-Oberfläche
|
||||
Route::prefix('chat/api')->name('chat.api.')->group(function () {
|
||||
Route::get('/neues', [MessageController::class, 'updates'])->middleware('throttle:120,1')->name('updates');
|
||||
Route::get('/ungelesen', [MessageController::class, 'unread'])->middleware('throttle:60,1')->name('unread');
|
||||
Route::get('/gifs', [MessageController::class, 'gifs'])->middleware('throttle:60,1')->name('gifs');
|
||||
Route::post('/echtzeit/anmelden', [MessageController::class, 'realtimeAuth'])->middleware('throttle:30,1')->name('realtime');
|
||||
|
||||
Route::get('/gespraeche', [ConversationController::class, 'index'])->name('conversations');
|
||||
Route::post('/direkt', [ConversationController::class, 'direct'])->middleware('throttle:30,1')->name('direct');
|
||||
Route::post('/gruppen', [ConversationController::class, 'createGroup'])->middleware('throttle:10,1')->name('groups');
|
||||
Route::put('/gespraeche/{conversation}', [ConversationController::class, 'update'])->name('update');
|
||||
Route::delete('/gespraeche/{conversation}', [ConversationController::class, 'leave'])->name('leave');
|
||||
Route::post('/gespraeche/{conversation}/mitglieder', [ConversationController::class, 'addMembers'])->name('members.add');
|
||||
Route::delete('/gespraeche/{conversation}/mitglieder/{user}', [ConversationController::class, 'removeMember'])->name('members.remove');
|
||||
Route::put('/gespraeche/{conversation}/mitglieder/{user}', [ConversationController::class, 'setAdmin'])->name('members.admin');
|
||||
|
||||
Route::get('/gespraeche/{conversation}/nachrichten', [MessageController::class, 'index'])->name('messages');
|
||||
Route::post('/gespraeche/{conversation}/nachrichten', [MessageController::class, 'store'])->middleware('throttle:60,1')->name('send');
|
||||
Route::post('/gespraeche/{conversation}/gelesen', [MessageController::class, 'read'])->name('read');
|
||||
Route::post('/gespraeche/{conversation}/tippt', [MessageController::class, 'typing'])->middleware('throttle:60,1')->name('typing');
|
||||
Route::put('/nachrichten/{message}', [MessageController::class, 'update'])->name('edit');
|
||||
Route::delete('/nachrichten/{message}', [MessageController::class, 'destroy'])->name('delete');
|
||||
Route::post('/nachrichten/{message}/reaktion', [MessageController::class, 'react'])->middleware('throttle:60,1')->name('react');
|
||||
});
|
||||
});
|
||||
317
src/Chat.php
Normal file
317
src/Chat.php
Normal 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
38
src/ChatPlugin.php
Normal 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);
|
||||
}
|
||||
}
|
||||
153
src/Filament/Pages/ChatSettings.php
Normal file
153
src/Filament/Pages/ChatSettings.php
Normal 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();
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
79
src/Filament/Resources/Gifs/GifResource.php
Normal file
79
src/Filament/Resources/Gifs/GifResource.php
Normal 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('/')];
|
||||
}
|
||||
}
|
||||
17
src/Filament/Resources/Gifs/Pages/ManageGifs.php
Normal file
17
src/Filament/Resources/Gifs/Pages/ManageGifs.php
Normal 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
90
src/Gifs.php
Normal 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();
|
||||
}
|
||||
}
|
||||
135
src/Http/Controllers/ConversationController.php
Normal file
135
src/Http/Controllers/ConversationController.php
Normal 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));
|
||||
}
|
||||
}
|
||||
181
src/Http/Controllers/MessageController.php
Normal file
181
src/Http/Controllers/MessageController.php
Normal 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
30
src/Models/Attachment.php
Normal 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);
|
||||
}
|
||||
}
|
||||
74
src/Models/Conversation.php
Normal file
74
src/Models/Conversation.php
Normal 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
27
src/Models/Gif.php
Normal 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
62
src/Models/Message.php
Normal 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);
|
||||
}
|
||||
}
|
||||
53
src/Models/Participant.php
Normal file
53
src/Models/Participant.php
Normal 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
20
src/Models/Reaction.php
Normal 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
53
src/Notifier.php
Normal 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
112
src/Presenter.php
Normal 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
122
src/Realtime.php
Normal 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 '';
|
||||
}
|
||||
}
|
||||
}
|
||||
209
tests/ChatTest.php
Normal file
209
tests/ChatTest.php
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Plugins\Chat;
|
||||
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Notifications\PortalNotification;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
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\Models\Conversation;
|
||||
use Inhaus\Plugins\Chat\Models\Gif;
|
||||
use Inhaus\Plugins\Chat\Models\Message;
|
||||
use Inhaus\Plugins\Chat\Realtime;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Läuft innerhalb einer Inhaus-Installation, in der das Plugin unter plugins/chat liegt:
|
||||
* vendor-dev/bin/phpunit plugins/chat/tests
|
||||
*/
|
||||
class ChatTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private ?string $previousState = null;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
// Plugin aktivieren, bevor die Anwendung startet – so laufen seine Migrationen mit
|
||||
// (Kunden-Plugins sind nach der Installation aus)
|
||||
$file = getcwd().'/storage/app/plugins.json';
|
||||
$this->previousState = is_file($file) ? file_get_contents($file) : null;
|
||||
$state = json_decode($this->previousState ?? '{}', true) ?: [];
|
||||
$state['chat'] = ['enabled' => true];
|
||||
file_put_contents($file, json_encode($state));
|
||||
|
||||
parent::setUp();
|
||||
|
||||
Storage::fake('local');
|
||||
Storage::fake('uploads');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$file = storage_path('app/plugins.json');
|
||||
$this->previousState === null ? @unlink($file) : file_put_contents($file, $this->previousState);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function dm(User $a, User $b): int
|
||||
{
|
||||
return $this->actingAs($a)->postJson('/chat/api/direkt', ['user_id' => $b->id])->assertOk()->json('id');
|
||||
}
|
||||
|
||||
public function test_direct_messages_unread_and_privacy(): void
|
||||
{
|
||||
[$ada, $bob, $eve] = User::factory()->count(3)->create()->all();
|
||||
$id = $this->dm($ada, $bob);
|
||||
$this->assertSame($id, $this->dm($bob, $ada)); // ein Gespräch je Paar
|
||||
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['body' => 'Hallo Bob 👋'])->assertCreated()->assertJsonPath('message.body', 'Hallo Bob 👋');
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['body' => ' '])->assertUnprocessable();
|
||||
|
||||
$this->actingAs($bob)->getJson('/chat/api/ungelesen')->assertJsonPath('unread', 1);
|
||||
$this->actingAs($bob)->get('/')->assertInertia(fn (Assert $p) => $p->where('headerItems.0.component', 'chat::Unread')->where('headerItems.0.props.unread', 1));
|
||||
|
||||
$messageId = $this->actingAs($bob)->getJson("/chat/api/gespraeche/{$id}/nachrichten")->assertOk()->json('messages.0.id');
|
||||
$this->actingAs($bob)->postJson("/chat/api/gespraeche/{$id}/gelesen", ['message_id' => $messageId])->assertJsonPath('unread', 0);
|
||||
|
||||
// Andere – auch die Administration – kommen nicht hinein
|
||||
$this->actingAs($eve)->getJson("/chat/api/gespraeche/{$id}/nachrichten")->assertNotFound();
|
||||
$this->actingAs(User::factory()->admin()->create())->getJson("/chat/api/gespraeche/{$id}/nachrichten")->assertNotFound();
|
||||
$this->actingAs($eve)->get("/chat/{$id}")->assertNotFound();
|
||||
$this->actingAs($ada)->get("/chat/{$id}")->assertOk()->assertInertia(fn (Assert $p) => $p->component('chat::Index')->where('activeId', $id)->has('conversations', 1));
|
||||
}
|
||||
|
||||
public function test_attachments_are_private_and_dangerous_files_blocked(): void
|
||||
{
|
||||
[$ada, $bob, $eve] = User::factory()->count(3)->create()->all();
|
||||
$id = $this->dm($ada, $bob);
|
||||
|
||||
$this->actingAs($ada)->post("/chat/api/gespraeche/{$id}/nachrichten", ['files' => [UploadedFile::fake()->create('boese.php', 1, 'text/x-php')]], ['Accept' => 'application/json'])
|
||||
->assertUnprocessable();
|
||||
|
||||
$response = $this->actingAs($ada)->post("/chat/api/gespraeche/{$id}/nachrichten", [
|
||||
'body' => 'Foto und Plan',
|
||||
'files' => [UploadedFile::fake()->image('foto.jpg', 400, 300), UploadedFile::fake()->create('Dienstplan.pdf', 50, 'application/pdf')],
|
||||
], ['Accept' => 'application/json'])->assertCreated();
|
||||
|
||||
$image = $response->json('message.attachments.0');
|
||||
$this->assertTrue($image['image']);
|
||||
$this->assertSame(400, $image['width']);
|
||||
|
||||
$this->actingAs($bob)->get($image['url'])->assertOk()->assertHeader('X-Content-Type-Options', 'nosniff');
|
||||
$this->actingAs($eve)->get($image['url'])->assertNotFound();
|
||||
$this->assertStringContainsString('attachment', $this->actingAs($bob)->get($response->json('message.attachments.1.url'))->headers->get('Content-Disposition'));
|
||||
|
||||
// Löschen entfernt auch die Dateien
|
||||
$this->actingAs($ada)->deleteJson('/chat/api/nachrichten/'.$response->json('message.id'))->assertOk();
|
||||
$this->assertSame([], Storage::disk('local')->allFiles('chat'));
|
||||
}
|
||||
|
||||
public function test_groups_need_the_right_and_admins_manage_members(): void
|
||||
{
|
||||
[$ada, $bob, $cem] = User::factory()->count(3)->create()->all();
|
||||
$this->actingAs($ada)->postJson('/chat/api/gruppen', ['name' => 'Team', 'members' => [$bob->id]])->assertForbidden();
|
||||
|
||||
$role = Role::query()->create(['name' => 'Teamleitung']);
|
||||
$role->grants()->create(['ability' => 'chat.groups.create']);
|
||||
$ada->roles()->attach($role);
|
||||
|
||||
$id = $this->actingAs($ada)->postJson('/chat/api/gruppen', ['name' => 'Station 3', 'members' => [$bob->id]])->assertCreated()->json('id');
|
||||
$this->actingAs($bob)->postJson("/chat/api/gespraeche/{$id}/mitglieder", ['members' => [$cem->id]])->assertForbidden();
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/mitglieder", ['members' => [$cem->id]])->assertOk();
|
||||
$this->actingAs($cem)->getJson("/chat/api/gespraeche/{$id}/nachrichten")->assertOk()->assertJsonPath('messages.1.kind', 'system');
|
||||
|
||||
// Letzte Admin-Person verlässt die Gruppe → Nächste übernimmt
|
||||
$this->actingAs($ada)->deleteJson("/chat/api/gespraeche/{$id}")->assertOk();
|
||||
$this->actingAs($ada)->getJson("/chat/api/gespraeche/{$id}/nachrichten")->assertNotFound();
|
||||
$this->assertSame('admin', Conversation::query()->find($id)->participant($bob)->role);
|
||||
$this->actingAs($bob)->deleteJson("/chat/api/gespraeche/{$id}/mitglieder/{$cem->id}")->assertOk();
|
||||
$this->actingAs($cem)->getJson("/chat/api/gespraeche/{$id}/nachrichten")->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_updates_edit_react_and_typing(): void
|
||||
{
|
||||
[$ada, $bob] = User::factory()->count(2)->create()->all();
|
||||
$id = $this->dm($ada, $bob);
|
||||
$cursor = $this->actingAs($bob)->getJson("/chat/api/neues?offen={$id}")->json('cursor');
|
||||
|
||||
$messageId = $this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['body' => 'Kommst du?'])->json('message.id');
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/tippt")->assertOk();
|
||||
|
||||
$this->actingAs($bob)->getJson('/chat/api/neues?'.http_build_query(['offen' => $id, 'seit' => $cursor, 'nach' => 0]))
|
||||
->assertJsonPath('messages.0.body', 'Kommst du?')->assertJsonPath('typing.0', $ada->first_name)->assertJsonPath('unread', 1)
|
||||
->assertJsonPath('conversations.0.id', $id);
|
||||
|
||||
$this->actingAs($bob)->putJson("/chat/api/nachrichten/{$messageId}", ['body' => 'geändert'])->assertForbidden();
|
||||
$this->actingAs($ada)->putJson("/chat/api/nachrichten/{$messageId}", ['body' => 'Kommst du heute?'])->assertOk();
|
||||
$this->actingAs($bob)->postJson("/chat/api/nachrichten/{$messageId}/reaktion", ['emoji' => '👍'])->assertOk();
|
||||
$this->actingAs($bob)->postJson("/chat/api/nachrichten/{$messageId}/reaktion", ['emoji' => '🍕'])->assertUnprocessable();
|
||||
|
||||
$this->actingAs($ada)->getJson("/chat/api/gespraeche/{$id}/nachrichten")
|
||||
->assertJsonPath('messages.0.body', 'Kommst du heute?')->assertJsonPath('messages.0.edited', true)
|
||||
->assertJsonPath('messages.0.reactions.0.emoji', '👍')->assertJsonPath('messages.0.reactions.0.mine', false);
|
||||
}
|
||||
|
||||
public function test_gifs_from_own_collection_and_giphy(): void
|
||||
{
|
||||
[$ada, $bob] = User::factory()->count(2)->create()->all();
|
||||
$id = $this->dm($ada, $bob);
|
||||
Storage::disk('uploads')->put('chat-gifs/daumen.gif', 'GIF89a');
|
||||
Gif::query()->create(['path' => 'chat-gifs/daumen.gif', 'title' => 'Daumen hoch', 'tags' => 'super']);
|
||||
|
||||
$own = $this->actingAs($ada)->getJson('/chat/api/gifs?q=super')->assertOk()->assertJsonPath('giphy', false)->json('gifs.0.url');
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['gif_url' => $own])->assertCreated()->assertJsonPath('message.kind', 'gif');
|
||||
|
||||
$giphy = 'https://media2.giphy.com/media/abc123/200.gif?cid=x&rid=200.gif';
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['gif_url' => $giphy])->assertUnprocessable();
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['gif_url' => 'https://evil.example/x.gif'])->assertUnprocessable();
|
||||
|
||||
app(Settings::class)->set('chat.giphy_key', Crypt::encryptString('gk'));
|
||||
Http::fake(['api.giphy.com/*' => Http::response(['data' => [['title' => 'Yay', 'images' => ['fixed_height' => ['url' => $giphy, 'width' => '200', 'height' => '200']]]]])]);
|
||||
$this->actingAs($ada)->getJson('/chat/api/gifs?q=yay')->assertJsonPath('gifs.0.source', 'giphy');
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['gif_url' => $giphy])->assertCreated();
|
||||
}
|
||||
|
||||
public function test_notifications_once_until_read_and_not_while_open(): void
|
||||
{
|
||||
Notification::fake();
|
||||
[$ada, $bob] = User::factory()->count(2)->create()->all();
|
||||
$id = $this->dm($ada, $bob);
|
||||
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['body' => 'Eins']);
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['body' => 'Zwei']);
|
||||
Notification::assertSentToTimes($bob, PortalNotification::class, 1);
|
||||
|
||||
$last = Message::query()->max('id');
|
||||
$this->actingAs($bob)->postJson("/chat/api/gespraeche/{$id}/gelesen", ['message_id' => $last]);
|
||||
$this->actingAs($bob)->getJson("/chat/api/neues?offen={$id}"); // Bob hat das Gespräch offen
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['body' => 'Drei']);
|
||||
Notification::assertSentToTimes($bob, PortalNotification::class, 1);
|
||||
}
|
||||
|
||||
public function test_realtime_signals_without_content_and_private_channels(): void
|
||||
{
|
||||
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', 'chat.realtime.port' => 443]);
|
||||
Http::fake(['ws.example.org/*' => Http::response([])]);
|
||||
[$ada, $bob] = User::factory()->count(2)->create()->all();
|
||||
$id = $this->dm($ada, $bob);
|
||||
|
||||
$this->actingAs($ada)->postJson("/chat/api/gespraeche/{$id}/nachrichten", ['body' => 'Geheimer Inhalt']);
|
||||
|
||||
Http::assertSent(fn ($r) => str_starts_with($r->url(), 'https://ws.example.org/apps/42/events?')
|
||||
&& str_contains($r->url(), 'auth_signature=')
|
||||
&& in_array(Realtime::channel($bob->id), $r['channels'], true)
|
||||
&& ! str_contains($r->body(), 'Geheimer'));
|
||||
|
||||
$this->actingAs($ada)->postJson('/chat/api/echtzeit/anmelden', ['socket_id' => '123.456', 'channel_name' => Realtime::channel($ada->id)])
|
||||
->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();
|
||||
}
|
||||
}
|
||||
5
vite.config.js
Normal file
5
vite.config.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { defineConfig } from 'vite';
|
||||
import { inhausPlugin } from './inhaus-sdk/vite.js';
|
||||
|
||||
// Baut resources/js/{pages,widgets,blocks,…} nach dist/ (siehe inhaus-sdk/vite.js)
|
||||
export default defineConfig(inhausPlugin());
|
||||
Loading…
Add table
Add a link
Reference in a new issue