diff --git a/.ai/guidelines/workflow/02-triage-labels.blade.php b/.ai/guidelines/workflow/02-triage-labels.blade.php index 56d22eb9a..d6c39d783 100644 --- a/.ai/guidelines/workflow/02-triage-labels.blade.php +++ b/.ai/guidelines/workflow/02-triage-labels.blade.php @@ -50,6 +50,7 @@ | `mod:identity` | `identity` | Auth & user identity | | `mod:integration-devto` | `integration-devto` | Dev.to integration | | `mod:integration-discord`| `integration-discord` | Discord OAuth/API | +| `mod:integration-slido` | `integration-slido` | Slido Q&A integration | | `mod:integration-twitch` | `integration-twitch` | Twitch integration | | `mod:marketing` | `marketing` | Encurtador, campanhas | | `mod:moderation` | `moderation` | Moderation pipeline | diff --git a/app-modules/integration-slido/composer.json b/app-modules/integration-slido/composer.json new file mode 100644 index 000000000..79335bfc8 --- /dev/null +++ b/app-modules/integration-slido/composer.json @@ -0,0 +1,32 @@ +{ + "name": "he4rt/integration-slido", + "description": "", + "type": "library", + "version": "1.0.0", + "license": "proprietary", + "require": { + "ratchet/pawl": "^0.4.3", + "react/event-loop": "^1.6.0", + "saloonphp/saloon": "^4.5.0" + }, + "autoload": { + "psr-4": { + "He4rt\\IntegrationSlido\\": "src/", + "He4rt\\IntegrationSlido\\Database\\Factories\\": "database/factories/", + "He4rt\\IntegrationSlido\\Database\\Seeders\\": "database/seeders/" + } + }, + "autoload-dev": { + "psr-4": { + "He4rt\\IntegrationSlido\\Tests\\": "tests/" + } + }, + "minimum-stability": "stable", + "extra": { + "laravel": { + "providers": [ + "He4rt\\IntegrationSlido\\IntegrationSlidoServiceProvider" + ] + } + } +} diff --git a/app-modules/integration-slido/config/integration-slido.php b/app-modules/integration-slido/config/integration-slido.php new file mode 100644 index 000000000..a131a788d --- /dev/null +++ b/app-modules/integration-slido/config/integration-slido.php @@ -0,0 +1,11 @@ + env('SLIDO_CLIENT_ID', '8d10c777-8ac6-4eb9-9d78-1e66cfc93b24'), + 'auth_url' => env('SLIDO_AUTH_URL', 'https://auth.slido.com'), + 'lookup_url' => env('SLIDO_LOOKUP_URL', 'https://app.sli.do/global/api'), + 'wall_url' => env('SLIDO_WALL_URL', 'https://wall.sli.do'), + 'stream_url' => env('SLIDO_STREAM_URL', 'wss://wall.sli.do'), +]; diff --git a/app-modules/integration-slido/database/factories/.gitkeep b/app-modules/integration-slido/database/factories/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/app-modules/integration-slido/database/migrations/.gitkeep b/app-modules/integration-slido/database/migrations/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/app-modules/integration-slido/database/seeders/.gitkeep b/app-modules/integration-slido/database/seeders/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/app-modules/integration-slido/phpstan.ignore.neon b/app-modules/integration-slido/phpstan.ignore.neon new file mode 100644 index 000000000..f51e71c3f --- /dev/null +++ b/app-modules/integration-slido/phpstan.ignore.neon @@ -0,0 +1,2 @@ +parameters: + ignoreErrors: [] diff --git a/app-modules/integration-slido/phpstan.neon b/app-modules/integration-slido/phpstan.neon new file mode 100644 index 000000000..b577d0f29 --- /dev/null +++ b/app-modules/integration-slido/phpstan.neon @@ -0,0 +1,6 @@ +includes: + - phpstan.ignore.neon + +parameters: + paths: + - src/ diff --git a/app-modules/integration-slido/src/Broadcasting/SlidoQuestionChanged.php b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionChanged.php new file mode 100644 index 000000000..b478bd925 --- /dev/null +++ b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionChanged.php @@ -0,0 +1,46 @@ + $streamers + */ + public function __construct( + public array $streamers, + public SlidoQuestion $question, + ) {} + + /** @return array */ + public function broadcastOn(): array + { + return array_map(fn (Streamer $streamer): PrivateChannel => new PrivateChannel($streamer->overlayChannel()), $this->streamers); + } + + public function broadcastAs(): string + { + return 'pub.question'; + } + + /** + * @return array + */ + public function broadcastWith(): array + { + return $this->question->toArray(); + } +} diff --git a/app-modules/integration-slido/src/Broadcasting/SlidoQuestionPatched.php b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionPatched.php new file mode 100644 index 000000000..dcc09fc76 --- /dev/null +++ b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionPatched.php @@ -0,0 +1,46 @@ + $streamers + */ + public function __construct( + public array $streamers, + public SlidoQuestionPatch $patch, + ) {} + + /** @return array */ + public function broadcastOn(): array + { + return array_map(fn (Streamer $streamer): PrivateChannel => new PrivateChannel($streamer->overlayChannel()), $this->streamers); + } + + public function broadcastAs(): string + { + return 'pub.question-patch'; + } + + /** + * @return array{id: int, changes: array} + */ + public function broadcastWith(): array + { + return $this->patch->toArray(); + } +} diff --git a/app-modules/integration-slido/src/Broadcasting/SlidoQuestionsSynced.php b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionsSynced.php new file mode 100644 index 000000000..78970e082 --- /dev/null +++ b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionsSynced.php @@ -0,0 +1,47 @@ + $streamers + * @param list $questions + */ + public function __construct( + public array $streamers, + public array $questions, + ) {} + + /** @return array */ + public function broadcastOn(): array + { + return array_map(fn (Streamer $streamer): PrivateChannel => new PrivateChannel($streamer->overlayChannel()), $this->streamers); + } + + public function broadcastAs(): string + { + return 'pub.questions'; + } + + /** + * @return array{questions: list>} + */ + public function broadcastWith(): array + { + return ['questions' => array_map(fn (SlidoQuestion $question): array => $question->toArray(), $this->questions)]; + } +} diff --git a/app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php b/app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php new file mode 100644 index 000000000..a50dd0da1 --- /dev/null +++ b/app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php @@ -0,0 +1,113 @@ + */ + private array $connections = []; + + /** @var array */ + private array $locations = []; + + public function handle(SlidoClient $client, QuestionFeed $feed, SlidoAudience $audience): int + { + $loop = Loop::get(); + $interval = max(5, (int) $this->option('interval')); + + $this->log(sprintf('Conferindo as overlays He4rt Pub a cada %ds.', $interval)); + + $reconcile = function () use ($client, $feed, $audience, $loop): void { + try { + $this->reconcile($client, $feed, $audience->current(), $loop); + } catch (Throwable $throwable) { + $this->log('Falhou ao conferir as overlays: '.$throwable->getMessage()); + } + }; + + $reconcile(); + $loop->addPeriodicTimer($interval, $reconcile); + $loop->run(); + + return self::SUCCESS; + } + + /** + * @param array> $audience + */ + private function reconcile(SlidoClient $client, QuestionFeed $feed, array $audience, LoopInterface $loop): void + { + $plan = SlidoSubscriptionPlan::between($this->hashesOf($audience), $this->hashesOf($this->connections)); + + foreach ($plan->closing as $eventHash) { + $this->connections[$eventHash]->close(); + unset($this->connections[$eventHash]); + $this->log(sprintf('[%s] Nenhuma overlay aberta: desconectou.', $eventHash)); + } + + foreach ($plan->keeping as $eventHash) { + $this->connections[$eventHash]->session->retarget($audience[$eventHash]); + } + + foreach ($plan->opening as $eventHash) { + $this->open($client, $feed, $eventHash, $audience[$eventHash], $loop); + } + } + + /** + * @param list $streamers + */ + private function open(SlidoClient $client, QuestionFeed $feed, string $eventHash, array $streamers, LoopInterface $loop): void + { + try { + $location = $this->locations[$eventHash] ??= $client->locate($eventHash); + } catch (Throwable $throwable) { + $this->log(sprintf('[%s] Não achou o evento no Slido: %s', $eventHash, $throwable->getMessage())); + + return; + } + + $log = fn (string $line) => $this->log(sprintf('[%s] %s', $eventHash, $line)); + $session = new SlidoStreamSession($client, $feed, $location, $streamers, $log); + $connection = new SlidoConnection($session, $loop, $log); + + $this->connections[$eventHash] = $connection; + $log(sprintf('Conectando para %d overlay(s).', count($streamers))); + $connection->open(); + } + + /** + * PHP turns a digit-only event hash into an integer array key. + * + * @param array $keyedByHash + * @return list + */ + private function hashesOf(array $keyedByHash): array + { + return array_map(strval(...), array_keys($keyedByHash)); + } + + private function log(string $line): void + { + $this->line(sprintf('[%s] %s', now()->format('H:i:s'), $line)); + } +} diff --git a/app-modules/integration-slido/src/Data/SlidoEvent.php b/app-modules/integration-slido/src/Data/SlidoEvent.php new file mode 100644 index 000000000..95c46c6ce --- /dev/null +++ b/app-modules/integration-slido/src/Data/SlidoEvent.php @@ -0,0 +1,51 @@ + $payload + */ + public static function fromPayload(SlidoEventLocation $location, array $payload): self + { + $name = $payload['name'] ?? null; + $participantUrl = is_array($payload['url'] ?? null) ? ($payload['url']['app'] ?? null) : null; + + throw_unless(is_string($name) && is_string($participantUrl), SlidoResponseInvalid::missing('event', 'name, url.app')); + + return new self( + location: $location, + name: $name, + code: is_scalar($payload['code'] ?? null) ? (string) $payload['code'] : '', + isActive: ($payload['is_active'] ?? false) === true, + participantUrl: $participantUrl, + ); + } + + /** + * @return array{hash: string, name: string, code: string, isActive: bool, participantUrl: string} + */ + public function toArray(): array + { + return [ + 'hash' => $this->location->hash, + 'name' => $this->name, + 'code' => $this->code, + 'isActive' => $this->isActive, + 'participantUrl' => $this->participantUrl, + ]; + } +} diff --git a/app-modules/integration-slido/src/Data/SlidoEventHash.php b/app-modules/integration-slido/src/Data/SlidoEventHash.php new file mode 100644 index 000000000..84b4b41d3 --- /dev/null +++ b/app-modules/integration-slido/src/Data/SlidoEventHash.php @@ -0,0 +1,23 @@ +string('integration-slido.wall_url'), '/'), $this->hash); + } + + public function streamTarget(): string + { + return sprintf('slido/events/%s/', $this->uuid); + } +} diff --git a/app-modules/integration-slido/src/Data/SlidoParticipantToken.php b/app-modules/integration-slido/src/Data/SlidoParticipantToken.php new file mode 100644 index 000000000..90eccca9d --- /dev/null +++ b/app-modules/integration-slido/src/Data/SlidoParticipantToken.php @@ -0,0 +1,47 @@ + $payload + */ + public static function fromPayload(array $payload): self + { + $accessToken = $payload['access_token'] ?? null; + $refreshToken = $payload['refresh_token'] ?? null; + $expiresIn = $payload['expires_in'] ?? null; + + $hasValidShape = is_string($accessToken) && is_string($refreshToken) && is_int($expiresIn); + + throw_unless($hasValidShape, SlidoResponseInvalid::missing('token', 'access_token, refresh_token, expires_in')); + + return new self($accessToken, $refreshToken, CarbonImmutable::now()->addSeconds($expiresIn)); + } + + public function needsRefresh(): bool + { + return CarbonImmutable::now()->addSeconds(self::REFRESH_MARGIN_SECONDS)->greaterThanOrEqualTo($this->expiresAt); + } + + public function secondsUntilRefresh(): int + { + $seconds = (int) CarbonImmutable::now()->diffInSeconds($this->expiresAt->subSeconds(self::REFRESH_MARGIN_SECONDS), absolute: false); + + return max($seconds, 1); + } +} diff --git a/app-modules/integration-slido/src/Data/SlidoQuestion.php b/app-modules/integration-slido/src/Data/SlidoQuestion.php new file mode 100644 index 000000000..d08508f4f --- /dev/null +++ b/app-modules/integration-slido/src/Data/SlidoQuestion.php @@ -0,0 +1,122 @@ + $replies + */ + public function __construct( + public int $id, + public string $text, + public ?string $authorName, + public int $score, + public bool $isHighlighted, + public bool $isAnswered, + public bool $isVisible, + public CarbonImmutable $createdAt, + public array $replies = [], + ) {} + + /** + * @param array $payload + */ + public static function tryFromPayload(array $payload): ?self + { + $id = $payload['event_question_id'] ?? null; + $text = $payload['text'] ?? null; + $isQuestion = ($payload['type'] ?? 'Question') === 'Question'; + + if (!$isQuestion || !is_int($id) || !is_string($text)) { + return null; + } + + $isPublic = ($payload['is_public'] ?? true) === true; + $isDeleted = ($payload['date_deleted'] ?? null) !== null; + $createdAt = self::createdAtOf($payload['date_created'] ?? null); + $pinnedReplies = is_array($payload['pinned_replies'] ?? null) ? $payload['pinned_replies'] : []; + + return new self( + id: $id, + text: $text, + authorName: self::authorNameOf($payload), + score: is_int($payload['score'] ?? null) ? $payload['score'] : 0, + isHighlighted: ($payload['is_highlighted'] ?? false) === true, + isAnswered: ($payload['is_answered'] ?? false) === true, + isVisible: $isPublic && !$isDeleted, + createdAt: $createdAt, + replies: self::repliesOf($pinnedReplies), + ); + } + + /** + * @param array $payload + */ + public static function authorNameOf(array $payload): ?string + { + if (($payload['is_anonymous'] ?? false) === true) { + return null; + } + + $author = is_array($payload['author'] ?? null) ? $payload['author'] : []; + $name = $author['name'] ?? null; + + return is_string($name) && $name !== '' ? $name : null; + } + + /** + * @return array{id: int, text: string, authorName: string|null, score: int, isHighlighted: bool, isAnswered: bool, isVisible: bool, createdAt: string, replies: list} + */ + public function toArray(): array + { + return [ + 'id' => $this->id, + 'text' => $this->text, + 'authorName' => $this->authorName, + 'score' => $this->score, + 'isHighlighted' => $this->isHighlighted, + 'isAnswered' => $this->isAnswered, + 'isVisible' => $this->isVisible, + 'createdAt' => $this->createdAt->toIso8601String(), + 'replies' => array_map(fn (SlidoReply $reply): array => $reply->toArray(), $this->replies), + ]; + } + + private static function createdAtOf(mixed $value): CarbonImmutable + { + if (!is_string($value)) { + return CarbonImmutable::now(); + } + + try { + return CarbonImmutable::parse($value); + } catch (InvalidFormatException) { + return CarbonImmutable::now(); + } + } + + /** + * @param array $pinnedReplies + * @return list + */ + private static function repliesOf(array $pinnedReplies): array + { + $replies = []; + + foreach ($pinnedReplies as $pinnedReply) { + $reply = is_array($pinnedReply) ? SlidoReply::tryFromPayload($pinnedReply) : null; + + if ($reply instanceof SlidoReply) { + $replies[] = $reply; + } + } + + return $replies; + } +} diff --git a/app-modules/integration-slido/src/Data/SlidoQuestionPatch.php b/app-modules/integration-slido/src/Data/SlidoQuestionPatch.php new file mode 100644 index 000000000..c5f99eadf --- /dev/null +++ b/app-modules/integration-slido/src/Data/SlidoQuestionPatch.php @@ -0,0 +1,54 @@ + 'score', + 'is_highlighted' => 'isHighlighted', + 'is_answered' => 'isAnswered', + ]; + + /** + * @param array $changes + */ + public function __construct( + public int $id, + public array $changes, + ) {} + + /** + * @param array $payload + */ + public static function tryFromPayload(array $payload): ?self + { + $id = $payload['event_question_id'] ?? null; + + if (!is_int($id)) { + return null; + } + + $changes = []; + + foreach (self::FIELDS as $source => $target) { + $value = $payload[$source] ?? null; + + if (is_int($value) || is_bool($value)) { + $changes[$target] = $value; + } + } + + return $changes === [] ? null : new self($id, $changes); + } + + /** + * @return array{id: int, changes: array} + */ + public function toArray(): array + { + return ['id' => $this->id, 'changes' => $this->changes]; + } +} diff --git a/app-modules/integration-slido/src/Data/SlidoReply.php b/app-modules/integration-slido/src/Data/SlidoReply.php new file mode 100644 index 000000000..fd5ad0d43 --- /dev/null +++ b/app-modules/integration-slido/src/Data/SlidoReply.php @@ -0,0 +1,50 @@ + $payload + */ + public static function tryFromPayload(array $payload): ?self + { + $id = $payload['event_question_id'] ?? null; + $text = $payload['text'] ?? null; + + if (!is_int($id) || !is_string($text)) { + return null; + } + + $attrs = is_array($payload['attrs'] ?? null) ? $payload['attrs'] : []; + + return new self( + id: $id, + text: $text, + authorName: SlidoQuestion::authorNameOf($payload), + isFromModerator: ($attrs['is_admin'] ?? false) === true, + ); + } + + /** + * @return array{id: int, text: string, authorName: string|null, isFromModerator: bool} + */ + public function toArray(): array + { + return [ + 'id' => $this->id, + 'text' => $this->text, + 'authorName' => $this->authorName, + 'isFromModerator' => $this->isFromModerator, + ]; + } +} diff --git a/app-modules/integration-slido/src/Exceptions/SlidoResponseInvalid.php b/app-modules/integration-slido/src/Exceptions/SlidoResponseInvalid.php new file mode 100644 index 000000000..a7a6fd02c --- /dev/null +++ b/app-modules/integration-slido/src/Exceptions/SlidoResponseInvalid.php @@ -0,0 +1,15 @@ +mergeConfigFrom(__DIR__.'/../config/integration-slido.php', 'integration-slido'); + + $this->app->bind(SlidoAuthConnector::class, fn (): SlidoAuthConnector => new SlidoAuthConnector( + baseUrl: config()->string('integration-slido.auth_url'), + clientId: config()->string('integration-slido.client_id'), + )); + + $this->app->bind(SlidoLookupConnector::class, fn (): SlidoLookupConnector => new SlidoLookupConnector( + baseUrl: config()->string('integration-slido.lookup_url'), + )); + } + + public function boot(): void + { + if ($this->app->runningInConsole()) { + $this->commands([ServeSlidoEventsCommand::class]); + } + } +} diff --git a/app-modules/integration-slido/src/Stream/FrameKind.php b/app-modules/integration-slido/src/Stream/FrameKind.php new file mode 100644 index 000000000..82e2ef146 --- /dev/null +++ b/app-modules/integration-slido/src/Stream/FrameKind.php @@ -0,0 +1,17 @@ +isAnyOf($frame, self::SNAPSHOT_EVENTS) ? SlidoQuestion::tryFromPayload($frame->params()) : null; + } + + public function patchFrom(SocketIoFrame $frame): ?SlidoQuestionPatch + { + return $this->isAnyOf($frame, self::PATCH_EVENTS) ? SlidoQuestionPatch::tryFromPayload($frame->params()) : null; + } + + public function isKnown(SocketIoFrame $frame): bool + { + return $this->isAnyOf($frame, [...self::SNAPSHOT_EVENTS, ...self::PATCH_EVENTS, ...self::IGNORED_EVENTS]); + } + + /** + * @param list $eventNames + */ + private function isAnyOf(SocketIoFrame $frame, array $eventNames): bool + { + return $frame->kind === FrameKind::Event && in_array($frame->eventName, $eventNames, strict: true); + } +} diff --git a/app-modules/integration-slido/src/Stream/SlidoAudience.php b/app-modules/integration-slido/src/Stream/SlidoAudience.php new file mode 100644 index 000000000..c99514a3f --- /dev/null +++ b/app-modules/integration-slido/src/Stream/SlidoAudience.php @@ -0,0 +1,49 @@ +> + */ + public function current(): array + { + $audience = []; + + $streamers = Streamer::query() + ->where('status', StreamerStatus::Active) + ->whereNotNull(sprintf('settings->scenes->%s->slido_event_hash', OverlayScene::Pub->value)) + ->get(); + + foreach ($streamers as $streamer) { + $eventHash = $streamer->settings->pub->slidoEventHash; + $hasOverlayClosed = $this->connections->count($streamer) === 0; + + if ($eventHash === null || $hasOverlayClosed) { + continue; + } + + $audience[$eventHash][] = $streamer; + } + + return $audience; + } +} diff --git a/app-modules/integration-slido/src/Stream/SlidoConnection.php b/app-modules/integration-slido/src/Stream/SlidoConnection.php new file mode 100644 index 000000000..d20888825 --- /dev/null +++ b/app-modules/integration-slido/src/Stream/SlidoConnection.php @@ -0,0 +1,170 @@ +isClosed) { + return; + } + + (new Connector($this->loop))($this->session->streamUrl(), [], ['Origin' => self::ORIGIN])->then( + function (WebSocket $socket): void { + if ($this->isClosed) { + $socket->close(); + + return; + } + + $this->socket = $socket; + + $socket->on('message', function (MessageInterface $message) use ($socket): void { + $this->receive($socket, (string) $message); + }); + + $socket->on('close', function (?int $code = null, ?string $reason = null): void { + if ($this->isClosed) { + return; + } + + ($this->log)(sprintf('Conexão fechada (%s %s).', $code ?? '-', $reason ?? '')); + $this->reconnect(); + }); + + try { + $this->scheduleTokenRefresh(); + } catch (Throwable $throwable) { + ($this->log)('Falhou ao preparar o token: '.$throwable->getMessage()); + $socket->close(); + } + }, + function (Throwable $throwable): void { + ($this->log)('Falhou ao conectar no Slido: '.$throwable->getMessage()); + $this->reconnect(); + }, + ); + } + + public function close(): void + { + $this->isClosed = true; + $this->cancelTimers(); + $this->socket?->close(); + $this->socket = null; + } + + private function receive(WebSocket $socket, string $raw): void + { + try { + $this->sendAll($socket, $this->session->handle($raw)); + + if ($this->session->isSubscribed()) { + $this->reconnectAttempts = 0; + } + } catch (SlidoSubscriptionRejected $rejected) { + ($this->log)($rejected->getMessage()); + $socket->close(); + } catch (Throwable $throwable) { + ($this->log)('Falhou ao tratar um frame do Slido: '.$throwable->getMessage()); + } + } + + private function reconnect(): void + { + $this->socket = null; + $this->cancelTimers(); + + if ($this->isClosed) { + return; + } + + $delay = min(2 ** $this->reconnectAttempts, self::MAX_RECONNECT_DELAY_SECONDS); + $this->reconnectAttempts++; + + ($this->log)(sprintf('Reconectando em %ds…', $delay)); + + $this->reconnectTimer = $this->loop->addTimer($delay, fn () => $this->open()); + } + + private function scheduleTokenRefresh(): void + { + if ($this->refreshTimer instanceof TimerInterface) { + $this->loop->cancelTimer($this->refreshTimer); + } + + $this->refreshTimer = $this->loop->addTimer($this->session->secondsUntilRefresh(), function (): void { + try { + $frames = $this->session->refreshToken(); + } catch (Throwable $throwable) { + ($this->log)('Falhou ao renovar o token: '.$throwable->getMessage()); + $this->socket?->close(); + + return; + } + + if ($this->socket instanceof WebSocket) { + $this->sendAll($this->socket, $frames); + } + + $this->scheduleTokenRefresh(); + }); + } + + private function cancelTimers(): void + { + foreach ([$this->refreshTimer, $this->reconnectTimer] as $timer) { + if ($timer instanceof TimerInterface) { + $this->loop->cancelTimer($timer); + } + } + + $this->refreshTimer = null; + $this->reconnectTimer = null; + } + + /** + * @param list $frames + */ + private function sendAll(WebSocket $socket, array $frames): void + { + foreach ($frames as $frame) { + $socket->send($frame); + } + } +} diff --git a/app-modules/integration-slido/src/Stream/SlidoStreamSession.php b/app-modules/integration-slido/src/Stream/SlidoStreamSession.php new file mode 100644 index 000000000..fdf3550e1 --- /dev/null +++ b/app-modules/integration-slido/src/Stream/SlidoStreamSession.php @@ -0,0 +1,189 @@ + $streamers + * @param Closure(string): void $log + */ + public function __construct( + private readonly SlidoClient $client, + private readonly QuestionFeed $feed, + private readonly SlidoEventLocation $location, + private array $streamers, + private readonly Closure $log, + ) {} + + /** + * @param list $streamers + */ + public function retarget(array $streamers): void + { + $this->streamers = $streamers; + } + + public function isSubscribed(): bool + { + return $this->isSubscribed; + } + + public function streamUrl(): string + { + $query = http_build_query([ + 'clientId' => mb_substr(md5($this->location->uuid), 0, 15), + 'slidoappVersion' => 'SlidoPresentApp/88.7.0 (web)', + 'EIO' => 4, + 'transport' => 'websocket', + ]); + + return sprintf('%s/%s/stream/v0.5/stream-sio/?%s', mb_rtrim(config()->string('integration-slido.stream_url'), '/'), $this->location->cluster, $query); + } + + public function syncQuestions(): void + { + $questions = $this->client->questions($this->location, $this->token()); + + event(new SlidoQuestionsSynced($this->streamers, $questions)); + + ($this->log)(sprintf('Sincronizou %d pergunta(s) visíveis.', count($questions))); + } + + /** + * @return list + * + * @throws SlidoSubscriptionRejected when Slido refuses the subscription; close the socket to recover + */ + public function handle(string $raw): array + { + $frame = SocketIoFrame::parse($raw); + + return match ($frame->kind) { + FrameKind::Open => [SocketIoFrame::CONNECT], + FrameKind::Connected => [$this->subscribeFrame()], + FrameKind::Ping => [SocketIoFrame::PONG], + FrameKind::Ack => $this->acknowledge($frame, $raw), + FrameKind::Event => $this->broadcast($frame), + FrameKind::ConnectError => $this->reject($raw), + FrameKind::Disconnected, FrameKind::Unknown => $this->ignore($frame, $raw), + }; + } + + /** + * @return list + */ + public function refreshToken(): array + { + try { + $this->token = $this->client->refreshParticipantToken($this->token()); + ($this->log)('Renovou o token de participante.'); + } catch (Throwable $throwable) { + ($this->log)('Refresh recusado, emitindo token novo: '.$throwable->getMessage()); + $this->token = $this->client->issueParticipantToken($this->location); + } + + return [$this->subscribeFrame()]; + } + + public function secondsUntilRefresh(): int + { + return $this->token()->secondsUntilRefresh(); + } + + private function token(): SlidoParticipantToken + { + return $this->token ??= $this->client->issueParticipantToken($this->location); + } + + private function subscribeFrame(): string + { + return SocketIoFrame::subscribe($this->token()->accessToken, $this->location->streamTarget()); + } + + /** + * @return list + */ + private function acknowledge(SocketIoFrame $frame, string $raw): array + { + if (!$frame->isSubscriptionAccepted()) { + return $this->reject($raw); + } + + $this->isSubscribed = true; + ($this->log)('Assinatura aceita pelo Slido.'); + + try { + $this->syncQuestions(); + } catch (Throwable $throwable) { + ($this->log)('Falhou ao sincronizar as perguntas: '.$throwable->getMessage()); + } + + return []; + } + + private function reject(string $raw): never + { + $this->token = null; + $this->isSubscribed = false; + + throw SlidoSubscriptionRejected::withFrame($raw); + } + + /** + * @return list + */ + private function broadcast(SocketIoFrame $frame): array + { + $question = $this->feed->questionFrom($frame); + + if ($question instanceof SlidoQuestion) { + event(new SlidoQuestionChanged($this->streamers, $question)); + + return []; + } + + $patch = $this->feed->patchFrom($frame); + + if ($patch instanceof SlidoQuestionPatch) { + event(new SlidoQuestionPatched($this->streamers, $patch)); + + return []; + } + + if (!$this->feed->isKnown($frame)) { + ($this->log)(sprintf('Evento novo do Slido: %s %s', $frame->eventName, json_encode($frame->params(), JSON_UNESCAPED_UNICODE))); + } + + return []; + } + + /** + * @return list + */ + private function ignore(SocketIoFrame $frame, string $raw): array + { + ($this->log)(sprintf('Frame %s: %s', $frame->kind->name, mb_substr($raw, 0, 200))); + + return []; + } +} diff --git a/app-modules/integration-slido/src/Stream/SlidoSubscriptionPlan.php b/app-modules/integration-slido/src/Stream/SlidoSubscriptionPlan.php new file mode 100644 index 000000000..6045b2bf0 --- /dev/null +++ b/app-modules/integration-slido/src/Stream/SlidoSubscriptionPlan.php @@ -0,0 +1,32 @@ + $opening + * @param list $closing + * @param list $keeping + */ + private function __construct( + public array $opening, + public array $closing, + public array $keeping, + ) {} + + /** + * @param list $wanted event hashes that have an audience now + * @param list $connected event hashes with an open connection + */ + public static function between(array $wanted, array $connected): self + { + return new self( + opening: array_values(array_diff($wanted, $connected)), + closing: array_values(array_diff($connected, $wanted)), + keeping: array_values(array_intersect($connected, $wanted)), + ); + } +} diff --git a/app-modules/integration-slido/src/Stream/SocketIoFrame.php b/app-modules/integration-slido/src/Stream/SocketIoFrame.php new file mode 100644 index 000000000..c38e7695a --- /dev/null +++ b/app-modules/integration-slido/src/Stream/SocketIoFrame.php @@ -0,0 +1,99 @@ + $payload + */ + public function __construct( + public FrameKind $kind, + public ?string $eventName = null, + public array $payload = [], + ) {} + + public static function parse(string $raw): self + { + return match (true) { + $raw === '2' => new self(FrameKind::Ping), + str_starts_with($raw, '40') => new self(FrameKind::Connected, payload: self::decode(mb_substr($raw, 2))), + str_starts_with($raw, '41') => new self(FrameKind::Disconnected), + str_starts_with($raw, '42') => self::event(self::withoutAckId(mb_substr($raw, 2))), + str_starts_with($raw, '43') => new self(FrameKind::Ack, payload: self::decode(self::withoutAckId(mb_substr($raw, 2)))), + str_starts_with($raw, '44') => new self(FrameKind::ConnectError, payload: self::decode(mb_substr($raw, 2))), + str_starts_with($raw, '0') => new self(FrameKind::Open, payload: self::decode(mb_substr($raw, 1))), + default => new self(FrameKind::Unknown), + }; + } + + public static function subscribe(string $accessToken, string $target): string + { + $packet = ['subscribe', ['accessToken' => $accessToken, 'targets' => [$target]]]; + + return sprintf('42%d%s', self::SUBSCRIBE_ACK_ID, json_encode($packet, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)); + } + + /** + * @return array + */ + public function params(): array + { + $params = $this->payload['params'] ?? null; + + return is_array($params) ? $params : []; + } + + public function isSubscriptionAccepted(): bool + { + $first = $this->payload[0] ?? null; + + return $this->kind === FrameKind::Ack && is_array($first) && ($first['code'] ?? null) === 200; + } + + private static function event(string $json): self + { + $packet = self::decode($json); + $name = $packet[0] ?? null; + $data = $packet[1] ?? null; + + if (!is_string($name)) { + return new self(FrameKind::Unknown); + } + + return new self(FrameKind::Event, $name, is_array($data) ? $data : []); + } + + private static function withoutAckId(string $raw): string + { + return (string) preg_replace('/^\d+/', '', $raw); + } + + /** + * @return array + */ + private static function decode(string $json): array + { + if ($json === '') { + return []; + } + + try { + $decoded = json_decode($json, associative: true, flags: JSON_THROW_ON_ERROR); + } catch (JsonException) { + return []; + } + + return is_array($decoded) ? $decoded : []; + } +} diff --git a/app-modules/integration-slido/src/Transport/Requests/AuthorizeParticipant.php b/app-modules/integration-slido/src/Transport/Requests/AuthorizeParticipant.php new file mode 100644 index 000000000..b3a7ef963 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/Requests/AuthorizeParticipant.php @@ -0,0 +1,51 @@ +eventUuid)); + } + + /** + * @return array + */ + protected function defaultQuery(): array + { + return [ + 'client_id' => $this->clientId, + 'redirect_uri' => $this->redirectUri, + 'scope' => self::SCOPE, + 'state' => 'he4rt', + 'code_challenge' => $this->codeChallenge, + 'code_challenge_method' => 'S256', + ]; + } + + /** + * @return array + */ + protected function defaultConfig(): array + { + return [RequestOptions::ALLOW_REDIRECTS => ['max' => 3]]; + } +} diff --git a/app-modules/integration-slido/src/Transport/Requests/ExchangeAuthorizationCode.php b/app-modules/integration-slido/src/Transport/Requests/ExchangeAuthorizationCode.php new file mode 100644 index 000000000..a72d6ad85 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/Requests/ExchangeAuthorizationCode.php @@ -0,0 +1,43 @@ + + */ + protected function defaultBody(): array + { + return [ + 'client_id' => $this->clientId, + 'grant_type' => 'authorization_code', + 'code' => $this->code, + 'redirect_uri' => $this->redirectUri, + 'code_verifier' => $this->codeVerifier, + ]; + } +} diff --git a/app-modules/integration-slido/src/Transport/Requests/GetEvent.php b/app-modules/integration-slido/src/Transport/Requests/GetEvent.php new file mode 100644 index 000000000..30dc76f3b --- /dev/null +++ b/app-modules/integration-slido/src/Transport/Requests/GetEvent.php @@ -0,0 +1,20 @@ +eventUuid); + } +} diff --git a/app-modules/integration-slido/src/Transport/Requests/GetEventByHash.php b/app-modules/integration-slido/src/Transport/Requests/GetEventByHash.php new file mode 100644 index 000000000..798728c86 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/Requests/GetEventByHash.php @@ -0,0 +1,28 @@ + + */ + protected function defaultQuery(): array + { + return ['hash' => $this->eventHash]; + } +} diff --git a/app-modules/integration-slido/src/Transport/Requests/GetQuestions.php b/app-modules/integration-slido/src/Transport/Requests/GetQuestions.php new file mode 100644 index 000000000..17af48815 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/Requests/GetQuestions.php @@ -0,0 +1,36 @@ +eventUuid)); + } + + /** + * @return array + */ + protected function defaultQuery(): array + { + return [ + 'eventSectionId' => $this->sectionUuid, + 'highlighted_first' => 'true', + 'path' => '/questions', + 'sort' => 'top', + ]; + } +} diff --git a/app-modules/integration-slido/src/Transport/Requests/LookupEvent.php b/app-modules/integration-slido/src/Transport/Requests/LookupEvent.php new file mode 100644 index 000000000..f95ca2df6 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/Requests/LookupEvent.php @@ -0,0 +1,20 @@ +eventHash); + } +} diff --git a/app-modules/integration-slido/src/Transport/Requests/RefreshParticipantToken.php b/app-modules/integration-slido/src/Transport/Requests/RefreshParticipantToken.php new file mode 100644 index 000000000..eb773e654 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/Requests/RefreshParticipantToken.php @@ -0,0 +1,39 @@ + + */ + protected function defaultBody(): array + { + return [ + 'client_id' => $this->clientId, + 'grant_type' => 'refresh_token', + 'refresh_token' => $this->refreshToken, + ]; + } +} diff --git a/app-modules/integration-slido/src/Transport/SlidoAuthConnector.php b/app-modules/integration-slido/src/Transport/SlidoAuthConnector.php new file mode 100644 index 000000000..e90d02868 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/SlidoAuthConnector.php @@ -0,0 +1,37 @@ +baseUrl; + } + + /** + * @return array + */ + protected function defaultHeaders(): array + { + return ['Accept' => 'application/json']; + } +} diff --git a/app-modules/integration-slido/src/Transport/SlidoClient.php b/app-modules/integration-slido/src/Transport/SlidoClient.php new file mode 100644 index 000000000..c7839ef87 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/SlidoClient.php @@ -0,0 +1,146 @@ +lookupConnector->send(new LookupEvent($eventHash))->array(); + + $uuid = $payload['eventId'] ?? null; + $cluster = $payload['clusterId'] ?? null; + + throw_unless(is_string($uuid) && is_string($cluster), SlidoResponseInvalid::missing('event lookup', 'eventId, clusterId')); + + return new SlidoEventLocation($eventHash, $uuid, $cluster); + } + + public function event(SlidoEventLocation $location): SlidoEvent + { + $payload = $this->wall($location)->send(new GetEventByHash($location->hash))->array(); + + return SlidoEvent::fromPayload($location, $payload); + } + + public function issueParticipantToken(SlidoEventLocation $location): SlidoParticipantToken + { + $codeVerifier = Str::random(64); + $codeChallenge = mb_rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, binary: true)), '+/', '-_'), '='); + + $authorization = $this->authConnector->send(new AuthorizeParticipant( + eventUuid: $location->uuid, + clientId: $this->authConnector->clientId, + redirectUri: $location->callbackUrl(), + codeChallenge: $codeChallenge, + ))->array(); + + $code = $this->authorizationCodeOf($authorization); + + $payload = $this->authConnector->send(new ExchangeAuthorizationCode( + clientId: $this->authConnector->clientId, + code: $code, + redirectUri: $location->callbackUrl(), + codeVerifier: $codeVerifier, + ))->array(); + + return SlidoParticipantToken::fromPayload($payload); + } + + public function refreshParticipantToken(SlidoParticipantToken $token): SlidoParticipantToken + { + $payload = $this->authConnector->send(new RefreshParticipantToken( + clientId: $this->authConnector->clientId, + refreshToken: $token->refreshToken, + ))->array(); + + return SlidoParticipantToken::fromPayload($payload); + } + + /** + * @return list + */ + public function questions(SlidoEventLocation $location, SlidoParticipantToken $token): array + { + $wall = $this->wall($location, $token); + $sectionUuid = $this->activeSectionUuid($wall->send(new GetEvent($location->uuid))->array()); + + if ($sectionUuid === null) { + return []; + } + + $questions = []; + + foreach ($wall->send(new GetQuestions($location->uuid, $sectionUuid))->array() as $payload) { + $question = is_array($payload) ? SlidoQuestion::tryFromPayload($payload) : null; + + if ($question instanceof SlidoQuestion && $question->isVisible) { + $questions[] = $question; + } + } + + return $questions; + } + + private function wall(SlidoEventLocation $location, ?SlidoParticipantToken $token = null): SlidoWallConnector + { + return new SlidoWallConnector($location->cluster, $token?->accessToken); + } + + /** + * @param array $authorization + */ + private function authorizationCodeOf(array $authorization): string + { + $redirectUri = $authorization['redirectUri'] ?? null; + + throw_unless(is_string($redirectUri), SlidoResponseInvalid::missing('authorization', 'redirectUri')); + + parse_str((string) parse_url($redirectUri, PHP_URL_QUERY), $query); + + $code = $query['code'] ?? null; + + throw_unless(is_string($code) && $code !== '', SlidoResponseInvalid::missing('authorization redirect', 'code')); + + return $code; + } + + /** + * @param array $event + */ + private function activeSectionUuid(array $event): ?string + { + $sections = is_array($event['sections'] ?? null) ? $event['sections'] : []; + + foreach ($sections as $section) { + $isActiveSection = is_array($section) && ($section['is_active'] ?? false) === true && is_string($section['uuid'] ?? null); + + if ($isActiveSection) { + return $section['uuid']; + } + } + + return null; + } +} diff --git a/app-modules/integration-slido/src/Transport/SlidoLookupConnector.php b/app-modules/integration-slido/src/Transport/SlidoLookupConnector.php new file mode 100644 index 000000000..a7e9cb521 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/SlidoLookupConnector.php @@ -0,0 +1,34 @@ +baseUrl; + } + + /** + * @return array + */ + protected function defaultHeaders(): array + { + return ['Accept' => 'application/json']; + } +} diff --git a/app-modules/integration-slido/src/Transport/SlidoWallConnector.php b/app-modules/integration-slido/src/Transport/SlidoWallConnector.php new file mode 100644 index 000000000..535226dc6 --- /dev/null +++ b/app-modules/integration-slido/src/Transport/SlidoWallConnector.php @@ -0,0 +1,42 @@ +accessToken !== null) { + $this->authenticate(new TokenAuthenticator($this->accessToken)); + } + } + + public function resolveBaseUrl(): string + { + return sprintf('%s/%s/api/v0.5', mb_rtrim(config()->string('integration-slido.wall_url'), '/'), $this->cluster); + } + + /** + * @return array + */ + protected function defaultHeaders(): array + { + return ['Accept' => 'application/json']; + } +} diff --git a/app-modules/integration-slido/tests/Feature/.gitkeep b/app-modules/integration-slido/tests/Feature/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/app-modules/integration-slido/tests/Feature/SlidoAudienceTest.php b/app-modules/integration-slido/tests/Feature/SlidoAudienceTest.php new file mode 100644 index 000000000..7d2789f5b --- /dev/null +++ b/app-modules/integration-slido/tests/Feature/SlidoAudienceTest.php @@ -0,0 +1,68 @@ + $openOverlays overlay count per streamer id; missing ids count as one + */ +function fakeOpenOverlays(array $openOverlays): void +{ + app()->instance(OverlayConnections::class, new readonly class($openOverlays) implements OverlayConnections + { + public function __construct(private array $openOverlays) {} + + public function count(Streamer $streamer): ?int + { + return array_key_exists($streamer->id, $this->openOverlays) ? $this->openOverlays[$streamer->id] : 1; + } + }); +} + +function pubStreamer(?string $eventHash, bool $isActive = true): Streamer +{ + $factory = $isActive ? Streamer::factory() : Streamer::factory()->disabled(); + + return $factory->create(['settings' => (new StreamerSettings)->withScene(new PubSettings($eventHash))]); +} + +function audienceIds(): array +{ + return array_map( + fn (array $streamers): array => array_map(fn (Streamer $streamer): string => $streamer->id, $streamers), + resolve(SlidoAudience::class)->current(), + ); +} + +test('junta no mesmo evento os streamers com a overlay He4rt Pub aberta', function (): void { + $first = pubStreamer('jC9L7Lu93Vw3ssNhB92Pvb'); + $second = pubStreamer('jC9L7Lu93Vw3ssNhB92Pvb'); + $other = pubStreamer('Outro5Evento6Hash'); + fakeOpenOverlays([]); + + expect(audienceIds())->toEqualCanonicalizing([ + 'jC9L7Lu93Vw3ssNhB92Pvb' => [$first->id, $second->id], + 'Outro5Evento6Hash' => [$other->id], + ]); +}); + +test('deixa de fora quem fechou a overlay, está desativado ou não configurou o Slido', function (): void { + $closed = pubStreamer('jC9L7Lu93Vw3ssNhB92Pvb'); + pubStreamer('jC9L7Lu93Vw3ssNhB92Pvb', isActive: false); + pubStreamer(eventHash: null); + fakeOpenOverlays([$closed->id => 0]); + + expect(audienceIds())->toBeEmpty(); +}); + +test('mantém o streamer quando o Reverb não responde a contagem de overlays', function (): void { + $streamer = pubStreamer('jC9L7Lu93Vw3ssNhB92Pvb'); + fakeOpenOverlays([$streamer->id => null]); + + expect(audienceIds())->toBe(['jC9L7Lu93Vw3ssNhB92Pvb' => [$streamer->id]]); +}); diff --git a/app-modules/integration-slido/tests/Feature/SlidoClientTest.php b/app-modules/integration-slido/tests/Feature/SlidoClientTest.php new file mode 100644 index 000000000..ca1692753 --- /dev/null +++ b/app-modules/integration-slido/tests/Feature/SlidoClientTest.php @@ -0,0 +1,189 @@ + + */ +function slidoTokenPayload(string $suffix = 'a'): array +{ + return [ + 'access_token' => 'access-'.$suffix, + 'refresh_token' => 'refresh-'.$suffix, + 'expires_in' => 600, + 'refresh_token_expires_in' => 432_000, + 'token_type' => 'Bearer', + ]; +} + +function slidoQuestionPayload(array $overrides = []): array +{ + return array_replace([ + 'event_question_id' => 122_180_089, + 'type' => 'Question', + 'text' => 'Como vocês organizam a He4rt Pub?', + 'author' => ['name' => 'danielhe4rt'], + 'is_anonymous' => false, + 'is_public' => true, + 'is_answered' => false, + 'is_highlighted' => false, + 'score' => 3, + 'date_created' => '2026-10-31T18:23:13.000Z', + 'date_deleted' => null, + 'pinned_replies' => [], + ], $overrides); +} + +afterEach(function (): void { + MockClient::destroyGlobal(); +}); + +test('resolve o hash do evento para o cluster e o uuid', function (): void { + MockClient::global([ + LookupEvent::class => MockResponse::make(['clusterId' => 'eu1', 'eventId' => SLIDO_UUID]), + ]); + + $location = resolve(SlidoClient::class)->locate(SLIDO_HASH); + + expect($location->cluster)->toBe('eu1') + ->and($location->uuid)->toBe(SLIDO_UUID) + ->and($location->streamTarget())->toBe('slido/events/'.SLIDO_UUID.'/'); +}); + +test('lê nome, código e link do participante do evento público', function (): void { + MockClient::global([ + GetEventByHash::class => MockResponse::make([ + 'name' => 'He4rt Pub #12', + 'code' => 9_410_834, + 'is_active' => true, + 'url' => ['app' => 'https://app.sli.do/event/'.SLIDO_HASH], + ]), + ]); + + $event = resolve(SlidoClient::class)->event(slidoLocation()); + + expect($event->toArray())->toBe([ + 'hash' => SLIDO_HASH, + 'name' => 'He4rt Pub #12', + 'code' => '9410834', + 'isActive' => true, + 'participantUrl' => 'https://app.sli.do/event/'.SLIDO_HASH, + ]); +}); + +test('emite token de participante com PKCE sem cookie', function (): void { + $mockClient = MockClient::global([ + AuthorizeParticipant::class => MockResponse::make([ + 'redirectUri' => 'https://wall.sli.do/event/'.SLIDO_HASH.'/oauth-callback?cluster_id=eu1&code=auth-code&state=he4rt', + ]), + ExchangeAuthorizationCode::class => MockResponse::make(slidoTokenPayload()), + ]); + + $token = resolve(SlidoClient::class)->issueParticipantToken(slidoLocation()); + + expect($token->accessToken)->toBe('access-a') + ->and($token->refreshToken)->toBe('refresh-a') + ->and($token->needsRefresh())->toBeFalse(); + + $authorizeQuery = $mockClient->findResponseByRequest(AuthorizeParticipant::class)?->getPendingRequest()->query()->all() ?? []; + $exchangeBody = $mockClient->findResponseByRequest(ExchangeAuthorizationCode::class)?->getPendingRequest()->body()?->all() ?? []; + $expectedChallenge = mb_rtrim(strtr(base64_encode(hash('sha256', (string) $exchangeBody['code_verifier'], binary: true)), '+/', '-_'), '='); + + expect($authorizeQuery)->toMatchArray([ + 'scope' => AuthorizeParticipant::SCOPE, + 'code_challenge_method' => 'S256', + 'code_challenge' => $expectedChallenge, + 'redirect_uri' => 'https://wall.sli.do/event/'.SLIDO_HASH.'/oauth-callback', + ])->and($exchangeBody)->toMatchArray([ + 'code' => 'auth-code', + 'grant_type' => 'authorization_code', + ]); +}); + +test('falha com mensagem clara quando o slido não devolve o code', function (): void { + MockClient::global([ + AuthorizeParticipant::class => MockResponse::make([ + 'redirectUri' => 'https://wall.sli.do/event/'.SLIDO_HASH.'/oauth-callback?error=login_required', + ]), + ]); + + resolve(SlidoClient::class)->issueParticipantToken(slidoLocation()); +})->throws(SlidoResponseInvalid::class, 'authorization redirect'); + +test('renova o token usando o refresh token que rotaciona', function (): void { + MockClient::global([ + RefreshParticipantToken::class => MockResponse::make(slidoTokenPayload('b')), + ]); + + $client = resolve(SlidoClient::class); + $token = SlidoParticipantToken::fromPayload(slidoTokenPayload()); + + $refreshed = $client->refreshParticipantToken($token); + + expect($refreshed->accessToken)->toBe('access-b') + ->and($refreshed->refreshToken)->toBe('refresh-b'); +}); + +test('lista só as perguntas visíveis da seção ativa, com as respostas fixadas', function (): void { + $mockClient = MockClient::global([ + GetEvent::class => MockResponse::make([ + 'sections' => [ + ['uuid' => 'old-section', 'is_active' => false], + ['uuid' => SLIDO_SECTION, 'is_active' => true], + ], + ]), + GetQuestions::class => MockResponse::make([ + slidoQuestionPayload([ + 'event_question_id' => 1, + 'is_anonymous' => true, + 'author' => [], + 'is_highlighted' => true, + 'pinned_replies' => [[ + 'event_question_id' => 9, + 'type' => 'Comment', + 'text' => 'Toda sexta, às 20h', + 'author' => ['name' => 'Moderator'], + 'attrs' => ['is_admin' => true], + ]], + ]), + slidoQuestionPayload(['event_question_id' => 2, 'date_deleted' => '2026-10-31T18:30:00.000Z']), + slidoQuestionPayload(['event_question_id' => 3, 'is_public' => false]), + ]), + ]); + + $questions = resolve(SlidoClient::class)->questions(slidoLocation(), SlidoParticipantToken::fromPayload(slidoTokenPayload())); + + expect($questions)->toHaveCount(1) + ->and($questions[0]->toArray())->toMatchArray([ + 'id' => 1, + 'authorName' => null, + 'isHighlighted' => true, + 'replies' => [['id' => 9, 'text' => 'Toda sexta, às 20h', 'authorName' => 'Moderator', 'isFromModerator' => true]], + ]); + + $mockClient->assertSent(fn (GetQuestions $request, mixed $response): bool => $response->getPendingRequest()->query()->get('eventSectionId') === SLIDO_SECTION + && $response->getPendingRequest()->headers()->get('Authorization') === 'Bearer access-a'); +}); diff --git a/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php new file mode 100644 index 000000000..66ae6999e --- /dev/null +++ b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php @@ -0,0 +1,247 @@ + 'access-'.$suffix, + 'refresh_token' => 'refresh-'.$suffix, + 'expires_in' => 600, + ]); +} + +function streamSession(Streamer $streamer, array &$logs = []): SlidoStreamSession +{ + return new SlidoStreamSession( + client: resolve(SlidoClient::class), + feed: new QuestionFeed, + location: new SlidoEventLocation('jC9L7Lu93Vw3ssNhB92Pvb', STREAM_EVENT_UUID, 'eu1'), + streamers: [$streamer], + log: function (string $line) use (&$logs): void { + $logs[] = $line; + }, + ); +} + +function fakeSlido(array $overrides = []): void +{ + MockClient::destroyGlobal(); + MockClient::global([ + AuthorizeParticipant::class => MockResponse::make(['redirectUri' => 'https://wall.sli.do/event/x/oauth-callback?code=c1']), + ExchangeAuthorizationCode::class => streamTokenResponse('a'), + RefreshParticipantToken::class => streamTokenResponse('b'), + ...$overrides, + ]); +} + +function questionUpdateFrame(array $params): string +{ + return '42'.json_encode(['slido.event.question.update', ['target' => 'slido/events/'.STREAM_EVENT_UUID.'/', 'params' => $params]]); +} + +beforeEach(function (): void { + Event::fake([SlidoQuestionChanged::class, SlidoQuestionPatched::class, SlidoQuestionsSynced::class]); + + fakeSlido(); +}); + +afterEach(function (): void { + MockClient::destroyGlobal(); +}); + +test('faz o handshake e assina o evento com o token de participante', function (): void { + $session = streamSession(Streamer::factory()->create()); + + expect($session->handle('0{"sid":"s","pingInterval":25000}'))->toBe(['40']) + ->and($session->handle('40{"sid":"s2"}'))->toBe(['420["subscribe",{"accessToken":"access-a","targets":["slido/events/'.STREAM_EVENT_UUID.'/"]}]']) + ->and($session->handle('2'))->toBe(['3']); +}); + +function highlightedQuestionFrame(): string +{ + return questionUpdateFrame([ + 'event_question_id' => 122_180_089, + 'type' => 'Question', + 'text' => 'eaeaeaeaeaeaea', + 'author' => ['name' => 'danielhe4rt'], + 'is_anonymous' => false, + 'is_public' => true, + 'is_highlighted' => true, + 'is_answered' => false, + 'date_created' => '2026-10-31T18:23:13.000Z', + 'pinned_replies' => [], + ]); +} + +test('envia a pergunta atualizada para o canal da overlay do streamer', function (): void { + $streamer = Streamer::factory()->create(); + $session = streamSession($streamer); + + $session->handle(highlightedQuestionFrame()); + + Event::assertDispatched(fn (SlidoQuestionChanged $event): bool => $event->question->id === 122_180_089 + && $event->question->isHighlighted + && array_map(fn (PrivateChannel $channel): string => $channel->name, $event->broadcastOn()) === ['private-'.$streamer->overlayChannel()]); +}); + +test('passa a enviar para as overlays que abriram depois de conectar', function (): void { + $first = Streamer::factory()->create(); + $second = Streamer::factory()->create(); + $session = streamSession($first); + + $session->retarget([$first, $second]); + $session->handle(highlightedQuestionFrame()); + + Event::assertDispatched(fn (SlidoQuestionChanged $event): bool => array_map(fn (PrivateChannel $channel): string => $channel->name, $event->broadcastOn()) === [ + 'private-'.$first->overlayChannel(), + 'private-'.$second->overlayChannel(), + ]); +}); + +test('envia só o que mudou quando o Slido manda um patch ou uma ação do moderador', function (string $raw, array $changes): void { + $session = streamSession(Streamer::factory()->create()); + + $session->handle($raw); + + Event::assertDispatched(fn (SlidoQuestionPatched $event): bool => $event->patch->toArray() === ['id' => 122_180_089, 'changes' => $changes]); + Event::assertNotDispatched(SlidoQuestionChanged::class); +})->with([ + 'voto' => ['42["slido.event.question.patch",{"params":{"score":2,"event_question_id":122180089}}]', ['score' => 2]], + 'destaque' => ['42["slido.event.question.admin.action",{"params":{"is_highlighted":true,"is_answered":false,"event_question_id":122180089}}]', ['isHighlighted' => true, 'isAnswered' => false]], +]); + +test('ignora o comentário solto porque o update da pergunta pai traz a resposta', function (): void { + $session = streamSession(Streamer::factory()->create()); + + $session->handle('42'.json_encode(['newQuestion', ['params' => [ + 'event_question_id' => 122_180_096, + 'type' => 'Comment', + 'parent' => ['id' => '122180088', 'type' => 'Question'], + 'text' => 'eaeaea', + ]]])); + + Event::assertNotDispatched(SlidoQuestionChanged::class); +}); + +test('registra no log um evento do Slido que ainda não foi mapeado', function (): void { + $logs = []; + $session = streamSession(Streamer::factory()->create(), $logs); + + $session->handle('42["slido.event.question.delete",{"params":{"event_question_id":5}}]'); + $session->handle('42["slido.event.analytics.update",{"params":{}}]'); + + expect($logs)->toHaveCount(1) + ->and($logs[0])->toContain('slido.event.question.delete'); +}); + +test('sincroniza as perguntas visíveis ao conectar', function (): void { + fakeSlido([ + GetEvent::class => MockResponse::make(['sections' => [['uuid' => 'section-1', 'is_active' => true]]]), + GetQuestions::class => MockResponse::make([ + ['event_question_id' => 1, 'type' => 'Question', 'text' => 'Primeira', 'is_public' => true], + ['event_question_id' => 2, 'type' => 'Question', 'text' => 'Apagada', 'is_public' => true, 'date_deleted' => '2026-10-31T18:30:00.000Z'], + ]), + ]); + + streamSession(Streamer::factory()->create())->syncQuestions(); + + Event::assertDispatched(fn (SlidoQuestionsSynced $event): bool => count($event->questions) === 1 + && $event->questions[0]->text === 'Primeira'); +}); + +test('renova o token e assina de novo com o token novo', function (): void { + $session = streamSession(Streamer::factory()->create()); + $session->handle('40{"sid":"s"}'); + + expect($session->refreshToken())->toBe(['420["subscribe",{"accessToken":"access-b","targets":["slido/events/'.STREAM_EVENT_UUID.'/"]}]']); +}); + +test('emite um token novo quando o refresh é recusado', function (): void { + fakeSlido([ + RefreshParticipantToken::class => MockResponse::make(['error' => 'invalid_grant'], 400), + ]); + + $logs = []; + $session = streamSession(Streamer::factory()->create(), $logs); + $session->handle('40{"sid":"s"}'); + + expect($session->refreshToken()[0])->toContain('"accessToken":"access-a"') + ->and($logs[0])->toContain('Refresh recusado'); +}); + +test('sincroniza as perguntas só depois que o Slido aceita a assinatura', function (): void { + fakeSlido([ + GetEvent::class => MockResponse::make(['sections' => [['uuid' => 'section-1', 'is_active' => true]]]), + GetQuestions::class => MockResponse::make([['event_question_id' => 1, 'type' => 'Question', 'text' => 'Primeira', 'is_public' => true]]), + ]); + $session = streamSession(Streamer::factory()->create()); + + $session->handle('40{"sid":"s"}'); + Event::assertNotDispatched(SlidoQuestionsSynced::class); + + $session->handle('430[{"code":200,"message":"Subscribed"}]'); + Event::assertDispatched(SlidoQuestionsSynced::class); +}); + +test('a assinatura recusada descarta o token para a reconexão emitir outro', function (string $raw): void { + $session = streamSession(Streamer::factory()->create()); + $session->handle('40{"sid":"s"}'); + + expect(fn () => $session->handle($raw))->toThrow(SlidoSubscriptionRejected::class); + + MockClient::getGlobal()?->assertSentCount(2); + $session->handle('40{"sid":"s2"}'); + MockClient::getGlobal()?->assertSentCount(4); +})->with([ + 'ack sem code 200' => ['430[{"code":401,"message":"Unauthorized"}]'], + 'erro de conexão do socket.io' => ['44{"message":"unauthorized"}'], +]); + +test('a pergunta com data inválida entra com a hora atual', function (): void { + $session = streamSession(Streamer::factory()->create()); + + $session->handle(questionUpdateFrame([ + 'event_question_id' => 7, + 'type' => 'Question', + 'text' => 'Data quebrada', + 'is_public' => true, + 'date_created' => 'ontem à noite', + ])); + + Event::assertDispatched(fn (SlidoQuestionChanged $event): bool => $event->question->id === 7); +}); + +test('a sessão só conta como assinada depois do ack aceito', function (): void { + $session = streamSession(Streamer::factory()->create()); + $session->handle('40{"sid":"s"}'); + + expect($session->isSubscribed())->toBeFalse(); + + $session->handle('430[{"code":200,"message":"Subscribed"}]'); + expect($session->isSubscribed())->toBeTrue(); + + expect(fn () => $session->handle('44{"message":"unauthorized"}'))->toThrow(SlidoSubscriptionRejected::class); + expect($session->isSubscribed())->toBeFalse(); +}); diff --git a/app-modules/integration-slido/tests/Unit/.gitkeep b/app-modules/integration-slido/tests/Unit/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/app-modules/integration-slido/tests/Unit/SlidoEventHashTest.php b/app-modules/integration-slido/tests/Unit/SlidoEventHashTest.php new file mode 100644 index 000000000..723fca611 --- /dev/null +++ b/app-modules/integration-slido/tests/Unit/SlidoEventHashTest.php @@ -0,0 +1,17 @@ +toBe($expected); +})->with([ + 'link do participante' => ['https://app.sli.do/event/jC9L7Lu93Vw3ssNhB92Pvb', 'jC9L7Lu93Vw3ssNhB92Pvb'], + 'link do wall com query' => ['https://wall.sli.do/event/jC9L7Lu93Vw3ssNhB92Pvb?section=abc', 'jC9L7Lu93Vw3ssNhB92Pvb'], + 'link do admin com caminho' => ['https://admin.sli.do/event/jC9L7Lu93Vw3ssNhB92Pvb/questions', 'jC9L7Lu93Vw3ssNhB92Pvb'], + 'hash com espaços' => [' jC9L7Lu93Vw3ssNhB92Pvb ', 'jC9L7Lu93Vw3ssNhB92Pvb'], + 'outro domínio' => ['https://example.com/event/jC9L7Lu93Vw3ssNhB92Pvb', null], + 'http sem tls' => ['http://app.sli.do/event/jC9L7Lu93Vw3ssNhB92Pvb', null], + 'texto qualquer' => ['he4rt pub', null], +]); diff --git a/app-modules/integration-slido/tests/Unit/SlidoSubscriptionPlanTest.php b/app-modules/integration-slido/tests/Unit/SlidoSubscriptionPlanTest.php new file mode 100644 index 000000000..50adbe457 --- /dev/null +++ b/app-modules/integration-slido/tests/Unit/SlidoSubscriptionPlanTest.php @@ -0,0 +1,28 @@ +opening)->toBe(['pub-5']) + ->and($plan->closing)->toBeEmpty() + ->and($plan->keeping)->toBeEmpty(); +}); + +test('desconecta do evento que ficou sem overlay aberta', function (): void { + $plan = SlidoSubscriptionPlan::between(wanted: [], connected: ['pub-5']); + + expect($plan->opening)->toBeEmpty() + ->and($plan->closing)->toBe(['pub-5']); +}); + +test('troca de evento quando o link muda no painel e mantém o que continua igual', function (): void { + $plan = SlidoSubscriptionPlan::between(wanted: ['pub-6', 'meetup'], connected: ['pub-5', 'meetup']); + + expect($plan->opening)->toBe(['pub-6']) + ->and($plan->closing)->toBe(['pub-5']) + ->and($plan->keeping)->toBe(['meetup']); +}); diff --git a/app-modules/integration-slido/tests/Unit/SocketIoFrameTest.php b/app-modules/integration-slido/tests/Unit/SocketIoFrameTest.php new file mode 100644 index 000000000..29066d596 --- /dev/null +++ b/app-modules/integration-slido/tests/Unit/SocketIoFrameTest.php @@ -0,0 +1,44 @@ +kind)->toBe($expected); +})->with([ + 'open' => ['0{"sid":"abc","pingInterval":25000,"pingTimeout":20000}', FrameKind::Open], + 'connected' => ['40{"sid":"def"}', FrameKind::Connected], + 'ping' => ['2', FrameKind::Ping], + 'ack' => ['430[{"code":200,"message":"Subscribed"}]', FrameKind::Ack], + 'event' => ['42["newQuestion",{"params":{}}]', FrameKind::Event], + 'connect error' => ['44{"message":"unauthorized"}', FrameKind::ConnectError], + 'disconnect' => ['41', FrameKind::Disconnected], + 'json quebrado' => ['42[not-json', FrameKind::Unknown], +]); + +test('lê o nome e os params de um evento', function (): void { + $frame = SocketIoFrame::parse('42["slido.event.question.update",{"target":"slido/events/x/","params":{"event_question_id":7}}]'); + + expect($frame->eventName)->toBe('slido.event.question.update') + ->and($frame->params())->toBe(['event_question_id' => 7]); +}); + +test('aceita a assinatura só quando o ack tem code 200', function (): void { + expect(SocketIoFrame::parse('430[{"code":200,"message":"Subscribed"}]')->isSubscriptionAccepted())->toBeTrue() + ->and(SocketIoFrame::parse('430[{"code":401,"message":"Unauthorized"}]')->isSubscriptionAccepted())->toBeFalse(); +}); + +test('monta o frame de subscribe com ack id 0', function (): void { + expect(SocketIoFrame::subscribe('token-1', 'slido/events/abc/')) + ->toBe('420["subscribe",{"accessToken":"token-1","targets":["slido/events/abc/"]}]'); +}); + +test('lê o evento mesmo quando o servidor manda um id de ack antes do pacote', function (): void { + $frame = SocketIoFrame::parse('4212["newQuestion",{"params":{"event_question_id":5}}]'); + + expect($frame->kind)->toBe(FrameKind::Event) + ->and($frame->eventName)->toBe('newQuestion') + ->and($frame->params())->toBe(['event_question_id' => 5]); +}); diff --git a/app-modules/integration-twitch/src/OAuth/TwitchOAuthClient.php b/app-modules/integration-twitch/src/OAuth/TwitchOAuthClient.php index 3fe392b77..9d635c7d8 100644 --- a/app-modules/integration-twitch/src/OAuth/TwitchOAuthClient.php +++ b/app-modules/integration-twitch/src/OAuth/TwitchOAuthClient.php @@ -7,6 +7,7 @@ use App\Contracts\OAuthClientContract; use He4rt\Identity\Auth\DTOs\OAuthAccessDTO; use He4rt\Identity\Auth\DTOs\OAuthStateDTO; +use He4rt\Identity\Auth\Enums\OAuthIntent; use He4rt\Identity\Auth\Exceptions\OAuthFlowException; use He4rt\IntegrationTwitch\OAuth\DTO\TwitchOAuthAccessDTO; use He4rt\IntegrationTwitch\OAuth\DTO\TwitchOAuthDTO; @@ -31,14 +32,15 @@ public function redirectUrl(?OAuthStateDTO $state = null): string TwitchStreamerFeature::fromValues($state->features ?? []), ); - $callbackUrl = $this->callbackUrl(); + $isLinkingToSignedInUser = $state?->intent === OAuthIntent::Link; return 'https://id.twitch.tv/oauth2/authorize?'.http_build_query([ 'client_id' => $this->oauthConnector->clientId, - 'redirect_uri' => $callbackUrl, + 'redirect_uri' => $this->callbackUrl(), 'response_type' => 'code', 'scope' => implode(' ', $scopes), 'state' => (string) $state, + ...($isLinkingToSignedInUser ? ['force_verify' => 'true'] : []), ]); } diff --git a/app-modules/integration-twitch/tests/Feature/TwitchScopesTest.php b/app-modules/integration-twitch/tests/Feature/TwitchScopesTest.php index 631f7217b..3f7715c64 100644 --- a/app-modules/integration-twitch/tests/Feature/TwitchScopesTest.php +++ b/app-modules/integration-twitch/tests/Feature/TwitchScopesTest.php @@ -52,6 +52,21 @@ expect($query['scope'])->toBe('user:read:email moderator:read:followers channel:read:subscriptions bits:read'); }); +test('vincular uma conta pede para a Twitch confirmar com qual conta entrar', function (OAuthIntent $intent, bool $forcesAccountChoice): void { + $redirectUrl = resolve(TwitchOAuthClient::class)->redirectUrl(new OAuthStateDTO( + intent: $intent, + provider: IdentityProvider::Twitch, + panel: 'app', + )); + + parse_str((string) parse_url($redirectUrl, PHP_URL_QUERY), $query); + + expect(($query['force_verify'] ?? null) === 'true')->toBe($forcesAccountChoice); +})->with([ + 'vínculo pelo painel' => [OAuthIntent::Link, true], + 'login' => [OAuthIntent::Login, false], +]); + test('o card mostra os mesmos escopos que o redirect pede', function (): void { $streamer = User::factory()->streamer()->create(); diff --git a/app-modules/panel-app/resources/views/pages/streaming/dashboard.blade.php b/app-modules/panel-app/resources/views/pages/streaming/dashboard.blade.php index e3a76ae3b..f775e9d78 100644 --- a/app-modules/panel-app/resources/views/pages/streaming/dashboard.blade.php +++ b/app-modules/panel-app/resources/views/pages/streaming/dashboard.blade.php @@ -250,10 +250,16 @@ class="text-sm text-gray-700 dark:text-gray-200"

{{ '@' . ($source->identity->metadata['username'] ?? $source->identity->external_account_id) }}

-

- {{ $source->enabled ? 'Ligada' : 'Desligada' }} · - {{ $source->chat_reader ? 'chat ' . \Illuminate\Support\Str::lcfirst($source->chat_reader->getLabel()) : 'sem chat na overlay' }} -

+ @if ($this->sourceMissingScopes($source) !== []) +

+ Sem permissão na Twitch: não recebe chat nem alertas +

+ @else +

+ {{ $source->enabled ? 'Ligada' : 'Desligada' }} · + {{ $source->chat_reader ? 'chat ' . \Illuminate\Support\Str::lcfirst($source->chat_reader->getLabel()) : 'sem chat na overlay' }} +

+ @endif chatReaderAction)(['source' => $source->id]) : null, ($this->toggleSourceAction)(['source' => $source->id]), + ($this->reconnectSourceAction)(['source' => $source->id]), ])" icon="heroicon-m-ellipsis-vertical" color="gray" diff --git a/app-modules/panel-app/resources/views/pages/streaming/overlays.blade.php b/app-modules/panel-app/resources/views/pages/streaming/overlays.blade.php index ce1b1ca41..95e2c08ec 100644 --- a/app-modules/panel-app/resources/views/pages/streaming/overlays.blade.php +++ b/app-modules/panel-app/resources/views/pages/streaming/overlays.blade.php @@ -127,9 +127,13 @@ class="absolute right-3 bottom-3 rounded bg-black/40 px-1.5 py-0.5 font-mono tex

- @if ($item['settingsAction']) - {{ $this->{$item['settingsAction']} }} - @endif +
+ @if ($item['settingsAction']) + {{ $this->{$item['settingsAction']} }} + @endif + + {{ ($this->sceneSourcesAction)(['scene' => $item['scene']->value]) }} +
label(fn (array $arguments): string => sprintf('Reconectar como @%s', $this->ownedSource($arguments)?->identity->metadata['username'] ?? 'conta')) + ->icon(Heroicon::OutlinedArrowPath) + ->color('warning') + ->size('sm') + ->url(fn (array $arguments): string => $this->twitchAuthorizationUrl($this->ownedSource($arguments)?->chat_reader)) + ->visible(fn (array $arguments): bool => $this->sourceMissingScopes($this->ownedSource($arguments)) !== []); + } + + /** + * @return array + */ + public function sourceMissingScopes(?StreamerSource $source): array + { + $isTwitchSource = $source?->identity->provider === IdentityProvider::Twitch; + + if (!$source instanceof StreamerSource || !$isTwitchSource) { + return []; + } + + return $source->identity->missingScopes($this->requiredTwitchScopes($source->chat_reader)); + } + public function chatReaderAction(): Action { return Action::make('chatReader') diff --git a/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php index 71de36976..f354de37b 100644 --- a/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php +++ b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php @@ -5,7 +5,9 @@ namespace He4rt\PanelApp\Clusters\Streaming\Pages; use BackedEnum; +use Closure; use Filament\Actions\Action; +use Filament\Forms\Components\CheckboxList; use Filament\Forms\Components\Radio; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; @@ -15,6 +17,7 @@ use Filament\Schemas\Components\Grid; use Filament\Support\Icons\Heroicon; use He4rt\Identity\User\Models\User; +use He4rt\IntegrationSlido\Data\SlidoEventHash; use He4rt\PanelApp\Clusters\Streaming\StreamingCluster; use He4rt\Streaming\Enums\ChatAlignment; use He4rt\Streaming\Enums\ChatDirection; @@ -28,13 +31,20 @@ use He4rt\Streaming\Streamer\Actions\UpdateStreamerSettings; use He4rt\Streaming\Streamer\Data\AlertSettings; use He4rt\Streaming\Streamer\Data\ChatSettings; +use He4rt\Streaming\Streamer\Data\PubSettings; use He4rt\Streaming\Streamer\Data\StartingSoonSettings; use He4rt\Streaming\Streamer\Data\VoiceSettings; use He4rt\Streaming\Streamer\Models\Streamer; +use He4rt\Streaming\Streamer\Models\StreamerSource; use He4rt\Streaming\StreamEvent\Actions\TriggerTestAlert; +use Illuminate\Database\Eloquent\Collection; +use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; use Livewire\Attributes\Renderless; +/** + * @property-read Collection $overlaySources + */ class StreamOverlaysPage extends Page { private const int SCENE_WIDTH = 1_920; @@ -211,6 +221,99 @@ public function chatSettingsAction(): Action }); } + public function pubSettingsAction(): Action + { + return Action::make('pubSettings') + ->label('Configurar') + ->icon(Heroicon::OutlinedAdjustmentsHorizontal) + ->color('gray') + ->size('sm') + ->modalHeading(OverlayScene::Pub->getLabel()) + ->modalDescription('Cole o link do evento do Slido da edição. A overlay mostra as perguntas e o QR Code desse evento. Deixe vazio para tirar o Slido da overlay.') + ->modalSubmitActionLabel('Salvar') + ->fillForm(fn (): array => ['slido_event' => $this->currentStreamer()->settings->pub->slidoEventHash]) + ->schema([ + TextInput::make('slido_event') + ->label('Evento do Slido') + ->placeholder('https://app.sli.do/event/jC9L7Lu93Vw3ssNhB92Pvb') + ->helperText('Link do participante, do wall ou só o código do evento.') + ->rule(fn (): Closure => function (string $attribute, mixed $value, Closure $fail): void { + $isFilledButUnknown = is_string($value) && $value !== '' && SlidoEventHash::fromInput($value) === null; + + if ($isFilledButUnknown) { + $fail('Não reconheci esse link do Slido.'); + } + }), + ]) + ->action(function (array $data, UpdateStreamerSettings $updateSettings): void { + $streamer = $this->currentStreamer(); + $slidoEvent = $data['slido_event'] ?? null; + $eventHash = is_string($slidoEvent) && $slidoEvent !== '' ? SlidoEventHash::fromInput($slidoEvent) : null; + + $updateSettings->handle($streamer, $streamer->settings->withScene(new PubSettings($eventHash))); + + Notification::make() + ->title('He4rt Pub atualizada') + ->body($eventHash === null ? 'A overlay deixa de mostrar o Slido.' : 'A overlay passa a mostrar as perguntas desse evento em alguns segundos.') + ->success() + ->send(); + }); + } + + public function sceneSourcesAction(): Action + { + return Action::make('sceneSources') + ->label(fn (array $arguments): string => $this->sceneSourcesLabel($this->sceneOf($arguments))) + ->icon(Heroicon::OutlinedSignal) + ->color('gray') + ->size('sm') + ->modalHeading(fn (array $arguments): string => sprintf('Fontes: %s', $this->sceneOf($arguments)?->getLabel() ?? 'cena')) + ->modalDescription('De quais canais esta cena recebe chat e alertas. Sem nenhum marcado, ela usa todas as fontes ligadas. A overlay aberta no OBS recarrega sozinha.') + ->modalSubmitActionLabel('Salvar') + ->fillForm(fn (array $arguments): array => [ + 'sources' => $this->sceneOf($arguments) instanceof OverlayScene + ? $this->currentStreamer()->settings->sceneSources->chosenFor($this->sceneOf($arguments)) + : [], + ]) + ->schema([ + CheckboxList::make('sources') + ->hiddenLabel() + ->options(fn (): array => $this->overlaySources->mapWithKeys(fn (StreamerSource $source): array => [$source->id => $this->sourceHandle($source)])->all()) + ->descriptions(fn (): array => $this->overlaySources->mapWithKeys(fn (StreamerSource $source): array => [ + $source->id => sprintf('%s · %s', $source->identity->provider->getLabel(), $source->enabled ? 'ligada' : 'desligada no Painel'), + ])->all()), + ]) + ->visible(fn (): bool => $this->overlaySources->count() > 1) + ->action(function (array $arguments, array $data, UpdateStreamerSettings $updateSettings): void { + $scene = $this->sceneOf($arguments); + + if (!$scene instanceof OverlayScene) { + return; + } + + $submitted = is_array($data['sources'] ?? null) ? $data['sources'] : []; + $ownedSourceIds = array_values(array_intersect($submitted, $this->overlaySourceIds())); + $streamer = $this->currentStreamer(); + + $updateSettings->handle($streamer, $streamer->settings->withSceneSources($scene, $ownedSourceIds)); + + Notification::make() + ->title('Fontes da cena atualizadas') + ->body($ownedSourceIds === [] ? 'A cena volta a usar todas as fontes ligadas.' : null) + ->success() + ->send(); + }); + } + + /** + * @return Collection + */ + #[Computed] + public function overlaySources(): Collection + { + return $this->currentStreamer()->sources()->with('identity')->oldest()->get(); + } + public function testAlertAction(): Action { return Action::make('testAlert') @@ -314,6 +417,7 @@ protected function getViewData(): array OverlayScene::StartingSoon => 'startingSoonSettingsAction', OverlayScene::Voice => 'voiceSettingsAction', OverlayScene::Chat => 'chatSettingsAction', + OverlayScene::Pub => 'pubSettingsAction', OverlayScene::Coworking => null, }, 'size' => $scene === OverlayScene::Chat ? 'qualquer tamanho' : '1920 × 1080', @@ -348,6 +452,49 @@ private function alertTypeOf(array $arguments): ?StreamEventType return is_string($type) ? StreamEventType::tryFrom($type) : null; } + /** + * @param array $arguments + */ + private function sceneOf(array $arguments): ?OverlayScene + { + $scene = $arguments['scene'] ?? null; + + return is_string($scene) ? OverlayScene::tryFrom($scene) : null; + } + + private function sceneSourcesLabel(?OverlayScene $scene): string + { + $chosenSourceIds = $scene instanceof OverlayScene + ? $this->currentStreamer()->settings->sceneSources->allowedFor($scene, $this->overlaySourceIds()) + : null; + + if ($chosenSourceIds === null) { + return 'Fontes: todas'; + } + + $handles = $this->overlaySources + ->filter(fn (StreamerSource $source): bool => in_array($source->id, $chosenSourceIds, strict: true)) + ->map($this->sourceHandle(...)) + ->implode(', '); + + return 'Fontes: '.$handles; + } + + /** + * @return list + */ + private function overlaySourceIds(): array + { + return array_values($this->overlaySources->map(fn (StreamerSource $source): string => $source->id)->all()); + } + + private function sourceHandle(StreamerSource $source): string + { + $username = $source->identity->metadata['username'] ?? null; + + return '@'.(is_string($username) ? $username : $source->identity->external_account_id); + } + private function sceneUrl(OverlayScene $scene, string $token): string { return url(sprintf('/overlay/%s/%s', $token, $scene->value)); diff --git a/app-modules/panel-app/tests/Feature/Streaming/StreamDashboardDataTest.php b/app-modules/panel-app/tests/Feature/Streaming/StreamDashboardDataTest.php index dde3943c5..948474283 100644 --- a/app-modules/panel-app/tests/Feature/Streaming/StreamDashboardDataTest.php +++ b/app-modules/panel-app/tests/Feature/Streaming/StreamDashboardDataTest.php @@ -176,3 +176,20 @@ function enableBotAccount(): void livewire(StreamDashboardPage::class) ->assertViewHas('otherSources', fn ($sources): bool => $sources->count() === 1 && $sources->first()->is($otherSource)); }); + +test('a outra fonte sem permissão na Twitch avisa e oferece reconectar', function (): void { + $mainSource = dashboardTwitchSource($this->user); + $otherSource = StreamerSource::factory()->create(['streamer_id' => $mainSource->streamer_id]); + $otherSource->identity->update([ + 'provider' => IdentityProvider::Twitch, + 'connected_at' => now()->subMonth(), + 'disconnected_at' => null, + 'metadata' => ['username' => 'he4rtdevs'], + ]); + + livewire(StreamDashboardPage::class) + ->assertSee('Sem permissão na Twitch') + ->assertActionVisible(TestAction::make('reconnectSource')->arguments(['source' => $otherSource->id])) + ->assertActionHasLabel(TestAction::make('reconnectSource')->arguments(['source' => $otherSource->id]), 'Reconectar como @he4rtdevs') + ->assertActionHidden(TestAction::make('reconnectSource')->arguments(['source' => $mainSource->id])); +}); diff --git a/app-modules/panel-app/tests/Feature/Streaming/StreamOverlayPreviewTest.php b/app-modules/panel-app/tests/Feature/Streaming/StreamOverlayPreviewTest.php index 4bfdcf913..9ae005bca 100644 --- a/app-modules/panel-app/tests/Feature/Streaming/StreamOverlayPreviewTest.php +++ b/app-modules/panel-app/tests/Feature/Streaming/StreamOverlayPreviewTest.php @@ -54,7 +54,7 @@ function chatPreviewVersion(string $html, string $token): string test('só as cenas transparentes trocam o fundo da prévia', function (): void { $html = livewire(StreamOverlaysPage::class)->html(); - expect(mb_substr_count($html, 'aria-label="Fundo da prévia"'))->toBe(2); + expect(mb_substr_count($html, 'aria-label="Fundo da prévia"'))->toBe(3); }); test('a prévia recarrega depois de salvar a configuração', function (): void { diff --git a/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php b/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php index c5ca1927e..9a2cb0202 100644 --- a/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php +++ b/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php @@ -14,6 +14,7 @@ use He4rt\Streaming\Enums\StreamEventType; use He4rt\Streaming\Enums\VoiceLayout; use He4rt\Streaming\Streamer\Actions\EnsureStreamer; +use He4rt\Streaming\Streamer\Data\PubSettings; use He4rt\Streaming\Streamer\Models\Streamer; use He4rt\Streaming\Streamer\Models\StreamerSource; use He4rt\Streaming\StreamEvent\Actions\RecordStreamEvent; @@ -64,6 +65,28 @@ Event::assertDispatched(fn (OverlaySettingsUpdated $broadcast): bool => $broadcast->scene === OverlayScene::Voice); }); +test('a He4rt Pub guarda o hash do evento a partir do link do Slido', function (string $input): void { + livewire(StreamOverlaysPage::class) + ->callAction('pubSettings', data: ['slido_event' => $input]) + ->assertHasNoActionErrors() + ->assertNotified('He4rt Pub atualizada'); + + expect(Streamer::query()->whereKey($this->streamer->id)->sole()->settings->pub->slidoEventHash)->toBe('jC9L7Lu93Vw3ssNhB92Pvb'); + Event::assertDispatched(fn (OverlaySettingsUpdated $broadcast): bool => $broadcast->scene === OverlayScene::Pub); +})->with([ + 'link do participante' => ['https://app.sli.do/event/jC9L7Lu93Vw3ssNhB92Pvb'], + 'link do wall com seção' => ['https://wall.sli.do/event/jC9L7Lu93Vw3ssNhB92Pvb?section=e4ca2f4d'], + 'só o hash' => ['jC9L7Lu93Vw3ssNhB92Pvb'], +]); + +test('a He4rt Pub recusa um link que não é do Slido', function (): void { + livewire(StreamOverlaysPage::class) + ->callAction('pubSettings', data: ['slido_event' => 'https://example.com/event/jC9L7Lu93Vw3ssNhB92Pvb']) + ->assertHasActionErrors(['slido_event']); + + expect(Streamer::query()->whereKey($this->streamer->id)->sole()->settings->pub->slidoEventHash)->toBeNull(); +}); + test('o chat salva estilo, tempo, tamanho, largura, direção e alinhamento e muda a overlay aberta', function (): void { $chat = [ 'style' => ChatStyle::Terminal->value, @@ -137,3 +160,14 @@ ->assertActionVisible('chatSettings') ->assertActionVisible('alertSettings'); }); + +test('a He4rt Pub tira o Slido da overlay quando o link fica vazio', function (): void { + $this->streamer->update(['settings' => $this->streamer->settings->withScene(new PubSettings('jC9L7Lu93Vw3ssNhB92Pvb'))]); + + livewire(StreamOverlaysPage::class) + ->callAction('pubSettings', data: ['slido_event' => '']) + ->assertHasNoActionErrors() + ->assertNotified('He4rt Pub atualizada'); + + expect(Streamer::query()->whereKey($this->streamer->id)->sole()->settings->pub->slidoEventHash)->toBeNull(); +}); diff --git a/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySourcesTest.php b/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySourcesTest.php new file mode 100644 index 000000000..e3b986ee2 --- /dev/null +++ b/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySourcesTest.php @@ -0,0 +1,65 @@ +user = User::factory()->streamer()->create(); + $this->streamer = resolve(EnsureStreamer::class)->handle($this->user); + $this->actingAs($this->user); +}); + +function namedSource(StreamerSource $source, string $username): StreamerSource +{ + $source->identity->update(['metadata' => ['username' => $username]]); + + return $source; +} + +test('com uma fonte só, a cena não oferece escolher fontes', function (): void { + StreamerSource::factory()->for($this->streamer)->create(); + + livewire(StreamOverlaysPage::class) + ->assertActionHidden(TestAction::make('sceneSources')->arguments(['scene' => 'pub'])); +}); + +test('o streamer escolhe a fonte da cena e o botão mostra a escolha', function (): void { + $pubChannel = namedSource(StreamerSource::factory()->for($this->streamer)->create(), 'he4rtdevs'); + namedSource(StreamerSource::factory()->for($this->streamer)->create(), 'danielhe4rt'); + + livewire(StreamOverlaysPage::class) + ->assertActionHasLabel(TestAction::make('sceneSources')->arguments(['scene' => 'pub']), 'Fontes: todas') + ->callAction(TestAction::make('sceneSources')->arguments(['scene' => 'pub']), data: ['sources' => [$pubChannel->id]]) + ->assertNotified('Fontes da cena atualizadas') + ->assertActionHasLabel(TestAction::make('sceneSources')->arguments(['scene' => 'pub']), 'Fontes: @he4rtdevs') + ->assertActionHasLabel(TestAction::make('sceneSources')->arguments(['scene' => 'chat']), 'Fontes: todas'); + + expect($this->streamer->refresh()->settings->sceneSources->chosenFor(OverlayScene::Pub))->toBe([$pubChannel->id]); + Event::assertDispatched(fn (OverlaySourcesUpdated $broadcast): bool => $broadcast->scene === OverlayScene::Pub); +}); + +test('a fonte de outro streamer não entra na cena', function (): void { + $ownSource = StreamerSource::factory()->for($this->streamer)->create(); + StreamerSource::factory()->for($this->streamer)->create(); + $foreignSource = StreamerSource::factory()->create(); + + livewire(StreamOverlaysPage::class) + ->callAction(TestAction::make('sceneSources')->arguments(['scene' => 'pub']), data: ['sources' => [$ownSource->id, $foreignSource->id]]); + + expect($this->streamer->refresh()->settings->sceneSources->chosenFor(OverlayScene::Pub))->not->toContain($foreignSource->id); +}); diff --git a/app-modules/panel-overlays/resources/css/overlay.css b/app-modules/panel-overlays/resources/css/overlay.css index 23f4c4e10..6a35af094 100644 --- a/app-modules/panel-overlays/resources/css/overlay.css +++ b/app-modules/panel-overlays/resources/css/overlay.css @@ -1,4 +1,5 @@ @import url('https://fonts.googleapis.com/css2?family=Saira:ital,wght@0,400;0,500;0,600;0,700;0,800;1,600;1,700;1,800&family=Saira+Condensed:wght@600;700;800&family=Saira+Semi+Condensed:ital,wght@0,700;0,800;1,700;1,800&family=JetBrains+Mono:wght@400;600;700&display=swap'); +@import url('https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@700;800;900&family=Poppins:wght@500;600;700&family=Permanent+Marker&display=swap'); @import 'tailwindcss' source('../'); @theme { @@ -25,6 +26,16 @@ --color-yellow: #ffcb05; --color-spotify: #1ed760; + + --font-pub-cond: 'Barlow Condensed', sans-serif; + --font-pub-sans: 'Poppins', sans-serif; + --font-pub-marker: 'Permanent Marker', cursive; + + --color-pub-asphalt: #0b0b09; + --color-pub-yellow: #f3c506; + --color-pub-gold: #bf9905; + --color-pub-chalk: #e6e5e5; + --color-pub-purple: #7430f1; } html, @@ -252,3 +263,19 @@ body, transform: scale(1.03); } } + +@keyframes pubMessageIn { + from { + opacity: 0; + transform: translateY(12px); + } +} + +@keyframes pubWipe { + from { + clip-path: inset(0 100% 0 0); + } + to { + clip-path: inset(0 0 0 0); + } +} diff --git a/app-modules/panel-overlays/resources/images/he4rt-pub-logo.png b/app-modules/panel-overlays/resources/images/he4rt-pub-logo.png new file mode 100644 index 000000000..51b126713 Binary files /dev/null and b/app-modules/panel-overlays/resources/images/he4rt-pub-logo.png differ diff --git a/app-modules/panel-overlays/resources/js/feed.ts b/app-modules/panel-overlays/resources/js/feed.ts index 6cd15048c..dea24fb80 100644 --- a/app-modules/panel-overlays/resources/js/feed.ts +++ b/app-modules/panel-overlays/resources/js/feed.ts @@ -1,3 +1,4 @@ +import type { SlidoQuestionChanges, SlidoQuestionPayload } from './types'; export interface TextFragmentDto { kind: 'text'; text: string; @@ -148,6 +149,26 @@ export interface LevelProgressDto { xpToNext: number; } +export interface PubQuestionsDto { + kind: 'pubQuestions'; + questions: SlidoQuestionPayload[]; +} + +export interface PubQuestionDto { + kind: 'pubQuestion'; + question: SlidoQuestionPayload; +} + +export interface PubQuestionPatchDto { + kind: 'pubQuestionPatch'; + id: number; + changes: SlidoQuestionChanges; +} + +export interface ChannelReconnectedDto { + kind: 'channelReconnected'; +} + export type FeedEventDto = | ChatMessageDto | ChatMessageDeletedDto @@ -157,4 +178,8 @@ export type FeedEventDto = | NowPlayingDto | VoiceRosterDto | OverlayConfigDto - | LevelProgressDto; + | LevelProgressDto + | PubQuestionsDto + | PubQuestionDto + | PubQuestionPatchDto + | ChannelReconnectedDto; diff --git a/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts b/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts index 4cfad9a27..309c3d10e 100644 --- a/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts +++ b/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts @@ -5,6 +5,9 @@ import type { LevelProgressDto, NowPlayingDto, OverlayConfigDto, + PubQuestionDto, + PubQuestionPatchDto, + PubQuestionsDto, StreamEventDto, VoiceRosterDto, } from '../feed'; @@ -22,18 +25,29 @@ export interface OverlayFeedHandlers { onVoiceRoster?(dto: VoiceRosterDto): void; onOverlayConfig?(dto: OverlayConfigDto): void; onLevelProgress?(dto: LevelProgressDto): void; + onPubQuestions?(dto: PubQuestionsDto): void; + onPubQuestion?(dto: PubQuestionDto): void; + onPubQuestionPatch?(dto: PubQuestionPatchDto): void; + onChannelReconnected?(): void; } -export function useOverlayFeed({ channel, authEndpoint }: OverlayChannelSource, handlers: OverlayFeedHandlers): void { +export function useOverlayFeed( + { channel, authEndpoint, scene, sources }: OverlayChannelSource, + handlers: OverlayFeedHandlers, +): void { const handlersRef = useRef(handlers); handlersRef.current = handlers; + const sourcesKey = sources?.join(',') ?? ''; useEffect(() => { const listener = (dto: FeedEventDto) => dispatch(dto, handlersRef.current); const isDemo = new URLSearchParams(window.location.search).has('demo'); + const sceneSources = sourcesKey === '' ? null : sourcesKey.split(','); - return isDemo ? subscribeDemoFeed(listener) : subscribeOverlayChannel({ channel, authEndpoint }, listener); - }, [channel, authEndpoint]); + return isDemo + ? subscribeDemoFeed(listener) + : subscribeOverlayChannel({ channel, authEndpoint, scene, sources: sceneSources }, listener); + }, [channel, authEndpoint, scene, sourcesKey]); } function dispatch(dto: FeedEventDto, handlers: OverlayFeedHandlers): void { @@ -65,5 +79,17 @@ function dispatch(dto: FeedEventDto, handlers: OverlayFeedHandlers): void { case 'levelProgress': handlers.onLevelProgress?.(dto); break; + case 'pubQuestions': + handlers.onPubQuestions?.(dto); + break; + case 'pubQuestion': + handlers.onPubQuestion?.(dto); + break; + case 'pubQuestionPatch': + handlers.onPubQuestionPatch?.(dto); + break; + case 'channelReconnected': + handlers.onChannelReconnected?.(); + break; } } diff --git a/app-modules/panel-overlays/resources/js/hooks/usePubQuestions.ts b/app-modules/panel-overlays/resources/js/hooks/usePubQuestions.ts new file mode 100644 index 000000000..f3952790d --- /dev/null +++ b/app-modules/panel-overlays/resources/js/hooks/usePubQuestions.ts @@ -0,0 +1,19 @@ +import { useCallback, useReducer } from 'react'; +import type { PubQuestionDto, PubQuestionPatchDto, PubQuestionsDto } from '../feed'; +import { pubQuestionsReducer } from '../lib/pubQuestions'; +import type { SlidoQuestionPayload } from '../types'; + +export function usePubQuestions(initial: SlidoQuestionPayload[]) { + const [questions, dispatch] = useReducer(pubQuestionsReducer, initial, (seed) => + pubQuestionsReducer([], { type: 'sync', questions: seed }), + ); + + const onSync = useCallback((dto: PubQuestionsDto) => dispatch({ type: 'sync', questions: dto.questions }), []); + const onUpsert = useCallback((dto: PubQuestionDto) => dispatch({ type: 'upsert', question: dto.question }), []); + const onPatch = useCallback( + (dto: PubQuestionPatchDto) => dispatch({ type: 'patch', id: dto.id, changes: dto.changes }), + [], + ); + + return { questions, onSync, onUpsert, onPatch }; +} diff --git a/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts b/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts index c34c00379..dc2cb4ddd 100644 --- a/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts +++ b/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts @@ -1,7 +1,7 @@ import Echo from 'laravel-echo'; import Pusher from 'pusher-js'; import type { FeedEventDto } from '../feed'; -import type { ChatMessagePayload, OverlayChannelSource } from '../types'; +import type { ChatMessagePayload, OverlayChannelSource, SlidoQuestionChanges, SlidoQuestionPayload } from '../types'; import { toChatMessage, toOverlayConfig, @@ -12,8 +12,19 @@ import { type Listener = (dto: FeedEventDto) => void; +interface SourcedPayload { + sourceId?: string | null; +} + +export function isFromSceneSources({ sourceId }: SourcedPayload, sources: string[] | null | undefined): boolean { + const sceneUsesEverySource = !sources || sources.length === 0; + const payloadHasNoSource = !sourceId; + + return sceneUsesEverySource || payloadHasNoSource || sources.includes(sourceId); +} + export function subscribeOverlayChannel( - { channel, authEndpoint }: OverlayChannelSource, + { channel, authEndpoint, scene, sources }: OverlayChannelSource, listener: Listener, ): () => void { const port = Number(import.meta.env.VITE_REVERB_PORT); @@ -31,8 +42,16 @@ export function subscribeOverlayChannel( }); echo.private(channel) - .listen('.alert.triggered', (alert: AlertPayload) => listener(toStreamEvent(alert))) - .listen('.chat.message', (message: ChatMessagePayload) => listener(toChatMessage(message))) + .listen('.alert.triggered', (alert: AlertPayload) => { + if (isFromSceneSources(alert, sources)) { + listener(toStreamEvent(alert)); + } + }) + .listen('.chat.message', (message: ChatMessagePayload) => { + if (isFromSceneSources(message, sources)) { + listener(toChatMessage(message)); + } + }) .listen('.chat.message-deleted', ({ msgId }: { msgId: string }) => listener({ kind: 'chatMessageDeleted', msgId }), ) @@ -40,9 +59,31 @@ export function subscribeOverlayChannel( listener({ kind: 'chatterCleared', chatterId }), ) .listen('.chat.cleared', () => listener({ kind: 'chatCleared' })) + .listen('.sources.updated', (payload: { scene: string }) => { + if (payload.scene === scene) { + window.location.reload(); + } + }) .listen('.settings.updated', ({ scene, settings }: SettingsPayload) => listener(toOverlayConfig(scene, settings, Date.now())), + ) + .listen('.pub.questions', ({ questions }: { questions: SlidoQuestionPayload[] }) => + listener({ kind: 'pubQuestions', questions }), + ) + .listen('.pub.question', (question: SlidoQuestionPayload) => listener({ kind: 'pubQuestion', question })) + .listen('.pub.question-patch', ({ id, changes }: { id: number; changes: SlidoQuestionChanges }) => + listener({ kind: 'pubQuestionPatch', id, changes }), ); + let hasConnectedBefore = false; + + echo.connector.pusher.connection.bind('connected', () => { + if (hasConnectedBefore) { + listener({ kind: 'channelReconnected' }); + } + + hasConnectedBefore = true; + }); + return () => echo.disconnect(); } diff --git a/app-modules/panel-overlays/resources/js/lib/overlayEvents.ts b/app-modules/panel-overlays/resources/js/lib/overlayEvents.ts index b11e68e55..b9d5b1c80 100644 --- a/app-modules/panel-overlays/resources/js/lib/overlayEvents.ts +++ b/app-modules/panel-overlays/resources/js/lib/overlayEvents.ts @@ -8,7 +8,7 @@ interface AlertActor { displayName: string; } -export type AlertPayload = { actor: AlertActor | null; isTest: boolean } & ( +export type AlertPayload = { sourceId?: string | null; actor: AlertActor | null; isTest: boolean } & ( | { type: 'follow'; details: null } | { type: 'sub'; details: { tier: TwitchTier; months: number; message: string | null } } | { type: 'gift_sub'; details: { tier: TwitchTier; total: number } } diff --git a/app-modules/panel-overlays/resources/js/lib/pubEdition.ts b/app-modules/panel-overlays/resources/js/lib/pubEdition.ts new file mode 100644 index 000000000..b7d2de57a --- /dev/null +++ b/app-modules/panel-overlays/resources/js/lib/pubEdition.ts @@ -0,0 +1,13 @@ +const EDITION_PATTERNS = [/(\d{1,3})\s*[ªº°a]?\s*edi[cç][aã]o/i, /#\s*(\d{1,3})\b/, /\bpub\s+(\d{1,3})\b/i]; + +export function editionLabel(eventName: string): string { + for (const pattern of EDITION_PATTERNS) { + const match = eventName.match(pattern); + + if (match) { + return `${Number(match[1])}ª edição`; + } + } + + return eventName; +} diff --git a/app-modules/panel-overlays/resources/js/lib/pubQuestions.ts b/app-modules/panel-overlays/resources/js/lib/pubQuestions.ts new file mode 100644 index 000000000..0a67ece62 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/lib/pubQuestions.ts @@ -0,0 +1,30 @@ +import type { SlidoQuestionChanges, SlidoQuestionPayload } from '../types'; + +export type PubQuestionsAction = + | { type: 'sync'; questions: SlidoQuestionPayload[] } + | { type: 'upsert'; question: SlidoQuestionPayload } + | { type: 'patch'; id: number; changes: SlidoQuestionChanges }; + +export function pubQuestionsReducer(state: SlidoQuestionPayload[], action: PubQuestionsAction): SlidoQuestionPayload[] { + switch (action.type) { + case 'sync': + return action.questions.filter((question) => question.isVisible); + case 'upsert': { + const others = state.filter((question) => question.id !== action.question.id); + return action.question.isVisible ? [...others, action.question] : others; + } + case 'patch': + return state.map((question) => (question.id === action.id ? { ...question, ...action.changes } : question)); + } +} + +export function highlightedQuestion(questions: SlidoQuestionPayload[]): SlidoQuestionPayload | null { + return questions.find((question) => question.isHighlighted && !question.isAnswered) ?? null; +} + +export function queuedQuestions(questions: SlidoQuestionPayload[], limit: number): SlidoQuestionPayload[] { + return questions + .filter((question) => !question.isHighlighted && !question.isAnswered) + .sort((a, b) => b.score - a.score || a.createdAt.localeCompare(b.createdAt)) + .slice(0, limit); +} diff --git a/app-modules/panel-overlays/resources/js/pages/Overlays/Chat.tsx b/app-modules/panel-overlays/resources/js/pages/Overlays/Chat.tsx index bc9dd829e..62f251570 100644 --- a/app-modules/panel-overlays/resources/js/pages/Overlays/Chat.tsx +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/Chat.tsx @@ -16,12 +16,19 @@ function chatConfigOf(dto: OverlayConfigDto): ChatConfig | null { return values ? chatConfigFrom(values) : null; } -export default function ChatOverlay({ channel, authEndpoint, settings, recentChat }: OverlayPageProps) { +export default function ChatOverlay({ + scene, + channel, + authEndpoint, + sources, + settings, + recentChat, +}: OverlayPageProps) { const [config, setConfig] = useState(() => chatConfigFrom(settings)); const chat = useChatMessages(recentChat.map(toChatMessage), MAX_MESSAGES); useOverlayFeed( - { channel, authEndpoint }, + { channel, authEndpoint, scene, sources }, { onChatMessage: chat.push, onChatDeleted: chat.remove, diff --git a/app-modules/panel-overlays/resources/js/pages/Overlays/Coworking.tsx b/app-modules/panel-overlays/resources/js/pages/Overlays/Coworking.tsx index 5384f8cbe..46a9563e5 100644 --- a/app-modules/panel-overlays/resources/js/pages/Overlays/Coworking.tsx +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/Coworking.tsx @@ -22,7 +22,14 @@ import type { OverlayPageProps } from '../../types'; const ALERT_DURATION_MS = 6000; -export default function CoworkingOverlay({ handle, channel, authEndpoint, recentChat }: OverlayPageProps) { +export default function CoworkingOverlay({ + scene, + handle, + channel, + authEndpoint, + sources, + recentChat, +}: OverlayPageProps) { const chat = useChatMessages(recentChat.map(toChatMessage)); const footer = useFooterBar(); const leveling = useLevelProgress(); @@ -31,7 +38,7 @@ export default function CoworkingOverlay({ handle, channel, authEndpoint, recent const presence = useVoicePresence(voice.roster); useOverlayFeed( - { channel, authEndpoint }, + { channel, authEndpoint, scene, sources }, { onChatMessage: chat.push, onChatDeleted: chat.remove, diff --git a/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx new file mode 100644 index 000000000..1c8256760 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx @@ -0,0 +1,52 @@ +import { useChatMessages } from '../../hooks/useChatMessages'; +import { useOverlayFeed } from '../../hooks/useOverlayFeed'; +import { usePubQuestions } from '../../hooks/usePubQuestions'; +import { toChatMessage } from '../../lib/overlayEvents'; +import { editionLabel } from '../../lib/pubEdition'; +import { highlightedQuestion, queuedQuestions } from '../../lib/pubQuestions'; +import { Stage } from '../../ui/Stage'; +import PubBrand from '../../ui/pub/PubBrand'; +import PubChat from '../../ui/pub/PubChat'; +import PubDock from '../../ui/pub/PubDock'; +import type { PubPageProps } from '../../types'; + +const QUEUE_LIMIT = 3; + +export default function PubOverlay({ scene, channel, authEndpoint, sources, recentChat, pub }: PubPageProps) { + const chat = useChatMessages(recentChat.map(toChatMessage)); + const questions = usePubQuestions(pub?.questions ?? []); + + useOverlayFeed( + { channel, authEndpoint, scene, sources }, + { + onChatMessage: chat.push, + onChatDeleted: chat.remove, + onChatterCleared: chat.removeChatter, + onChatCleared: chat.clear, + onPubQuestions: questions.onSync, + onPubQuestion: questions.onUpsert, + onPubQuestionPatch: questions.onPatch, + onOverlayConfig: (dto) => { + const isPubSettingsChange = scene in dto.overlays; + + if (isPubSettingsChange) { + window.location.reload(); + } + }, + onChannelReconnected: () => window.location.reload(), + }, + ); + + return ( + + + + + + ); +} diff --git a/app-modules/panel-overlays/resources/js/pages/Overlays/StartingSoon.tsx b/app-modules/panel-overlays/resources/js/pages/Overlays/StartingSoon.tsx index cf0e7f7f4..3221fc608 100644 --- a/app-modules/panel-overlays/resources/js/pages/Overlays/StartingSoon.tsx +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/StartingSoon.tsx @@ -23,6 +23,7 @@ export default function StartingSoonOverlay({ handle, channel, authEndpoint, + sources, settings, recentChat, }: OverlayPageProps) { @@ -33,7 +34,7 @@ export default function StartingSoonOverlay({ const leveling = useLevelProgress(); useOverlayFeed( - { channel, authEndpoint }, + { channel, authEndpoint, scene, sources }, { onChatMessage: chat.push, onChatDeleted: chat.remove, diff --git a/app-modules/panel-overlays/resources/js/pages/Overlays/Voice.tsx b/app-modules/panel-overlays/resources/js/pages/Overlays/Voice.tsx index 36c51a30d..caf5c534d 100644 --- a/app-modules/panel-overlays/resources/js/pages/Overlays/Voice.tsx +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/Voice.tsx @@ -13,12 +13,18 @@ function layoutFrom(dto: OverlayConfigDto): DockLayout | null { return layout === 'row' || layout === 'col' ? layout : null; } -export default function VoiceOverlay({ channel, authEndpoint, settings }: OverlayPageProps) { +export default function VoiceOverlay({ + scene, + channel, + authEndpoint, + sources, + settings, +}: OverlayPageProps) { const voice = useVoiceRoster(); const [layout, setLayout] = useState(settings.layout); useOverlayFeed( - { channel, authEndpoint }, + { channel, authEndpoint, scene, sources }, { onVoiceRoster: voice.onDto, onOverlayConfig: (dto) => setLayout((current) => layoutFrom(dto) ?? current), diff --git a/app-modules/panel-overlays/resources/js/types.ts b/app-modules/panel-overlays/resources/js/types.ts index 702af6d6e..e3bd0f8bc 100644 --- a/app-modules/panel-overlays/resources/js/types.ts +++ b/app-modules/panel-overlays/resources/js/types.ts @@ -1,6 +1,6 @@ import type { FragmentDto } from './feed'; -export type OverlayScene = 'coworking' | 'starting' | 'voice' | 'chat'; +export type OverlayScene = 'coworking' | 'starting' | 'voice' | 'chat' | 'pub'; export type StartingSoonSettings = { title: string | null; @@ -20,8 +20,47 @@ export type ChatSettings = { alignment: string; }; +export type PubSettings = { + slido_event_hash: string | null; +}; + export type SceneSettings = Record; +export interface SlidoReplyPayload { + id: number; + text: string; + authorName: string | null; + isFromModerator: boolean; +} + +export interface SlidoQuestionPayload { + id: number; + text: string; + authorName: string | null; + score: number; + isHighlighted: boolean; + isAnswered: boolean; + isVisible: boolean; + createdAt: string; + replies: SlidoReplyPayload[]; +} + +export type SlidoQuestionChanges = Partial>; + +export interface SlidoEventPayload { + hash: string; + name: string; + code: string; + isActive: boolean; + participantUrl: string; +} + +export interface PubSnapshot { + event: SlidoEventPayload; + questions: SlidoQuestionPayload[]; + qrSvg: string; +} + export interface ChatBadgePayload { setId: string; version: string; @@ -29,6 +68,7 @@ export interface ChatBadgePayload { } export interface ChatMessagePayload { + sourceId?: string | null; msgId: string; chatterId: string; username: string; @@ -38,6 +78,7 @@ export interface ChatMessagePayload { } export interface SessionPayload { + sourceId?: string; title: string | null; category: string | null; startedAt: string; @@ -46,6 +87,8 @@ export interface SessionPayload { export interface OverlayChannelSource { channel: string; authEndpoint: string; + scene?: string; + sources?: string[] | null; } export interface OverlayPageProps extends OverlayChannelSource { @@ -55,3 +98,7 @@ export interface OverlayPageProps exte recentChat: ChatMessagePayload[]; session: SessionPayload | null; } + +export interface PubPageProps extends OverlayPageProps { + pub: PubSnapshot | null; +} diff --git a/app-modules/panel-overlays/resources/js/ui/Stage.tsx b/app-modules/panel-overlays/resources/js/ui/Stage.tsx index 2a3ec1a53..1094f75e1 100644 --- a/app-modules/panel-overlays/resources/js/ui/Stage.tsx +++ b/app-modules/panel-overlays/resources/js/ui/Stage.tsx @@ -2,33 +2,51 @@ import { useEffect, useState } from 'react'; export interface StageProps { children: React.ReactNode; + fillViewport?: boolean; +} + +interface StageBox { + scale: number; + width: number; + height: number; } const STAGE_W = 1920; const STAGE_H = 1080; -function fitScale(): number { - return Math.min(window.innerWidth / STAGE_W, window.innerHeight / STAGE_H); +function fitStage(fillViewport: boolean): StageBox { + const scale = Math.min(window.innerWidth / STAGE_W, window.innerHeight / STAGE_H); + + if (!fillViewport) { + return { scale, width: STAGE_W, height: STAGE_H }; + } + + return { scale, width: Math.ceil(window.innerWidth / scale), height: Math.ceil(window.innerHeight / scale) }; } -export function Stage({ children }: StageProps) { - const [scale, setScale] = useState(fitScale); +export function Stage({ children, fillViewport = false }: StageProps) { + const [box, setBox] = useState(() => fitStage(fillViewport)); useEffect(() => { - const onResize = () => setScale(fitScale()); + const onResize = () => setBox(fitStage(fillViewport)); + onResize(); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); - }, []); + }, [fillViewport]); + + const anchorStyle: React.CSSProperties = fillViewport + ? { position: 'absolute', top: 0, left: 0, transformOrigin: '0 0' } + : { position: 'relative', transformOrigin: 'center' }; return (
{children} diff --git a/app-modules/panel-overlays/resources/js/ui/pub/PubBrand.tsx b/app-modules/panel-overlays/resources/js/ui/pub/PubBrand.tsx new file mode 100644 index 000000000..0d5ff5045 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubBrand.tsx @@ -0,0 +1,13 @@ +import logoUrl from '../../../images/he4rt-pub-logo.png'; + +export function PubBrand() { + return ( + He4rt Pub + ); +} + +export default PubBrand; diff --git a/app-modules/panel-overlays/resources/js/ui/pub/PubChat.tsx b/app-modules/panel-overlays/resources/js/ui/pub/PubChat.tsx new file mode 100644 index 000000000..4c1eeee70 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubChat.tsx @@ -0,0 +1,49 @@ +import type { ChatMessageDto } from '../../feed'; + +export interface PubChatProps { + edition: string | null; + messages: ChatMessageDto[]; +} + +const VISIBLE_MESSAGES = 8; + +export function PubChat({ edition, messages }: PubChatProps) { + return ( + <> +
+ + {edition ? ( +
+ {edition} +
+ ) : null} + +
+ {messages.slice(-VISIBLE_MESSAGES).map((message) => ( +
+ {message.username} + + {message.fragments.map((fragment, index) => + fragment.kind === 'emote' ? ( + + ) : ( + {fragment.text} + ), + )} + +
+ ))} +
+ + ); +} + +export default PubChat; diff --git a/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx b/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx new file mode 100644 index 000000000..d21258c43 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx @@ -0,0 +1,98 @@ +import type { SlidoEventPayload, SlidoQuestionPayload } from '../../types'; + +export interface PubDockProps { + event: SlidoEventPayload | null; + qrSvg: string | null; + highlighted: SlidoQuestionPayload | null; + queue: SlidoQuestionPayload[]; +} + +function authorOf(question: SlidoQuestionPayload): string { + return question.authorName ?? 'Anônimo'; +} + +function QuestionOnAir({ question }: { question: SlidoQuestionPayload }) { + return ( + <> +
+ {authorOf(question)} pergunta + ▲ {question.score} +
+
+

+ {question.text} +

+
+ + ); +} + +function QuestionQueue({ queue }: { queue: SlidoQuestionPayload[] }) { + return ( +
+

Próximas perguntas

+ {queue.map((question) => ( +
+ ▲ {question.score} + {question.text} +
+ ))} +
+ ); +} + +function EmptyDock({ isConfigured }: { isConfigured: boolean }) { + return ( +
+ + {isConfigured ? 'Manda tua pergunta' : 'Slido não configurado'} + + + {isConfigured + ? 'Aponta a câmera do celular pro QR ao lado.' + : 'Cole o link do evento na cena He4rt Pub do painel.'} + +
+ ); +} + +export function PubDock({ event, qrSvg, highlighted, queue }: PubDockProps) { + const contentKey = highlighted ? `live-${highlighted.id}` : queue.length > 0 ? 'queue' : 'empty'; + + return ( +
+ {event && qrSvg ? ( +
+
+ + Pergunte aqui + + + slido.com #{event.code} + +
+ ) : null} + +
+ {highlighted ? ( + + ) : queue.length > 0 ? ( + + ) : ( + + )} +
+
+ ); +} + +export default PubDock; diff --git a/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php b/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php index 846797ebb..62ec5a9c9 100644 --- a/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php +++ b/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php @@ -4,6 +4,7 @@ namespace He4rt\PanelOverlays\Http\Controllers; +use He4rt\PanelOverlays\Pub\PubOverlayState; use He4rt\Streaming\Enums\OverlayScene; use He4rt\Streaming\Overlay\OverlayInitialState; use He4rt\Streaming\Streamer\Actions\ResolveOverlayToken; @@ -21,19 +22,24 @@ public function __invoke( OverlayScene $scene, ResolveOverlayToken $resolveToken, OverlayInitialState $initialState, + PubOverlayState $pubState, ): Response { $streamer = $resolveToken->handle($token); abort_unless($streamer instanceof Streamer, HttpResponse::HTTP_NOT_FOUND); + $sourceIds = $streamer->sourceIdsForScene($scene); + return Inertia::render($this->component($scene), [ 'scene' => $scene->value, 'handle' => $streamer->user->username, 'channel' => $streamer->overlayChannel(), 'authEndpoint' => route('overlays.broadcasting.auth', ['token' => $token]), 'settings' => $streamer->settings->forScene($scene)->toArray(), - 'recentChat' => $initialState->recentChat($streamer, self::RECENT_CHAT_LIMIT), - 'session' => $initialState->openSession($streamer), + 'sources' => $sourceIds, + 'recentChat' => $initialState->recentChat($streamer, self::RECENT_CHAT_LIMIT, $sourceIds), + 'session' => $initialState->openSession($streamer, $sourceIds), + 'pub' => $scene === OverlayScene::Pub ? $pubState->for($streamer) : null, ]); } @@ -44,6 +50,7 @@ private function component(OverlayScene $scene): string OverlayScene::StartingSoon => 'Overlays/StartingSoon', OverlayScene::Voice => 'Overlays/Voice', OverlayScene::Chat => 'Overlays/Chat', + OverlayScene::Pub => 'Overlays/Pub', }; } } diff --git a/app-modules/panel-overlays/src/Pub/PubOverlayState.php b/app-modules/panel-overlays/src/Pub/PubOverlayState.php new file mode 100644 index 000000000..d04fb0d84 --- /dev/null +++ b/app-modules/panel-overlays/src/Pub/PubOverlayState.php @@ -0,0 +1,76 @@ +>, qrSvg: string}|null + */ + public function for(Streamer $streamer): ?array + { + $eventHash = $streamer->settings->pub->slidoEventHash; + + if ($eventHash === null) { + return null; + } + + try { + $location = $this->client->locate($eventHash); + $event = $this->client->event($location); + $questions = $this->client->questions($location, $this->participantToken($eventHash, $location)); + } catch (Throwable $throwable) { + Log::warning('Slido indisponível ao montar a overlay da He4rt Pub.', ['hash' => $eventHash, 'error' => $throwable->getMessage()]); + + return null; + } + + return [ + 'event' => $event->toArray(), + 'questions' => array_map(fn (SlidoQuestion $question): array => $question->toArray(), $questions), + 'qrSvg' => $this->qrSvg($event->participantUrl), + ]; + } + + private function participantToken(string $eventHash, SlidoEventLocation $location): SlidoParticipantToken + { + $cacheKey = 'integration-slido:overlay-token:'.$eventHash; + $cached = Cache::get($cacheKey); + + if ($cached instanceof SlidoParticipantToken && !$cached->needsRefresh()) { + return $cached; + } + + $token = $this->client->issueParticipantToken($location); + + Cache::put($cacheKey, $token, $token->expiresAt); + + return $token; + } + + private function qrSvg(string $participantUrl): string + { + $writer = new Writer(new ImageRenderer(new RendererStyle(self::QR_SIZE, margin: 1), new SvgImageBackEnd())); + + return $writer->writeString($participantUrl); + } +} diff --git a/app-modules/panel-overlays/tests/Feature/ShowOverlayTest.php b/app-modules/panel-overlays/tests/Feature/ShowOverlayTest.php index 00037c867..a4cbef038 100644 --- a/app-modules/panel-overlays/tests/Feature/ShowOverlayTest.php +++ b/app-modules/panel-overlays/tests/Feature/ShowOverlayTest.php @@ -3,18 +3,27 @@ declare(strict_types=1); use He4rt\Activity\Message\Models\Message; +use He4rt\IntegrationSlido\Transport\Requests\AuthorizeParticipant; +use He4rt\IntegrationSlido\Transport\Requests\ExchangeAuthorizationCode; +use He4rt\IntegrationSlido\Transport\Requests\GetEvent; +use He4rt\IntegrationSlido\Transport\Requests\GetEventByHash; +use He4rt\IntegrationSlido\Transport\Requests\GetQuestions; +use He4rt\IntegrationSlido\Transport\Requests\LookupEvent; use He4rt\Streaming\Chat\Data\ChatMessageMetadata; use He4rt\Streaming\Enums\OverlayScene; use He4rt\Streaming\Enums\StreamerStatus; use He4rt\Streaming\Session\Models\StreamSession; use He4rt\Streaming\Streamer\Data\MutedChatter; use He4rt\Streaming\Streamer\Data\MutedChatters; +use He4rt\Streaming\Streamer\Data\PubSettings; use He4rt\Streaming\Streamer\Models\Streamer; use He4rt\Streaming\Streamer\Models\StreamerSource; use He4rt\Streaming\StreamEvent\Models\StreamEvent; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Inertia\Testing\AssertableInertia; +use Saloon\Http\Faking\MockClient; +use Saloon\Http\Faking\MockResponse; const OVERLAY_TOKEN = '3bfa1a2ce19eadd54f3242055ea3a1a9'; @@ -22,6 +31,10 @@ $this->streamer = Streamer::factory()->withToken(OVERLAY_TOKEN)->create(); }); +afterEach(function (): void { + MockClient::destroyGlobal(); +}); + function overlayChatMessage(StreamerSource $source, int $minutesAgo): Message { return Message::factory()->create([ @@ -43,6 +56,7 @@ function overlayChatMessage(StreamerSource $source, int $minutesAgo): Message ->where('channel', $this->streamer->overlayChannel()) ->where('authEndpoint', route('overlays.broadcasting.auth', ['token' => OVERLAY_TOKEN])) ->where('settings', $this->streamer->settings->forScene($scene)->toArray()) + ->where('sources', expected: null) ->where('recentChat', []) ->where('session', expected: null)); })->with([ @@ -50,8 +64,55 @@ function overlayChatMessage(StreamerSource $source, int $minutesAgo): Message 'a live vai começar' => [OverlayScene::StartingSoon, 'Overlays/StartingSoon'], 'sala de voz' => [OverlayScene::Voice, 'Overlays/Voice'], 'chat' => [OverlayScene::Chat, 'Overlays/Chat'], + 'he4rt pub' => [OverlayScene::Pub, 'Overlays/Pub'], ]); +test('a cena da He4rt Pub abre com a edição, as perguntas e o QR Code do Slido', function (): void { + $this->streamer->update(['settings' => $this->streamer->settings->withScene(new PubSettings('jC9L7Lu93Vw3ssNhB92Pvb'))]); + + MockClient::global([ + LookupEvent::class => MockResponse::make(['clusterId' => 'eu1', 'eventId' => '96d0aba7-efed-4b29-a78a-609e6e4074c0']), + GetEventByHash::class => MockResponse::make([ + 'name' => 'He4rt Pub #12', + 'code' => '9410834', + 'is_active' => true, + 'url' => ['app' => 'https://app.sli.do/event/jC9L7Lu93Vw3ssNhB92Pvb'], + ]), + AuthorizeParticipant::class => MockResponse::make(['redirectUri' => 'https://wall.sli.do/event/x/oauth-callback?code=c1']), + ExchangeAuthorizationCode::class => MockResponse::make(['access_token' => 'a', 'refresh_token' => 'r', 'expires_in' => 600]), + GetEvent::class => MockResponse::make(['sections' => [['uuid' => 'section-1', 'is_active' => true]]]), + GetQuestions::class => MockResponse::make([ + ['event_question_id' => 1, 'type' => 'Question', 'text' => 'Qual a próxima edição?', 'is_public' => true, 'is_highlighted' => true], + ]), + ]); + + $this->get(route('overlays.show', ['token' => OVERLAY_TOKEN, 'scene' => OverlayScene::Pub])) + ->assertOk() + ->assertInertia(fn (AssertableInertia $page): AssertableInertia => $page + ->component('Overlays/Pub') + ->where('pub.event.name', 'He4rt Pub #12') + ->where('pub.event.code', '9410834') + ->where('pub.questions.0.text', 'Qual a próxima edição?') + ->where('pub.questions.0.isHighlighted', expected: true) + ->where('pub.qrSvg', fn (string $svg): bool => str_contains($svg, 'streamer->update(['settings' => $this->streamer->settings->withScene(new PubSettings('jC9L7Lu93Vw3ssNhB92Pvb'))]); + + MockClient::global([ + LookupEvent::class => MockResponse::make(['message' => 'Bad Gateway'], 502), + ]); + + $this->get(route('overlays.show', ['token' => OVERLAY_TOKEN, 'scene' => OverlayScene::Pub])) + ->assertOk() + ->assertInertia(fn (AssertableInertia $page): AssertableInertia => $page + ->component('Overlays/Pub') + ->where('pub', expected: null)); + +}); + test('a barra da overlay mostra o usuário do streamer, não o canal privado', function (): void { $this->get('/overlay/'.OVERLAY_TOKEN.'/coworking') ->assertInertia(fn (AssertableInertia $page): AssertableInertia => $page @@ -166,3 +227,40 @@ function overlayChatMessage(StreamerSource $source, int $minutesAgo): Message ->where('session.category', 'Software and Game Development') ->has('session.startedAt')); }); + +test('a cena com fonte escolhida só traz o chat e a live dessa fonte', function (): void { + $pubChannel = StreamerSource::factory()->for($this->streamer)->readingChat()->create(); + $ownChannel = StreamerSource::factory()->for($this->streamer)->readingChat()->create(); + $pubMessage = overlayChatMessage($pubChannel, minutesAgo: 2); + overlayChatMessage($ownChannel, minutesAgo: 1); + StreamSession::factory()->forSource($ownChannel)->create(['title' => 'Live do canal pessoal']); + $this->streamer->update(['settings' => $this->streamer->settings->withSceneSources(OverlayScene::Pub, [$pubChannel->id])]); + + $this->get('/overlay/'.OVERLAY_TOKEN.'/pub') + ->assertInertia(fn (AssertableInertia $page): AssertableInertia => $page + ->where('sources', [$pubChannel->id]) + ->has('recentChat', 1) + ->where('recentChat.0.msgId', $pubMessage->provider_message_id) + ->where('recentChat.0.sourceId', $pubChannel->id) + ->where('session', expected: null)); + + $this->get('/overlay/'.OVERLAY_TOKEN.'/chat') + ->assertInertia(fn (AssertableInertia $page): AssertableInertia => $page + ->where('sources', expected: null) + ->has('recentChat', 2) + ->where('session.title', 'Live do canal pessoal') + ->where('session.sourceId', $ownChannel->id)); +}); + +test('a cena volta a usar todas as fontes quando a fonte escolhida some', function (): void { + $source = StreamerSource::factory()->for($this->streamer)->readingChat()->create(); + $gone = StreamerSource::factory()->for($this->streamer)->create(); + $this->streamer->update(['settings' => $this->streamer->settings->withSceneSources(OverlayScene::Pub, [$gone->id])]); + $gone->delete(); + overlayChatMessage($source, minutesAgo: 1); + + $this->get('/overlay/'.OVERLAY_TOKEN.'/pub') + ->assertInertia(fn (AssertableInertia $page): AssertableInertia => $page + ->where('sources', expected: null) + ->has('recentChat', 1)); +}); diff --git a/app-modules/streaming/CONTEXT.md b/app-modules/streaming/CONTEXT.md index aee8570f7..fdd1b9a83 100644 --- a/app-modules/streaming/CONTEXT.md +++ b/app-modules/streaming/CONTEXT.md @@ -52,8 +52,9 @@ Esses três dependem deste módulo, e este módulo não depende de nenhum deles. | **Adoção** | Quando alguém conecta uma conta que já existe como identidade solta, a identidade passa a apontar para o `User` dessa pessoa e o histórico vem junto. É feita no `identity`. | Account merge (ADR identity-0001): ele move dados entre dois `User` que já existem. | | **Token da overlay** | O segredo na URL do OBS (`/overlay/{token}/{cena}`). Um por streamer, vale para todas as cenas. Guardado como hash sha256 (para a busca) e criptografado (para o painel mostrar). | Um token de OAuth: o token da overlay não dá acesso a nenhuma API. | | **Impressão do token** | O começo do hash do token, usado no nome do canal privado. Quando o token muda, o canal muda e as overlays abertas param de receber na hora. | O token: a impressão não autentica nada sozinha. | -| **Cena** | `OverlayScene`: `coworking`, `starting`, `voice`, `chat`. Cada cena tem o próprio tipo de configuração. | Uma cena do OBS: a cena da He4rt é uma _fonte de navegador_ dentro de uma cena do OBS. | +| **Cena** | `OverlayScene`: `coworking`, `starting`, `voice`, `chat`, `pub`. Cada cena tem o próprio tipo de configuração. | Uma cena do OBS: a cena da He4rt é uma _fonte de navegador_ dentro de uma cena do OBS. | | **Configurações** | `streamers.settings`: jsonb tipado (`StreamerSettings`) com um bloco por cena e o mapa de alertas ligados. | `.env` / `config/`: as configurações são por streamer e mudam pelo painel. | +| **Fontes da cena** | `settings.scene_sources`: as fontes que uma cena usa. Cena sem escolha usa todas as fontes ligadas. Os broadcasts levam o `sourceId`, e a overlay da cena descarta o que vem de outra fonte. | O toggle da fonte: o toggle vale para todas as cenas, e as fontes da cena só restringem uma cena. | | **Alerta** | A apresentação de um evento de stream na overlay. Só sai se a fonte está ligada e o tipo está ligado nas configurações. | O evento: todo evento é gravado, e só alguns viram alerta. | | **Alerta de teste** | Um alerta disparado pelo painel. Vai **só** por broadcast e nunca é gravado. | Um evento real: nunca aparece nos números nem na atividade. | | **Status** | `active` ou `disabled`. Segue a role `streamer`: perder a role desativa o streamer, e recuperar a role reativa. `disabled` = token não resolve, canal recusa e inscrições EventSub removidas. Nenhum dado é apagado. | Soft delete: `deleted_at` protege contra exclusão acidental, e `disabled` é o estado normal de "sem acesso". | diff --git a/app-modules/streaming/README.md b/app-modules/streaming/README.md index 3ee839da3..d06eabee8 100644 --- a/app-modules/streaming/README.md +++ b/app-modules/streaming/README.md @@ -90,6 +90,11 @@ php artisan reverb:start --debug Com `--debug`, o terminal mostra cada broadcast, o que ajuda a conferir o nome do canal e o payload. +A cena He4rt Pub precisa também do `slido:serve`. Com o lerd, ligue o worker `slido`. Sem o lerd, +rode `php artisan slido:serve` junto do Reverb. O comando confere a cada 15 s quais streamers têm +um evento do Slido na cena e uma overlay aberta, conecta em cada evento e desconecta quando a +overlay fecha. Um evento usado por dois streamers abre uma conexão só. + ### 2. Streamer e fonte 1. Dê a role `streamer` ao seu usuário pelo painel admin. diff --git a/app-modules/streaming/src/Broadcasting/AlertTriggered.php b/app-modules/streaming/src/Broadcasting/AlertTriggered.php index 61f8119b6..b0b51b43f 100644 --- a/app-modules/streaming/src/Broadcasting/AlertTriggered.php +++ b/app-modules/streaming/src/Broadcasting/AlertTriggered.php @@ -6,6 +6,7 @@ use He4rt\Streaming\Enums\StreamEventType; use He4rt\Streaming\Streamer\Models\Streamer; +use He4rt\Streaming\Streamer\Models\StreamerSource; use He4rt\Streaming\StreamEvent\Data\StreamActor; use He4rt\Streaming\StreamEvent\Data\StreamEventDetails; use He4rt\Streaming\StreamEvent\Models\StreamEvent; @@ -29,15 +30,22 @@ public function __construct( public ?StreamActor $actor = null, public ?StreamEventDetails $details = null, public bool $isTest = false, + public ?string $sourceId = null, ) {} public static function fromEvent(StreamEvent $event): self { + $sourceId = StreamerSource::query() + ->where('streamer_id', $event->streamer_id) + ->where('external_identity_id', $event->external_identity_id) + ->value('id'); + return new self( streamer: $event->streamer, type: $event->type, actor: $event->actor(), details: $event->details, + sourceId: is_string($sourceId) ? $sourceId : null, ); } @@ -53,11 +61,12 @@ public function broadcastAs(): string } /** - * @return array{type: string, actor: array{login: string, displayName: string}|null, details: array|null, isTest: bool} + * @return array{sourceId: string|null, type: string, actor: array{login: string, displayName: string}|null, details: array|null, isTest: bool} */ public function broadcastWith(): array { return [ + 'sourceId' => $this->sourceId, 'type' => $this->type->value, 'actor' => $this->actor?->toBroadcast(), 'details' => $this->details?->toArray(), diff --git a/app-modules/streaming/src/Broadcasting/ChatMessageReceived.php b/app-modules/streaming/src/Broadcasting/ChatMessageReceived.php index e2a3698ca..c770d0a1e 100644 --- a/app-modules/streaming/src/Broadcasting/ChatMessageReceived.php +++ b/app-modules/streaming/src/Broadcasting/ChatMessageReceived.php @@ -28,15 +28,17 @@ public function __construct( public string $msgId, public string $chatterId, public ChatMessageMetadata $metadata, + public ?string $sourceId = null, ) {} - public static function fromMessage(Streamer $streamer, Message $message): self + public static function fromMessage(Streamer $streamer, Message $message, ?string $sourceId = null): self { return new self( streamer: $streamer, msgId: $message->provider_message_id ?? '', chatterId: $message->provider->external_account_id ?? '', metadata: ChatMessageMetadata::fromArray($message->metadata ?? []), + sourceId: $sourceId, ); } @@ -52,11 +54,12 @@ public function broadcastAs(): string } /** - * @return array{msgId: string, chatterId: string, username: string, color: string|null, badges: list>, fragments: list>} + * @return array{sourceId: string|null, msgId: string, chatterId: string, username: string, color: string|null, badges: list>, fragments: list>} */ public function broadcastWith(): array { return [ + 'sourceId' => $this->sourceId, 'msgId' => $this->msgId, 'chatterId' => $this->chatterId, 'username' => $this->metadata->displayName, diff --git a/app-modules/streaming/src/Broadcasting/OverlaySourcesUpdated.php b/app-modules/streaming/src/Broadcasting/OverlaySourcesUpdated.php new file mode 100644 index 000000000..2cc749a06 --- /dev/null +++ b/app-modules/streaming/src/Broadcasting/OverlaySourcesUpdated.php @@ -0,0 +1,44 @@ + */ + public function broadcastOn(): array + { + return [new PrivateChannel($this->streamer->overlayChannel())]; + } + + public function broadcastAs(): string + { + return 'sources.updated'; + } + + /** @return array{scene: string} */ + public function broadcastWith(): array + { + return ['scene' => $this->scene->value]; + } +} diff --git a/app-modules/streaming/src/Broadcasting/StreamSessionEnded.php b/app-modules/streaming/src/Broadcasting/StreamSessionEnded.php index cb4264bad..d582c28c9 100644 --- a/app-modules/streaming/src/Broadcasting/StreamSessionEnded.php +++ b/app-modules/streaming/src/Broadcasting/StreamSessionEnded.php @@ -41,10 +41,11 @@ public function broadcastWhen(): bool return $this->source->enabled; } - /** @return array{endedAt: string|null} */ + /** @return array{sourceId: string, endedAt: string|null} */ public function broadcastWith(): array { return [ + 'sourceId' => $this->source->id, 'endedAt' => $this->session->ended_at?->toIso8601String(), ]; } diff --git a/app-modules/streaming/src/Broadcasting/StreamSessionStarted.php b/app-modules/streaming/src/Broadcasting/StreamSessionStarted.php index 6463db069..88712ac86 100644 --- a/app-modules/streaming/src/Broadcasting/StreamSessionStarted.php +++ b/app-modules/streaming/src/Broadcasting/StreamSessionStarted.php @@ -41,10 +41,11 @@ public function broadcastWhen(): bool return $this->source->enabled; } - /** @return array{title: string|null, category: string|null, startedAt: string} */ + /** @return array{sourceId: string, title: string|null, category: string|null, startedAt: string} */ public function broadcastWith(): array { return [ + 'sourceId' => $this->source->id, 'title' => $this->session->title, 'category' => $this->session->category, 'startedAt' => $this->session->started_at->toIso8601String(), diff --git a/app-modules/streaming/src/Chat/Actions/RecordChatMessage.php b/app-modules/streaming/src/Chat/Actions/RecordChatMessage.php index 57ef0008a..3c415f539 100644 --- a/app-modules/streaming/src/Chat/Actions/RecordChatMessage.php +++ b/app-modules/streaming/src/Chat/Actions/RecordChatMessage.php @@ -48,7 +48,7 @@ public function handle(IncomingChatMessage $incoming): ?Message $isMutedOnOverlay = $source->streamer->settings->mutedChatters->contains($incoming->platform, $incoming->chatterId); if ($message->wasRecentlyCreated && $source->showsChat() && !$isMutedOnOverlay) { - event(ChatMessageReceived::fromMessage($source->streamer, $message)); + event(ChatMessageReceived::fromMessage($source->streamer, $message, $source->id)); } return $message; diff --git a/app-modules/streaming/src/Chat/Queries/StreamerChatMessages.php b/app-modules/streaming/src/Chat/Queries/StreamerChatMessages.php index f0c897695..f152a7047 100644 --- a/app-modules/streaming/src/Chat/Queries/StreamerChatMessages.php +++ b/app-modules/streaming/src/Chat/Queries/StreamerChatMessages.php @@ -11,20 +11,19 @@ use He4rt\Streaming\Streamer\Models\Streamer; use He4rt\Streaming\Streamer\Models\StreamerSource; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection; final readonly class StreamerChatMessages { /** * Messages from the channels of every source that shows chat on the overlay. * + * @param list|null $sourceIds narrows to these sources; null keeps every source * @return Builder */ - public function of(Streamer $streamer): Builder + public function of(Streamer $streamer, ?array $sourceIds = null): Builder { - $chatSources = $streamer->sources() - ->with('identity') - ->get() - ->filter(fn (StreamerSource $source): bool => $source->showsChat()); + $chatSources = $this->chatSources($streamer, $sourceIds); return Message::query()->where(function (Builder $query) use ($chatSources): void { if ($chatSources->isEmpty()) { @@ -42,13 +41,28 @@ public function of(Streamer $streamer): Builder } /** + * @param list|null $sourceIds narrows to these sources; null keeps every source + * @return Collection + */ + public function chatSources(Streamer $streamer, ?array $sourceIds = null): Collection + { + return $streamer->sources() + ->with('identity') + ->when($sourceIds !== null, fn (Builder $query): Builder => $query->whereKey($sourceIds)) + ->get() + ->filter(fn (StreamerSource $source): bool => $source->showsChat()) + ->values(); + } + + /** + * @param list|null $sourceIds narrows to these sources; null keeps every source * @return Builder */ - public function onOverlay(Streamer $streamer): Builder + public function onOverlay(Streamer $streamer, ?array $sourceIds = null): Builder { $mutedChatters = $streamer->settings->mutedChatters; - return $this->of($streamer) + return $this->of($streamer, $sourceIds) ->whereNull('metadata->deleted_at') ->whereNull('metadata->hidden_at') ->when($streamer->chat_cleared_at instanceof CarbonInterface, fn (Builder $query): Builder => $query->where('sent_at', '>', $streamer->chat_cleared_at)) diff --git a/app-modules/streaming/src/Enums/OverlayScene.php b/app-modules/streaming/src/Enums/OverlayScene.php index 4b22a6be9..a67840bd8 100644 --- a/app-modules/streaming/src/Enums/OverlayScene.php +++ b/app-modules/streaming/src/Enums/OverlayScene.php @@ -14,6 +14,7 @@ enum OverlayScene: string implements HasColor, HasDescription, HasLabel case StartingSoon = 'starting'; case Voice = 'voice'; case Chat = 'chat'; + case Pub = 'pub'; public function getLabel(): string { @@ -22,6 +23,7 @@ public function getLabel(): string self::StartingSoon => 'A live vai começar', self::Voice => 'Sala de voz', self::Chat => 'Chat', + self::Pub => 'He4rt Pub', }; } @@ -32,12 +34,13 @@ public function getDescription(): string self::StartingSoon => 'Cena de abertura com contagem regressiva.', self::Voice => 'Quem está na call do Discord, com fundo transparente, por cima de qualquer cena.', self::Chat => 'Só o chat da live, com fundo transparente, por cima de qualquer cena.', + self::Pub => 'Camada transparente sobre a câmera: chat, perguntas do Slido, QR Code e a edição da He4rt Pub.', }; } public function hasTransparentBackground(): bool { - return $this === self::Voice || $this === self::Chat; + return in_array($this, [self::Voice, self::Chat, self::Pub], strict: true); } public function getColor(): string @@ -47,6 +50,7 @@ public function getColor(): string self::StartingSoon => 'info', self::Voice => 'success', self::Chat => 'warning', + self::Pub => 'danger', }; } } diff --git a/app-modules/streaming/src/Overlay/OverlayInitialState.php b/app-modules/streaming/src/Overlay/OverlayInitialState.php index 1f7c17e28..01e7a4948 100644 --- a/app-modules/streaming/src/Overlay/OverlayInitialState.php +++ b/app-modules/streaming/src/Overlay/OverlayInitialState.php @@ -11,6 +11,7 @@ use He4rt\Streaming\Session\Models\StreamSession; use He4rt\Streaming\Streamer\Models\Streamer; use He4rt\Streaming\Streamer\Models\StreamerSource; +use Illuminate\Database\Eloquent\Builder; final readonly class OverlayInitialState { @@ -19,28 +20,41 @@ public function __construct( ) {} /** - * @return list>, fragments: list>}> + * @param list|null $sourceIds narrows to these sources; null keeps every source + * @return list>, fragments: list>}> */ - public function recentChat(Streamer $streamer, int $limit = 30): array + public function recentChat(Streamer $streamer, int $limit = 30, ?array $sourceIds = null): array { - $latestMessages = $this->chatMessages->onOverlay($streamer) + $sourceIdByChannel = $this->chatMessages->chatSources($streamer, $sourceIds) + ->mapWithKeys(fn (StreamerSource $source): array => [$this->channelKey($source->identity->provider->value, $source->identity->external_account_id) => $source->id]) + ->all(); + + $latestMessages = $this->chatMessages->onOverlay($streamer, $sourceIds) ->with('provider') ->latest('sent_at') ->limit($limit) ->get() ->reverse() - ->map(fn (Message $message): array => ChatMessageReceived::fromMessage($streamer, $message)->broadcastWith()) + ->map(fn (Message $message): array => ChatMessageReceived::fromMessage( + $streamer, + $message, + $sourceIdByChannel[$this->channelKey($message->platform->value, (string) $message->channel_id)] ?? null, + )->broadcastWith()) ->all(); return array_values($latestMessages); } /** - * @return array{title: string|null, category: string|null, startedAt: string}|null + * @param list|null $sourceIds narrows to these sources; null keeps every source + * @return array{sourceId: string, title: string|null, category: string|null, startedAt: string}|null */ - public function openSession(Streamer $streamer): ?array + public function openSession(Streamer $streamer, ?array $sourceIds = null): ?array { - $enabledSources = $streamer->sources()->where('enabled', operator: true)->get(); + $enabledSources = $streamer->sources() + ->where('enabled', operator: true) + ->when($sourceIds !== null, fn (Builder $query): Builder => $query->whereKey($sourceIds)) + ->get(); $session = StreamSession::query() ->open() @@ -56,4 +70,9 @@ public function openSession(Streamer $streamer): ?array return new StreamSessionStarted($source, $session)->broadcastWith(); } + + private function channelKey(string $platform, string $channelId): string + { + return $platform.':'.$channelId; + } } diff --git a/app-modules/streaming/src/Streamer/Actions/UpdateStreamerSettings.php b/app-modules/streaming/src/Streamer/Actions/UpdateStreamerSettings.php index c29c2a580..59ce3f33c 100644 --- a/app-modules/streaming/src/Streamer/Actions/UpdateStreamerSettings.php +++ b/app-modules/streaming/src/Streamer/Actions/UpdateStreamerSettings.php @@ -5,6 +5,7 @@ namespace He4rt\Streaming\Streamer\Actions; use He4rt\Streaming\Broadcasting\OverlaySettingsUpdated; +use He4rt\Streaming\Broadcasting\OverlaySourcesUpdated; use He4rt\Streaming\Enums\OverlayScene; use He4rt\Streaming\Streamer\Data\StreamerSettings; use He4rt\Streaming\Streamer\Models\Streamer; @@ -24,6 +25,12 @@ public function handle(Streamer $streamer, StreamerSettings $settings): Streamer if ($sceneChanged) { event(new OverlaySettingsUpdated($streamer, $scene, $sceneSettings)); } + + $sceneSourcesChanged = $previous->sceneSources->chosenFor($scene) !== $settings->sceneSources->chosenFor($scene); + + if ($sceneSourcesChanged) { + event(new OverlaySourcesUpdated($streamer, $scene)); + } } return $streamer; diff --git a/app-modules/streaming/src/Streamer/Data/PubSettings.php b/app-modules/streaming/src/Streamer/Data/PubSettings.php new file mode 100644 index 000000000..e399d9c66 --- /dev/null +++ b/app-modules/streaming/src/Streamer/Data/PubSettings.php @@ -0,0 +1,39 @@ +slidoEventHash = $isValidHash ? $slidoEventHash : null; + } + + /** + * @param array $payload + */ + public static function fromArray(array $payload): self + { + $hash = $payload['slido_event_hash'] ?? null; + + return new self(is_string($hash) ? $hash : null); + } + + /** + * @return array{slido_event_hash: string|null} + */ + public function toArray(): array + { + return [ + 'slido_event_hash' => $this->slidoEventHash, + ]; + } +} diff --git a/app-modules/streaming/src/Streamer/Data/SceneSources.php b/app-modules/streaming/src/Streamer/Data/SceneSources.php new file mode 100644 index 000000000..f73bbfa27 --- /dev/null +++ b/app-modules/streaming/src/Streamer/Data/SceneSources.php @@ -0,0 +1,90 @@ +> $sourceIdsByScene scene value => chosen source ids + */ + public function __construct( + public array $sourceIdsByScene = [], + ) {} + + /** + * @param array $payload + */ + public static function fromArray(array $payload): self + { + $sourceIdsByScene = []; + + foreach (OverlayScene::cases() as $scene) { + $sourceIds = $payload[$scene->value] ?? null; + + if (!is_array($sourceIds)) { + continue; + } + + $validIds = array_values(array_filter($sourceIds, fn (mixed $id): bool => is_string($id) && $id !== '')); + + if ($validIds !== []) { + $sourceIdsByScene[$scene->value] = $validIds; + } + } + + return new self($sourceIdsByScene); + } + + /** + * @return list + */ + public function chosenFor(OverlayScene $scene): array + { + return $this->sourceIdsByScene[$scene->value] ?? []; + } + + /** + * Narrows the streamer's sources to the ones the scene uses. + * + * Returns null when the scene uses every source: nothing was chosen, or every chosen source + * is gone. + * + * @param list $existingSourceIds + * @return list|null + */ + public function allowedFor(OverlayScene $scene, array $existingSourceIds): ?array + { + $stillExisting = array_values(array_intersect($this->chosenFor($scene), $existingSourceIds)); + + return $stillExisting === [] ? null : $stillExisting; + } + + /** + * @param list $sourceIds an empty list makes the scene use every source + */ + public function with(OverlayScene $scene, array $sourceIds): self + { + $sourceIdsByScene = $this->sourceIdsByScene; + unset($sourceIdsByScene[$scene->value]); + + $chosenIds = array_values(array_unique($sourceIds)); + + if ($chosenIds !== []) { + $sourceIdsByScene[$scene->value] = $chosenIds; + } + + return new self($sourceIdsByScene); + } + + /** + * @return array> + */ + public function toArray(): array + { + return $this->sourceIdsByScene; + } +} diff --git a/app-modules/streaming/src/Streamer/Data/StreamerSettings.php b/app-modules/streaming/src/Streamer/Data/StreamerSettings.php index defb838d6..c02ab562e 100644 --- a/app-modules/streaming/src/Streamer/Data/StreamerSettings.php +++ b/app-modules/streaming/src/Streamer/Data/StreamerSettings.php @@ -13,8 +13,10 @@ public function __construct( public StartingSoonSettings $startingSoon = new StartingSoonSettings, public VoiceSettings $voice = new VoiceSettings, public ChatSettings $chat = new ChatSettings, + public PubSettings $pub = new PubSettings, public AlertSettings $alerts = new AlertSettings, public MutedChatters $mutedChatters = new MutedChatters, + public SceneSources $sceneSources = new SceneSources, ) {} /** @@ -25,14 +27,17 @@ public static function fromArray(array $payload): self $scenes = is_array($payload['scenes'] ?? null) ? $payload['scenes'] : []; $alerts = is_array($payload['alerts'] ?? null) ? $payload['alerts'] : []; $mutedChatters = is_array($payload['muted_chatters'] ?? null) ? $payload['muted_chatters'] : []; + $sceneSources = is_array($payload['scene_sources'] ?? null) ? $payload['scene_sources'] : []; return new self( coworking: CoworkingSettings::fromArray(self::scenePayload($scenes, OverlayScene::Coworking)), startingSoon: StartingSoonSettings::fromArray(self::scenePayload($scenes, OverlayScene::StartingSoon)), voice: VoiceSettings::fromArray(self::scenePayload($scenes, OverlayScene::Voice)), chat: ChatSettings::fromArray(self::scenePayload($scenes, OverlayScene::Chat)), + pub: PubSettings::fromArray(self::scenePayload($scenes, OverlayScene::Pub)), alerts: AlertSettings::fromArray($alerts), mutedChatters: MutedChatters::fromArray($mutedChatters), + sceneSources: SceneSources::fromArray($sceneSources), ); } @@ -43,6 +48,7 @@ public function forScene(OverlayScene $scene): SceneSettings OverlayScene::StartingSoon => $this->startingSoon, OverlayScene::Voice => $this->voice, OverlayScene::Chat => $this->chat, + OverlayScene::Pub => $this->pub, }; } @@ -53,23 +59,33 @@ public function withScene(SceneSettings $settings): self startingSoon: $settings instanceof StartingSoonSettings ? $settings : $this->startingSoon, voice: $settings instanceof VoiceSettings ? $settings : $this->voice, chat: $settings instanceof ChatSettings ? $settings : $this->chat, + pub: $settings instanceof PubSettings ? $settings : $this->pub, alerts: $this->alerts, mutedChatters: $this->mutedChatters, + sceneSources: $this->sceneSources, ); } public function withAlerts(AlertSettings $alerts): self { - return new self($this->coworking, $this->startingSoon, $this->voice, $this->chat, $alerts, $this->mutedChatters); + return new self($this->coworking, $this->startingSoon, $this->voice, $this->chat, $this->pub, $alerts, $this->mutedChatters, $this->sceneSources); } public function withMutedChatters(MutedChatters $mutedChatters): self { - return new self($this->coworking, $this->startingSoon, $this->voice, $this->chat, $this->alerts, $mutedChatters); + return new self($this->coworking, $this->startingSoon, $this->voice, $this->chat, $this->pub, $this->alerts, $mutedChatters, $this->sceneSources); } /** - * @return array{scenes: array>, alerts: array, muted_chatters: list} + * @param list $sourceIds an empty list makes the scene use every source + */ + public function withSceneSources(OverlayScene $scene, array $sourceIds): self + { + return new self($this->coworking, $this->startingSoon, $this->voice, $this->chat, $this->pub, $this->alerts, $this->mutedChatters, $this->sceneSources->with($scene, $sourceIds)); + } + + /** + * @return array{scenes: array>, alerts: array, muted_chatters: list, scene_sources: array>} */ public function toArray(): array { @@ -83,6 +99,7 @@ public function toArray(): array 'scenes' => $scenes, 'alerts' => $this->alerts->toArray(), 'muted_chatters' => $this->mutedChatters->toArray(), + 'scene_sources' => $this->sceneSources->toArray(), ]; } diff --git a/app-modules/streaming/src/Streamer/Models/Streamer.php b/app-modules/streaming/src/Streamer/Models/Streamer.php index d09dbd7e7..1a7dd8069 100644 --- a/app-modules/streaming/src/Streamer/Models/Streamer.php +++ b/app-modules/streaming/src/Streamer/Models/Streamer.php @@ -7,6 +7,7 @@ use Carbon\CarbonInterface; use He4rt\Identity\User\Models\User; use He4rt\Streaming\Database\Factories\StreamerFactory; +use He4rt\Streaming\Enums\OverlayScene; use He4rt\Streaming\Enums\StreamerStatus; use He4rt\Streaming\Session\Models\StreamSession; use He4rt\Streaming\Streamer\Casts\AsStreamerSettings; @@ -79,6 +80,19 @@ public function isLive(): bool return StreamSession::query()->open()->whereBelongsTo($this)->exists(); } + /** + * The sources a scene uses, or null when it uses every source. + * + * @return list|null + */ + public function sourceIdsForScene(OverlayScene $scene): ?array + { + /** @var list $existingSourceIds */ + $existingSourceIds = $this->sources()->pluck('id')->all(); + + return $this->settings->sceneSources->allowedFor($scene, $existingSourceIds); + } + public function overlayChannel(): string { return sprintf( diff --git a/app-modules/streaming/tests/Feature/Chat/RecordChatMessageTest.php b/app-modules/streaming/tests/Feature/Chat/RecordChatMessageTest.php index cfa7c99c4..d308601c3 100644 --- a/app-modules/streaming/tests/Feature/Chat/RecordChatMessageTest.php +++ b/app-modules/streaming/tests/Feature/Chat/RecordChatMessageTest.php @@ -59,6 +59,7 @@ function chatMessageFor(StreamerSource $source, array $overrides = []): Incoming ->and(ChatMessageMetadata::fromArray($message?->metadata ?? [])->displayName)->toBe('MariaCoda'); Event::assertDispatched(fn (ChatMessageReceived $broadcast): bool => $broadcast->broadcastAs() === 'chat.message' && $broadcast->broadcastWith() === [ + 'sourceId' => $source->id, 'msgId' => 'msg-1', 'chatterId' => '9911', 'username' => 'MariaCoda', diff --git a/app-modules/streaming/tests/Feature/StreamEvent/RecordStreamEventTest.php b/app-modules/streaming/tests/Feature/StreamEvent/RecordStreamEventTest.php index 23a407156..c775a3245 100644 --- a/app-modules/streaming/tests/Feature/StreamEvent/RecordStreamEventTest.php +++ b/app-modules/streaming/tests/Feature/StreamEvent/RecordStreamEventTest.php @@ -46,6 +46,7 @@ function incomingEventFor(StreamerSource $source, array $overrides = []): Incomi Event::assertDispatched(fn (AlertTriggered $alert): bool => $alert->broadcastOn()[0]->name === 'private-'.$source->streamer->overlayChannel() && $alert->broadcastAs() === 'alert.triggered' && $alert->broadcastWith() === [ + 'sourceId' => $source->id, 'type' => 'follow', 'actor' => ['login' => 'mariacoda', 'displayName' => 'MariaCoda'], 'details' => null, diff --git a/app-modules/streaming/tests/Feature/Streamer/UpdateStreamerSettingsTest.php b/app-modules/streaming/tests/Feature/Streamer/UpdateStreamerSettingsTest.php index 779a80852..13dfd2cfd 100644 --- a/app-modules/streaming/tests/Feature/Streamer/UpdateStreamerSettingsTest.php +++ b/app-modules/streaming/tests/Feature/Streamer/UpdateStreamerSettingsTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use He4rt\Streaming\Broadcasting\OverlaySettingsUpdated; +use He4rt\Streaming\Broadcasting\OverlaySourcesUpdated; use He4rt\Streaming\Enums\OverlayScene; use He4rt\Streaming\Enums\StreamEventType; use He4rt\Streaming\Streamer\Actions\UpdateStreamerSettings; @@ -11,7 +12,7 @@ use Illuminate\Support\Facades\Event; beforeEach(function (): void { - Event::fake([OverlaySettingsUpdated::class]); + Event::fake([OverlaySettingsUpdated::class, OverlaySourcesUpdated::class]); }); test('salvar uma cena grava e avisa só a overlay dessa cena', function (): void { @@ -39,3 +40,15 @@ expect($streamer->refresh()->settings->alerts->isEnabled(StreamEventType::Raid))->toBeFalse(); Event::assertNotDispatched(OverlaySettingsUpdated::class); }); + +test('mudar as fontes de uma cena manda só essa overlay recarregar', function (): void { + $streamer = Streamer::factory()->create(); + + resolve(UpdateStreamerSettings::class)->handle($streamer, $streamer->settings->withSceneSources(OverlayScene::Pub, ['fonte-he4rtdevs'])); + + expect($streamer->refresh()->settings->sceneSources->chosenFor(OverlayScene::Pub))->toBe(['fonte-he4rtdevs']); + Event::assertDispatchedTimes(OverlaySourcesUpdated::class, 1); + Event::assertDispatched(fn (OverlaySourcesUpdated $broadcast): bool => $broadcast->scene === OverlayScene::Pub + && $broadcast->broadcastAs() === 'sources.updated'); + Event::assertNotDispatched(OverlaySettingsUpdated::class); +}); diff --git a/app-modules/streaming/tests/Unit/Streamer/PubSettingsTest.php b/app-modules/streaming/tests/Unit/Streamer/PubSettingsTest.php new file mode 100644 index 000000000..d21ae7b32 --- /dev/null +++ b/app-modules/streaming/tests/Unit/Streamer/PubSettingsTest.php @@ -0,0 +1,24 @@ + $hash])->slidoEventHash)->toBe($expected); +})->with([ + 'hash válido' => ['jC9L7Lu93Vw3ssNhB92Pvb', 'jC9L7Lu93Vw3ssNhB92Pvb'], + 'sem hash' => [null, null], + 'url no lugar do hash' => ['https://app.sli.do/event/jC9L7Lu93Vw3ssNhB92Pvb', null], +]); + +test('a cena da He4rt Pub entra nas configurações do streamer sem mexer nas outras', function (): void { + $settings = new StreamerSettings()->withScene(new PubSettings('jC9L7Lu93Vw3ssNhB92Pvb')); + + $restored = StreamerSettings::fromArray($settings->toArray()); + + expect($restored->forScene(OverlayScene::Pub)->toArray())->toBe(['slido_event_hash' => 'jC9L7Lu93Vw3ssNhB92Pvb']) + ->and($restored->chat->toArray())->toBe(new StreamerSettings()->chat->toArray()); +}); diff --git a/app-modules/streaming/tests/Unit/Streamer/SceneSourcesTest.php b/app-modules/streaming/tests/Unit/Streamer/SceneSourcesTest.php new file mode 100644 index 000000000..68338554b --- /dev/null +++ b/app-modules/streaming/tests/Unit/Streamer/SceneSourcesTest.php @@ -0,0 +1,32 @@ +allowedFor(OverlayScene::Pub, ['fonte-a', 'fonte-b']))->toBeNull(); +}); + +test('a cena usa só as fontes escolhidas que ainda existem', function (): void { + $sceneSources = new SceneSources()->with(OverlayScene::Pub, ['fonte-a', 'fonte-sumiu']); + + expect($sceneSources->allowedFor(OverlayScene::Pub, ['fonte-a', 'fonte-b']))->toBe(['fonte-a']) + ->and($sceneSources->allowedFor(OverlayScene::Pub, ['fonte-b']))->toBeNull() + ->and($sceneSources->allowedFor(OverlayScene::Chat, ['fonte-a']))->toBeNull(); +}); + +test('desmarcar todas as fontes volta a cena para todas', function (): void { + $sceneSources = new SceneSources()->with(OverlayScene::Pub, ['fonte-a'])->with(OverlayScene::Pub, []); + + expect($sceneSources->toArray())->toBeEmpty(); +}); + +test('as fontes por cena sobrevivem ao JSON das configurações e ignoram lixo', function (): void { + $settings = new StreamerSettings()->withSceneSources(OverlayScene::Pub, ['fonte-a']); + $payload = [...$settings->toArray(), 'scene_sources' => [...$settings->toArray()['scene_sources'], 'chat' => [42, ''], 'cena-inexistente' => ['fonte-b']]]; + + expect(StreamerSettings::fromArray($payload)->sceneSources->toArray())->toBe(['pub' => ['fonte-a']]); +}); diff --git a/composer.json b/composer.json index ecdc67069..7d1be59fb 100644 --- a/composer.json +++ b/composer.json @@ -28,6 +28,7 @@ "he4rt/integration-devto": "^1.0.0", "he4rt/integration-discord": "^1.0.0", "he4rt/integration-github": "^1.0.0", + "he4rt/integration-slido": "^1.0.0", "he4rt/integration-twitch": "^1.0.0", "he4rt/integration-whatsapp": "^1.0.0", "he4rt/marketing": "^1.0.0", diff --git a/composer.lock b/composer.lock index cd0e45f87..a25ca541d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "3044d4f3dddf69acd834eca1f013788a", + "content-hash": "aa7135b29ba87c893a738e20a3e8844b", "packages": [ { "name": "anourvalar/eloquent-serialize", @@ -3860,6 +3860,47 @@ "relative": true } }, + { + "name": "he4rt/integration-slido", + "version": "1.0.0", + "dist": { + "type": "path", + "url": "app-modules/integration-slido", + "reference": "d41d5a7edb9e555208fa461a3226db283102ff14" + }, + "require": { + "ratchet/pawl": "^0.4.3", + "react/event-loop": "^1.6.0", + "saloonphp/saloon": "^4.5.0" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "He4rt\\IntegrationSlido\\IntegrationSlidoServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "He4rt\\IntegrationSlido\\": "src/", + "He4rt\\IntegrationSlido\\Database\\Factories\\": "database/factories/", + "He4rt\\IntegrationSlido\\Database\\Seeders\\": "database/seeders/" + } + }, + "autoload-dev": { + "psr-4": { + "He4rt\\IntegrationSlido\\Tests\\": "tests/" + } + }, + "license": [ + "proprietary" + ], + "transport-options": { + "symlink": true, + "relative": true + } + }, { "name": "he4rt/integration-twitch", "version": "1.0",