From 03535114443c6715854b4101e6f54b8d7e68e5a3 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 15:41:37 -0300 Subject: [PATCH 01/15] =?UTF-8?q?feat(integration-slido):=20cliente=20do?= =?UTF-8?q?=20Slido=20com=20token=20an=C3=B4nimo=20de=20participante?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolve o evento pelo hash, emite o token de participante pelo fluxo authorize/default com PKCE (sem cookie e sem conta de admin), renova pelo refresh token e lista as perguntas visíveis da seção ativa com as respostas fixadas pelo moderador. --- .../workflow/02-triage-labels.blade.php | 1 + app-modules/integration-slido/composer.json | 27 +++ .../config/integration-slido.php | 11 + .../database/factories/.gitkeep | 0 .../database/migrations/.gitkeep | 0 .../database/seeders/.gitkeep | 0 .../integration-slido/phpstan.ignore.neon | 2 + app-modules/integration-slido/phpstan.neon | 6 + .../integration-slido/src/Data/SlidoEvent.php | 51 +++++ .../src/Data/SlidoEventLocation.php | 24 +++ .../src/Data/SlidoParticipantToken.php | 47 +++++ .../src/Data/SlidoQuestion.php | 108 ++++++++++ .../integration-slido/src/Data/SlidoReply.php | 50 +++++ .../src/Exceptions/SlidoResponseInvalid.php | 15 ++ .../src/IntegrationSlidoServiceProvider.php | 26 +++ .../Requests/AuthorizeParticipant.php | 51 +++++ .../Requests/ExchangeAuthorizationCode.php | 43 ++++ .../src/Transport/Requests/GetEvent.php | 20 ++ .../src/Transport/Requests/GetEventByHash.php | 28 +++ .../src/Transport/Requests/GetQuestions.php | 36 ++++ .../src/Transport/Requests/LookupEvent.php | 20 ++ .../Requests/RefreshParticipantToken.php | 39 ++++ .../src/Transport/SlidoAuthConnector.php | 37 ++++ .../src/Transport/SlidoClient.php | 146 ++++++++++++++ .../src/Transport/SlidoLookupConnector.php | 34 ++++ .../src/Transport/SlidoWallConnector.php | 42 ++++ .../integration-slido/tests/Feature/.gitkeep | 0 .../tests/Feature/SlidoClientTest.php | 189 ++++++++++++++++++ .../integration-slido/tests/Unit/.gitkeep | 0 composer.json | 1 + composer.lock | 38 +++- 31 files changed, 1091 insertions(+), 1 deletion(-) create mode 100644 app-modules/integration-slido/composer.json create mode 100644 app-modules/integration-slido/config/integration-slido.php create mode 100644 app-modules/integration-slido/database/factories/.gitkeep create mode 100644 app-modules/integration-slido/database/migrations/.gitkeep create mode 100644 app-modules/integration-slido/database/seeders/.gitkeep create mode 100644 app-modules/integration-slido/phpstan.ignore.neon create mode 100644 app-modules/integration-slido/phpstan.neon create mode 100644 app-modules/integration-slido/src/Data/SlidoEvent.php create mode 100644 app-modules/integration-slido/src/Data/SlidoEventLocation.php create mode 100644 app-modules/integration-slido/src/Data/SlidoParticipantToken.php create mode 100644 app-modules/integration-slido/src/Data/SlidoQuestion.php create mode 100644 app-modules/integration-slido/src/Data/SlidoReply.php create mode 100644 app-modules/integration-slido/src/Exceptions/SlidoResponseInvalid.php create mode 100644 app-modules/integration-slido/src/IntegrationSlidoServiceProvider.php create mode 100644 app-modules/integration-slido/src/Transport/Requests/AuthorizeParticipant.php create mode 100644 app-modules/integration-slido/src/Transport/Requests/ExchangeAuthorizationCode.php create mode 100644 app-modules/integration-slido/src/Transport/Requests/GetEvent.php create mode 100644 app-modules/integration-slido/src/Transport/Requests/GetEventByHash.php create mode 100644 app-modules/integration-slido/src/Transport/Requests/GetQuestions.php create mode 100644 app-modules/integration-slido/src/Transport/Requests/LookupEvent.php create mode 100644 app-modules/integration-slido/src/Transport/Requests/RefreshParticipantToken.php create mode 100644 app-modules/integration-slido/src/Transport/SlidoAuthConnector.php create mode 100644 app-modules/integration-slido/src/Transport/SlidoClient.php create mode 100644 app-modules/integration-slido/src/Transport/SlidoLookupConnector.php create mode 100644 app-modules/integration-slido/src/Transport/SlidoWallConnector.php create mode 100644 app-modules/integration-slido/tests/Feature/.gitkeep create mode 100644 app-modules/integration-slido/tests/Feature/SlidoClientTest.php create mode 100644 app-modules/integration-slido/tests/Unit/.gitkeep 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..03b7764af --- /dev/null +++ b/app-modules/integration-slido/composer.json @@ -0,0 +1,27 @@ +{ + "name": "he4rt/integration-slido", + "description": "", + "type": "library", + "version": "1.0.0", + "license": "proprietary", + "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/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/SlidoEventLocation.php b/app-modules/integration-slido/src/Data/SlidoEventLocation.php new file mode 100644 index 000000000..b5f81d691 --- /dev/null +++ b/app-modules/integration-slido/src/Data/SlidoEventLocation.php @@ -0,0 +1,24 @@ +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..93e4d1eab --- /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, 0); + } +} 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..7eb4f2ef3 --- /dev/null +++ b/app-modules/integration-slido/src/Data/SlidoQuestion.php @@ -0,0 +1,108 @@ + $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 = is_string($payload['date_created'] ?? null) ? $payload['date_created'] : 'now'; + $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: CarbonImmutable::parse($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), + ]; + } + + /** + * @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/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'), + )); + } +} 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/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/Unit/.gitkeep b/app-modules/integration-slido/tests/Unit/.gitkeep new file mode 100644 index 000000000..e69de29bb 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..ed6a0b156 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,42 @@ "relative": true } }, + { + "name": "he4rt/integration-slido", + "version": "1.0.0", + "dist": { + "type": "path", + "url": "app-modules/integration-slido", + "reference": "78a17dedc2e5592ee5c59747d39aaeb6d1ed9cb1" + }, + "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", From c5ced9f4055d3ecd7693a8f26ac3abe9b9848c27 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 15:46:42 -0300 Subject: [PATCH 02/15] feat(integration-slido): worker slido:listen que leva as perguntas para a overlay MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mantém o socket.io do Slido aberto com a Origin do wall, assina o evento com o token de participante, renova o token antes de expirar (emite um novo se o refresh for recusado) e reconecta com backoff. Cada pergunta vira broadcast no canal privado da overlay do streamer: pub.questions (sync ao conectar), pub.question (snapshot) e pub.question-patch (voto e ação do moderador). Eventos que o Slido mandar e ainda não estiverem mapeados vão para o log. --- .../src/Broadcasting/SlidoQuestionChanged.php | 43 +++++ .../src/Broadcasting/SlidoQuestionPatched.php | 43 +++++ .../src/Broadcasting/SlidoQuestionsSynced.php | 46 +++++ .../src/Console/ListenSlidoEventCommand.php | 141 ++++++++++++++ .../src/Data/SlidoQuestionPatch.php | 54 ++++++ .../src/IntegrationSlidoServiceProvider.php | 8 + .../src/Stream/FrameKind.php | 17 ++ .../src/Stream/QuestionFeed.php | 49 +++++ .../src/Stream/SlidoStreamSession.php | 150 +++++++++++++++ .../src/Stream/SocketIoFrame.php | 99 ++++++++++ .../tests/Feature/SlidoStreamSessionTest.php | 172 ++++++++++++++++++ .../tests/Unit/SocketIoFrameTest.php | 36 ++++ 12 files changed, 858 insertions(+) create mode 100644 app-modules/integration-slido/src/Broadcasting/SlidoQuestionChanged.php create mode 100644 app-modules/integration-slido/src/Broadcasting/SlidoQuestionPatched.php create mode 100644 app-modules/integration-slido/src/Broadcasting/SlidoQuestionsSynced.php create mode 100644 app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php create mode 100644 app-modules/integration-slido/src/Data/SlidoQuestionPatch.php create mode 100644 app-modules/integration-slido/src/Stream/FrameKind.php create mode 100644 app-modules/integration-slido/src/Stream/QuestionFeed.php create mode 100644 app-modules/integration-slido/src/Stream/SlidoStreamSession.php create mode 100644 app-modules/integration-slido/src/Stream/SocketIoFrame.php create mode 100644 app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php create mode 100644 app-modules/integration-slido/tests/Unit/SocketIoFrameTest.php 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..50bdc0b81 --- /dev/null +++ b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionChanged.php @@ -0,0 +1,43 @@ + */ + public function broadcastOn(): array + { + return [new PrivateChannel($this->streamer->overlayChannel())]; + } + + 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..6be733a0a --- /dev/null +++ b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionPatched.php @@ -0,0 +1,43 @@ + */ + public function broadcastOn(): array + { + return [new PrivateChannel($this->streamer->overlayChannel())]; + } + + 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..a5d4c8d46 --- /dev/null +++ b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionsSynced.php @@ -0,0 +1,46 @@ + $questions + */ + public function __construct( + public Streamer $streamer, + public array $questions, + ) {} + + /** @return array */ + public function broadcastOn(): array + { + return [new PrivateChannel($this->streamer->overlayChannel())]; + } + + 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/ListenSlidoEventCommand.php b/app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php new file mode 100644 index 000000000..6056800d3 --- /dev/null +++ b/app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php @@ -0,0 +1,141 @@ +whereHas('user', fn (Builder $query) => $query->where('username', $this->argument('streamer'))) + ->first(); + + if (!$streamer instanceof Streamer) { + $this->error(sprintf("Streamer '%s' não encontrado.", $this->argument('streamer'))); + + return self::FAILURE; + } + + $location = $client->locate((string) $this->argument('event')); + $event = $client->event($location); + + $this->info(sprintf('Escutando "%s" (%s) para a overlay de %s.', $event->name, $location->uuid, $this->argument('streamer'))); + + $session = new SlidoStreamSession($client, $feed, $location, $streamer, fn (string $line) => $this->line(sprintf('[%s] %s', now()->format('H:i:s'), $line))); + + $this->connect($session); + + Loop::run(); + + return self::SUCCESS; + } + + private function connect(SlidoStreamSession $session): void + { + try { + $session->syncQuestions(); + } catch (Throwable $throwable) { + $this->warn('Falhou ao sincronizar as perguntas: '.$throwable->getMessage()); + } + + (new Connector(Loop::get()))($session->streamUrl(), [], ['Origin' => self::ORIGIN])->then( + function (WebSocket $socket) use ($session): void { + $this->socket = $socket; + $this->reconnectAttempts = 0; + $this->scheduleTokenRefresh($session); + + $socket->on('message', function (MessageInterface $message) use ($socket, $session): void { + $this->sendAll($socket, $session->handle((string) $message)); + }); + + $socket->on('close', function (?int $code = null, ?string $reason = null) use ($session): void { + $this->warn(sprintf('Conexão fechada (%s %s).', $code ?? '-', $reason ?? '')); + $this->reconnect($session); + }); + }, + function (Throwable $throwable) use ($session): void { + $this->warn('Falhou ao conectar no Slido: '.$throwable->getMessage()); + $this->reconnect($session); + }, + ); + } + + private function reconnect(SlidoStreamSession $session): void + { + $this->socket = null; + + if ($this->refreshTimer instanceof TimerInterface) { + Loop::cancelTimer($this->refreshTimer); + } + + $delay = min(2 ** $this->reconnectAttempts, self::MAX_RECONNECT_DELAY_SECONDS); + $this->reconnectAttempts++; + + $this->line(sprintf('Reconectando em %ds…', $delay)); + + Loop::addTimer($delay, fn () => $this->connect($session)); + } + + private function scheduleTokenRefresh(SlidoStreamSession $session): void + { + if ($this->refreshTimer instanceof TimerInterface) { + Loop::cancelTimer($this->refreshTimer); + } + + $this->refreshTimer = Loop::addTimer($session->secondsUntilRefresh(), function () use ($session): void { + try { + $frames = $session->refreshToken(); + } catch (Throwable $throwable) { + $this->warn('Falhou ao renovar o token: '.$throwable->getMessage()); + $this->socket?->close(); + + return; + } + + if ($this->socket instanceof WebSocket) { + $this->sendAll($this->socket, $frames); + } + + $this->scheduleTokenRefresh($session); + }); + } + + /** + * @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/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/IntegrationSlidoServiceProvider.php b/app-modules/integration-slido/src/IntegrationSlidoServiceProvider.php index 609085094..092325821 100644 --- a/app-modules/integration-slido/src/IntegrationSlidoServiceProvider.php +++ b/app-modules/integration-slido/src/IntegrationSlidoServiceProvider.php @@ -4,6 +4,7 @@ namespace He4rt\IntegrationSlido; +use He4rt\IntegrationSlido\Console\ListenSlidoEventCommand; use He4rt\IntegrationSlido\Transport\SlidoAuthConnector; use He4rt\IntegrationSlido\Transport\SlidoLookupConnector; use Illuminate\Support\ServiceProvider; @@ -23,4 +24,11 @@ public function register(): void baseUrl: config()->string('integration-slido.lookup_url'), )); } + + public function boot(): void + { + if ($this->app->runningInConsole()) { + $this->commands([ListenSlidoEventCommand::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/SlidoStreamSession.php b/app-modules/integration-slido/src/Stream/SlidoStreamSession.php new file mode 100644 index 000000000..156b138cf --- /dev/null +++ b/app-modules/integration-slido/src/Stream/SlidoStreamSession.php @@ -0,0 +1,150 @@ + mb_substr(md5($this->streamer->getKey()), 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->streamer, $questions)); + + ($this->log)(sprintf('Sincronizou %d pergunta(s) visíveis.', count($questions))); + } + + /** + * @return list + */ + 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), + FrameKind::Event => $this->broadcast($frame), + FrameKind::ConnectError, 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): array + { + ($this->log)($frame->isSubscriptionAccepted() ? 'Assinatura aceita pelo Slido.' : 'Slido recusou a assinatura.'); + + return []; + } + + /** + * @return list + */ + private function broadcast(SocketIoFrame $frame): array + { + $question = $this->feed->questionFrom($frame); + + if ($question instanceof SlidoQuestion) { + event(new SlidoQuestionChanged($this->streamer, $question)); + + return []; + } + + $patch = $this->feed->patchFrom($frame); + + if ($patch instanceof SlidoQuestionPatch) { + event(new SlidoQuestionPatched($this->streamer, $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/SocketIoFrame.php b/app-modules/integration-slido/src/Stream/SocketIoFrame.php new file mode 100644 index 000000000..f14a40efe --- /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(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/tests/Feature/SlidoStreamSessionTest.php b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php new file mode 100644 index 000000000..4d65b1bfc --- /dev/null +++ b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php @@ -0,0 +1,172 @@ + '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'), + streamer: $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']); +}); + +test('envia a pergunta atualizada para o canal da overlay do streamer', function (): void { + $streamer = Streamer::factory()->create(); + $session = streamSession($streamer); + + $session->handle(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' => [], + ])); + + Event::assertDispatched(fn (SlidoQuestionChanged $event): bool => $event->streamer->is($streamer) + && $event->question->id === 122_180_089 + && $event->question->isHighlighted + && $event->broadcastOn()[0]->name === 'private-'.$streamer->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'); +}); 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..81da426bd --- /dev/null +++ b/app-modules/integration-slido/tests/Unit/SocketIoFrameTest.php @@ -0,0 +1,36 @@ +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/"]}]'); +}); From 4b35645a7adb7666188b8300c6417d7349f227f0 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 15:55:08 -0300 Subject: [PATCH 03/15] =?UTF-8?q?feat(panel-overlays):=20cena=20He4rt=20Pu?= =?UTF-8?q?b=20com=20c=C3=A2mera,=20chat,=20perguntas=20do=20Slido=20e=20Q?= =?UTF-8?q?R=20Code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nova cena pub na overlay: a câmera é o maior bloco, o chat ocupa a coluna inteira, o painel de perguntas mostra a pergunta no ar (com a resposta do moderador) ou a fila por votos, e o card traz o QR Code do evento. A edição ativa vem do nome do evento no Slido. O streamer cola o link do Slido no painel (Minha Live > Overlays). A página abre com o evento e as perguntas atuais e depois segue o broadcast do slido:listen, que agora lê o evento da cena quando o hash não é informado. --- .../src/Console/ListenSlidoEventCommand.php | 12 ++- .../src/Data/SlidoEventHash.php | 23 +++++ .../tests/Unit/SlidoEventHashTest.php | 17 ++++ .../Streaming/Pages/StreamOverlaysPage.php | 42 +++++++++ .../Streaming/StreamOverlaySettingsTest.php | 22 +++++ .../panel-overlays/resources/js/feed.ts | 22 ++++- .../resources/js/hooks/useOverlayFeed.ts | 15 +++ .../resources/js/hooks/usePubQuestions.ts | 19 ++++ .../resources/js/lib/overlayChannel.ts | 9 +- .../resources/js/lib/pubQuestions.ts | 34 +++++++ .../resources/js/pages/Overlays/Pub.tsx | 60 ++++++++++++ .../panel-overlays/resources/js/types.ts | 45 ++++++++- .../resources/js/ui/CameraWindow.tsx | 6 +- .../resources/js/ui/chat/ChatPanel.tsx | 7 +- .../resources/js/ui/pub/QrCard.tsx | 31 +++++++ .../resources/js/ui/pub/QuestionsPanel.tsx | 91 +++++++++++++++++++ .../Controllers/ShowOverlayController.php | 4 + .../src/Pub/PubOverlayState.php | 76 ++++++++++++++++ .../tests/Feature/ShowOverlayTest.php | 60 ++++++++++++ app-modules/streaming/CONTEXT.md | 2 +- .../streaming/src/Enums/OverlayScene.php | 4 + .../src/Streamer/Data/PubSettings.php | 39 ++++++++ .../src/Streamer/Data/StreamerSettings.php | 8 +- .../tests/Unit/Streamer/PubSettingsTest.php | 24 +++++ 24 files changed, 660 insertions(+), 12 deletions(-) create mode 100644 app-modules/integration-slido/src/Data/SlidoEventHash.php create mode 100644 app-modules/integration-slido/tests/Unit/SlidoEventHashTest.php create mode 100644 app-modules/panel-overlays/resources/js/hooks/usePubQuestions.ts create mode 100644 app-modules/panel-overlays/resources/js/lib/pubQuestions.ts create mode 100644 app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx create mode 100644 app-modules/panel-overlays/resources/js/ui/pub/QrCard.tsx create mode 100644 app-modules/panel-overlays/resources/js/ui/pub/QuestionsPanel.tsx create mode 100644 app-modules/panel-overlays/src/Pub/PubOverlayState.php create mode 100644 app-modules/streaming/src/Streamer/Data/PubSettings.php create mode 100644 app-modules/streaming/tests/Unit/Streamer/PubSettingsTest.php diff --git a/app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php b/app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php index 6056800d3..b4e5014ab 100644 --- a/app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php +++ b/app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php @@ -20,7 +20,7 @@ use Throwable; #[Description(description: 'Escuta as perguntas de um evento do Slido e envia para a overlay do streamer')] -#[Signature(signature: 'slido:listen {streamer : username do streamer dono da overlay} {event : hash do evento no Slido}')] +#[Signature(signature: 'slido:listen {streamer : username do streamer dono da overlay} {event? : hash do evento no Slido (padrão: o configurado na cena He4rt Pub)}')] final class ListenSlidoEventCommand extends Command { private const string ORIGIN = 'https://wall.sli.do'; @@ -45,7 +45,15 @@ public function handle(SlidoClient $client, QuestionFeed $feed): int return self::FAILURE; } - $location = $client->locate((string) $this->argument('event')); + $eventHash = $this->argument('event') ?? $streamer->settings->pub->slidoEventHash; + + if (!is_string($eventHash) || $eventHash === '') { + $this->error('Nenhum evento do Slido. Passe o hash ou configure a cena He4rt Pub no painel.'); + + return self::FAILURE; + } + + $location = $client->locate($eventHash); $event = $client->event($location); $this->info(sprintf('Escutando "%s" (%s) para a overlay de %s.', $event->name, $location->uuid, $this->argument('streamer'))); 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 @@ +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/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php index 71de36976..59a4095ec 100644 --- a/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php +++ b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php @@ -5,6 +5,7 @@ namespace He4rt\PanelApp\Clusters\Streaming\Pages; use BackedEnum; +use Closure; use Filament\Actions\Action; use Filament\Forms\Components\Radio; use Filament\Forms\Components\TextInput; @@ -15,6 +16,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,6 +30,7 @@ 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; @@ -211,6 +214,44 @@ 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.') + ->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 { + if (!is_string($value) || SlidoEventHash::fromInput($value) === null) { + $fail('Não reconheci esse link do Slido.'); + } + }) + ->required(), + ]) + ->action(function (array $data, UpdateStreamerSettings $updateSettings): void { + $streamer = $this->currentStreamer(); + $slidoEvent = $data['slido_event'] ?? null; + $eventHash = is_string($slidoEvent) ? SlidoEventHash::fromInput($slidoEvent) : null; + + $updateSettings->handle($streamer, $streamer->settings->withScene(new PubSettings($eventHash))); + + Notification::make() + ->title('He4rt Pub atualizada') + ->body('Reinicie o slido:listen para escutar o evento novo.') + ->success() + ->send(); + }); + } + public function testAlertAction(): Action { return Action::make('testAlert') @@ -314,6 +355,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', diff --git a/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php b/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php index c5ca1927e..050132333 100644 --- a/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php +++ b/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php @@ -64,6 +64,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, diff --git a/app-modules/panel-overlays/resources/js/feed.ts b/app-modules/panel-overlays/resources/js/feed.ts index 6cd15048c..17bef580c 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,22 @@ 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 type FeedEventDto = | ChatMessageDto | ChatMessageDeletedDto @@ -157,4 +174,7 @@ export type FeedEventDto = | NowPlayingDto | VoiceRosterDto | OverlayConfigDto - | LevelProgressDto; + | LevelProgressDto + | PubQuestionsDto + | PubQuestionDto + | PubQuestionPatchDto; diff --git a/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts b/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts index 4cfad9a27..99773623b 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,6 +25,9 @@ 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; } export function useOverlayFeed({ channel, authEndpoint }: OverlayChannelSource, handlers: OverlayFeedHandlers): void { @@ -65,5 +71,14 @@ 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; } } 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..6ce55726c 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, @@ -42,6 +42,13 @@ export function subscribeOverlayChannel( .listen('.chat.cleared', () => listener({ kind: 'chatCleared' })) .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 }), ); return () => echo.disconnect(); 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..7a1b70868 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/lib/pubQuestions.ts @@ -0,0 +1,34 @@ +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); +} + +export function pendingCount(questions: SlidoQuestionPayload[]): number { + return questions.filter((question) => !question.isAnswered).length; +} 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..d6fbc3881 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx @@ -0,0 +1,60 @@ +import { useChatMessages } from '../../hooks/useChatMessages'; +import { useOverlayFeed } from '../../hooks/useOverlayFeed'; +import { usePubQuestions } from '../../hooks/usePubQuestions'; +import { toChatBubble } from '../../lib/chat'; +import { toChatMessage } from '../../lib/overlayEvents'; +import { highlightedQuestion, pendingCount, queuedQuestions } from '../../lib/pubQuestions'; +import { CameraWindow } from '../../ui/CameraWindow'; +import { Stage } from '../../ui/Stage'; +import TopBar from '../../ui/TopBar'; +import ChatBubble from '../../ui/chat/ChatBubble'; +import ChatPanel from '../../ui/chat/ChatPanel'; +import QrCard from '../../ui/pub/QrCard'; +import QuestionsPanel from '../../ui/pub/QuestionsPanel'; +import type { PubPageProps } from '../../types'; + +const QUEUE_LIMIT = 3; +const CAMERA_BOTTOM = 262; + +export default function PubOverlay({ handle, channel, authEndpoint, recentChat, pub }: PubPageProps) { + const chat = useChatMessages(recentChat.map(toChatMessage)); + const questions = usePubQuestions(pub?.questions ?? []); + + useOverlayFeed( + { channel, authEndpoint }, + { + onChatMessage: chat.push, + onChatDeleted: chat.remove, + onChatterCleared: chat.removeChatter, + onChatCleared: chat.clear, + onPubQuestions: questions.onSync, + onPubQuestion: questions.onUpsert, + onPubQuestionPatch: questions.onPatch, + }, + ); + + const edition = pub?.event.name ? `HE4RT PUB · ${pub.event.name.toUpperCase()}` : 'HE4RT PUB'; + + return ( + + + + + {chat.messages.map((message) => ( + + ))} + + + + + + + + + ); +} diff --git a/app-modules/panel-overlays/resources/js/types.ts b/app-modules/panel-overlays/resources/js/types.ts index 702af6d6e..5d092b9bc 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; @@ -55,3 +94,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/CameraWindow.tsx b/app-modules/panel-overlays/resources/js/ui/CameraWindow.tsx index 49a44259f..74b86325c 100644 --- a/app-modules/panel-overlays/resources/js/ui/CameraWindow.tsx +++ b/app-modules/panel-overlays/resources/js/ui/CameraWindow.tsx @@ -1,16 +1,18 @@ export interface CameraWindowProps { label?: string; + bottom?: number; } -export function CameraWindow({ label }: CameraWindowProps) { +export function CameraWindow({ label, bottom = 130 }: CameraWindowProps) { return ( <>
+
diff --git a/app-modules/panel-overlays/resources/js/ui/pub/QrCard.tsx b/app-modules/panel-overlays/resources/js/ui/pub/QrCard.tsx new file mode 100644 index 000000000..ce92d5987 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/ui/pub/QrCard.tsx @@ -0,0 +1,31 @@ +import type { SlidoEventPayload } from '../../types'; + +export interface QrCardProps { + event: SlidoEventPayload | null; + qrSvg: string | null; +} + +export function QrCard({ event, qrSvg }: QrCardProps) { + return ( +
+
+
+ MANDE A SUA + + PERGUNTA + + {event ? ( +
+ ou em slido.com + #{event.code} +
+ ) : null} +
+
+ ); +} + +export default QrCard; diff --git a/app-modules/panel-overlays/resources/js/ui/pub/QuestionsPanel.tsx b/app-modules/panel-overlays/resources/js/ui/pub/QuestionsPanel.tsx new file mode 100644 index 000000000..15073220b --- /dev/null +++ b/app-modules/panel-overlays/resources/js/ui/pub/QuestionsPanel.tsx @@ -0,0 +1,91 @@ +import type { SlidoQuestionPayload } from '../../types'; + +export interface QuestionsPanelProps { + highlighted: SlidoQuestionPayload | null; + queue: SlidoQuestionPayload[]; + pending: number; + isConfigured: boolean; +} + +function authorOf(question: SlidoQuestionPayload): string { + return question.authorName ?? 'Anônimo'; +} + +function HighlightedQuestion({ question }: { question: SlidoQuestionPayload }) { + const reply = question.replies.find((candidate) => candidate.isFromModerator) ?? question.replies[0] ?? null; + + return ( +
+

+ {question.text} +

+
+ {authorOf(question).toUpperCase()} + {question.score > 0 ? ▲ {question.score} : null} +
+ {reply ? ( +

+ {reply.text} +

+ ) : null} +
+ ); +} + +function QueuedQuestions({ queue }: { queue: SlidoQuestionPayload[] }) { + return ( +
    + {queue.map((question) => ( +
  • + + ▲ {question.score} + + + {question.text} + + + {authorOf(question)} + +
  • + ))} +
+ ); +} + +function EmptyState({ isConfigured }: { isConfigured: boolean }) { + return ( +
+ {isConfigured + ? 'Nenhuma pergunta ainda. Aponta a câmera do celular pro QR Code ➜' + : 'Configure o evento do Slido na cena He4rt Pub do painel.'} +
+ ); +} + +export function QuestionsPanel({ highlighted, queue, pending, isConfigured }: QuestionsPanelProps) { + const title = highlighted ? 'PERGUNTA NO AR' : 'PERGUNTAS DA GALERA'; + + return ( +
+
+ + {title} +
+ {pending > 0 ? ( +
+ {pending} NA FILA +
+ ) : null} + + {highlighted ? ( + + ) : queue.length > 0 ? ( + + ) : ( + + )} +
+ ); +} + +export default QuestionsPanel; diff --git a/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php b/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php index 846797ebb..8a1649ee9 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,6 +22,7 @@ public function __invoke( OverlayScene $scene, ResolveOverlayToken $resolveToken, OverlayInitialState $initialState, + PubOverlayState $pubState, ): Response { $streamer = $resolveToken->handle($token); @@ -34,6 +36,7 @@ public function __invoke( 'settings' => $streamer->settings->forScene($scene)->toArray(), 'recentChat' => $initialState->recentChat($streamer, self::RECENT_CHAT_LIMIT), 'session' => $initialState->openSession($streamer), + 'pub' => $scene === OverlayScene::Pub ? $pubState->for($streamer) : null, ]); } @@ -44,6 +47,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..5bc188980 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([ @@ -50,8 +63,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 diff --git a/app-modules/streaming/CONTEXT.md b/app-modules/streaming/CONTEXT.md index aee8570f7..1a5f11c40 100644 --- a/app-modules/streaming/CONTEXT.md +++ b/app-modules/streaming/CONTEXT.md @@ -52,7 +52,7 @@ 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. | | **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. | diff --git a/app-modules/streaming/src/Enums/OverlayScene.php b/app-modules/streaming/src/Enums/OverlayScene.php index 4b22a6be9..3d5551564 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,6 +34,7 @@ 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 => 'Câmera, chat, perguntas do Slido e QR Code para o público mandar a pergunta.', }; } @@ -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/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/StreamerSettings.php b/app-modules/streaming/src/Streamer/Data/StreamerSettings.php index defb838d6..7849147d4 100644 --- a/app-modules/streaming/src/Streamer/Data/StreamerSettings.php +++ b/app-modules/streaming/src/Streamer/Data/StreamerSettings.php @@ -13,6 +13,7 @@ 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, ) {} @@ -31,6 +32,7 @@ public static function fromArray(array $payload): self 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), ); @@ -43,6 +45,7 @@ public function forScene(OverlayScene $scene): SceneSettings OverlayScene::StartingSoon => $this->startingSoon, OverlayScene::Voice => $this->voice, OverlayScene::Chat => $this->chat, + OverlayScene::Pub => $this->pub, }; } @@ -53,6 +56,7 @@ 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, ); @@ -60,12 +64,12 @@ public function withScene(SceneSettings $settings): self 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); } 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); } /** 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()); +}); From e622f1883e3de1782f443aa3a942026b671a8d19 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 16:22:28 -0300 Subject: [PATCH 04/15] =?UTF-8?q?feat(panel-overlays):=20dire=C3=A7=C3=A3o?= =?UTF-8?q?=20de=20arte=20da=20He4rt=20Pub=20sobre=20a=20c=C3=A2mera=204K?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A cena pub vira uma camada transparente: a câmera 4K entra inteira como fonte própria no OBS. A identidade segue a arte da edição (preto, amarelo, Barlow Condensed, Poppins e o logo em marcador) e tudo encosta nas bordas para não cobrir a plateia: a pergunta e o QR viram uma doca no canto inferior esquerdo, e o chat com o selo da edição sobe para o canto superior direito, em cima do teto e da parede. O selo lê o número da edição no nome do evento do Slido ("He4rt Pub #5" vira "5ª edição"). --- .../Streaming/StreamOverlayPreviewTest.php | 2 +- .../panel-overlays/resources/css/overlay.css | 27 +++++ .../resources/js/lib/pubEdition.ts | 13 +++ .../resources/js/lib/pubQuestions.ts | 4 - .../resources/js/pages/Overlays/Pub.tsx | 38 ++----- .../resources/js/ui/CameraWindow.tsx | 6 +- .../resources/js/ui/He4rtLogo.tsx | 4 +- .../resources/js/ui/chat/ChatPanel.tsx | 7 +- .../resources/js/ui/pub/PubBrand.tsx | 19 ++++ .../resources/js/ui/pub/PubChat.tsx | 47 ++++++++ .../resources/js/ui/pub/PubDock.tsx | 107 ++++++++++++++++++ .../resources/js/ui/pub/QrCard.tsx | 31 ----- .../resources/js/ui/pub/QuestionsPanel.tsx | 91 --------------- .../streaming/src/Enums/OverlayScene.php | 4 +- 14 files changed, 233 insertions(+), 167 deletions(-) create mode 100644 app-modules/panel-overlays/resources/js/lib/pubEdition.ts create mode 100644 app-modules/panel-overlays/resources/js/ui/pub/PubBrand.tsx create mode 100644 app-modules/panel-overlays/resources/js/ui/pub/PubChat.tsx create mode 100644 app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx delete mode 100644 app-modules/panel-overlays/resources/js/ui/pub/QrCard.tsx delete mode 100644 app-modules/panel-overlays/resources/js/ui/pub/QuestionsPanel.tsx 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-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/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 index 7a1b70868..0a67ece62 100644 --- a/app-modules/panel-overlays/resources/js/lib/pubQuestions.ts +++ b/app-modules/panel-overlays/resources/js/lib/pubQuestions.ts @@ -28,7 +28,3 @@ export function queuedQuestions(questions: SlidoQuestionPayload[], limit: number .sort((a, b) => b.score - a.score || a.createdAt.localeCompare(b.createdAt)) .slice(0, limit); } - -export function pendingCount(questions: SlidoQuestionPayload[]): number { - return questions.filter((question) => !question.isAnswered).length; -} diff --git a/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx index d6fbc3881..14ec01851 100644 --- a/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx @@ -1,22 +1,18 @@ import { useChatMessages } from '../../hooks/useChatMessages'; import { useOverlayFeed } from '../../hooks/useOverlayFeed'; import { usePubQuestions } from '../../hooks/usePubQuestions'; -import { toChatBubble } from '../../lib/chat'; import { toChatMessage } from '../../lib/overlayEvents'; -import { highlightedQuestion, pendingCount, queuedQuestions } from '../../lib/pubQuestions'; -import { CameraWindow } from '../../ui/CameraWindow'; +import { editionLabel } from '../../lib/pubEdition'; +import { highlightedQuestion, queuedQuestions } from '../../lib/pubQuestions'; import { Stage } from '../../ui/Stage'; -import TopBar from '../../ui/TopBar'; -import ChatBubble from '../../ui/chat/ChatBubble'; -import ChatPanel from '../../ui/chat/ChatPanel'; -import QrCard from '../../ui/pub/QrCard'; -import QuestionsPanel from '../../ui/pub/QuestionsPanel'; +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; -const CAMERA_BOTTOM = 262; -export default function PubOverlay({ handle, channel, authEndpoint, recentChat, pub }: PubPageProps) { +export default function PubOverlay({ channel, authEndpoint, recentChat, pub }: PubPageProps) { const chat = useChatMessages(recentChat.map(toChatMessage)); const questions = usePubQuestions(pub?.questions ?? []); @@ -33,28 +29,16 @@ export default function PubOverlay({ handle, channel, authEndpoint, recentChat, }, ); - const edition = pub?.event.name ? `HE4RT PUB · ${pub.event.name.toUpperCase()}` : 'HE4RT PUB'; - return ( - - - - {chat.messages.map((message) => ( - - ))} - - - - - + + - - ); } diff --git a/app-modules/panel-overlays/resources/js/ui/CameraWindow.tsx b/app-modules/panel-overlays/resources/js/ui/CameraWindow.tsx index 74b86325c..49a44259f 100644 --- a/app-modules/panel-overlays/resources/js/ui/CameraWindow.tsx +++ b/app-modules/panel-overlays/resources/js/ui/CameraWindow.tsx @@ -1,18 +1,16 @@ export interface CameraWindowProps { label?: string; - bottom?: number; } -export function CameraWindow({ label, bottom = 130 }: CameraWindowProps) { +export function CameraWindow({ label }: CameraWindowProps) { return ( <>
+
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..b6107a049 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubBrand.tsx @@ -0,0 +1,19 @@ +import { PATH_A, PATH_B } from '../He4rtLogo'; + +export function PubBrand() { + return ( +
+ + + + + He4rtPub + +
+ ); +} + +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..1a0e62e45 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubChat.tsx @@ -0,0 +1,47 @@ +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..d147fbbf6 --- /dev/null +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx @@ -0,0 +1,107 @@ +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 moderatorReplyOf(question: SlidoQuestionPayload): string | null { + return question.replies.find((reply) => reply.isFromModerator)?.text ?? null; +} + +function QuestionOnAir({ question }: { question: SlidoQuestionPayload }) { + const reply = moderatorReplyOf(question); + + return ( + <> +
+ {authorOf(question)} pergunta + ▲ {question.score} +
+
+ {question.text} +
+ {reply ? ( +
+ Moderação: {reply} +
+ ) : null} + + ); +} + +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/resources/js/ui/pub/QrCard.tsx b/app-modules/panel-overlays/resources/js/ui/pub/QrCard.tsx deleted file mode 100644 index ce92d5987..000000000 --- a/app-modules/panel-overlays/resources/js/ui/pub/QrCard.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import type { SlidoEventPayload } from '../../types'; - -export interface QrCardProps { - event: SlidoEventPayload | null; - qrSvg: string | null; -} - -export function QrCard({ event, qrSvg }: QrCardProps) { - return ( -
-
-
- MANDE A SUA - - PERGUNTA - - {event ? ( -
- ou em slido.com - #{event.code} -
- ) : null} -
-
- ); -} - -export default QrCard; diff --git a/app-modules/panel-overlays/resources/js/ui/pub/QuestionsPanel.tsx b/app-modules/panel-overlays/resources/js/ui/pub/QuestionsPanel.tsx deleted file mode 100644 index 15073220b..000000000 --- a/app-modules/panel-overlays/resources/js/ui/pub/QuestionsPanel.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import type { SlidoQuestionPayload } from '../../types'; - -export interface QuestionsPanelProps { - highlighted: SlidoQuestionPayload | null; - queue: SlidoQuestionPayload[]; - pending: number; - isConfigured: boolean; -} - -function authorOf(question: SlidoQuestionPayload): string { - return question.authorName ?? 'Anônimo'; -} - -function HighlightedQuestion({ question }: { question: SlidoQuestionPayload }) { - const reply = question.replies.find((candidate) => candidate.isFromModerator) ?? question.replies[0] ?? null; - - return ( -
-

- {question.text} -

-
- {authorOf(question).toUpperCase()} - {question.score > 0 ? ▲ {question.score} : null} -
- {reply ? ( -

- {reply.text} -

- ) : null} -
- ); -} - -function QueuedQuestions({ queue }: { queue: SlidoQuestionPayload[] }) { - return ( -
    - {queue.map((question) => ( -
  • - - ▲ {question.score} - - - {question.text} - - - {authorOf(question)} - -
  • - ))} -
- ); -} - -function EmptyState({ isConfigured }: { isConfigured: boolean }) { - return ( -
- {isConfigured - ? 'Nenhuma pergunta ainda. Aponta a câmera do celular pro QR Code ➜' - : 'Configure o evento do Slido na cena He4rt Pub do painel.'} -
- ); -} - -export function QuestionsPanel({ highlighted, queue, pending, isConfigured }: QuestionsPanelProps) { - const title = highlighted ? 'PERGUNTA NO AR' : 'PERGUNTAS DA GALERA'; - - return ( -
-
- - {title} -
- {pending > 0 ? ( -
- {pending} NA FILA -
- ) : null} - - {highlighted ? ( - - ) : queue.length > 0 ? ( - - ) : ( - - )} -
- ); -} - -export default QuestionsPanel; diff --git a/app-modules/streaming/src/Enums/OverlayScene.php b/app-modules/streaming/src/Enums/OverlayScene.php index 3d5551564..a67840bd8 100644 --- a/app-modules/streaming/src/Enums/OverlayScene.php +++ b/app-modules/streaming/src/Enums/OverlayScene.php @@ -34,13 +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 => 'Câmera, chat, perguntas do Slido e QR Code para o público mandar a pergunta.', + 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 From 79859616c1f60eaa7e1b5b10341fc915ad5f7a40 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 16:34:00 -0300 Subject: [PATCH 05/15] feat(integration-slido): slido:serve conecta sozinho nos eventos com overlay aberta MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O slido:listen escutava um evento fixo de um streamer e precisava ser reiniciado a cada troca de link. O slido:serve roda como um processo só, ao lado do Reverb, e a cada 15 s confere quais streamers ativos têm um evento do Slido na cena He4rt Pub e uma overlay aberta. Ele conecta nos eventos novos, desconecta quando a overlay fecha e troca de evento quando o link muda no painel. Um evento usado por dois streamers abre um socket só, e o broadcast vai para o canal de cada overlay. Quando o Reverb não responde a contagem, o streamer continua na lista: é melhor gastar um participante anônimo do que perder as perguntas no meio da live. --- .../src/Broadcasting/SlidoQuestionChanged.php | 7 +- .../src/Broadcasting/SlidoQuestionPatched.php | 7 +- .../src/Broadcasting/SlidoQuestionsSynced.php | 5 +- .../src/Console/ListenSlidoEventCommand.php | 149 ----------------- .../src/Console/ServeSlidoEventsCommand.php | 102 ++++++++++++ .../src/IntegrationSlidoServiceProvider.php | 4 +- .../src/Stream/SlidoAudience.php | 49 ++++++ .../src/Stream/SlidoConnection.php | 154 ++++++++++++++++++ .../src/Stream/SlidoStreamSession.php | 19 ++- .../src/Stream/SlidoSubscriptionPlan.php | 32 ++++ .../tests/Feature/SlidoAudienceTest.php | 68 ++++++++ .../tests/Feature/SlidoStreamSessionTest.php | 39 +++-- .../tests/Unit/SlidoSubscriptionPlanTest.php | 28 ++++ .../Streaming/Pages/StreamOverlaysPage.php | 2 +- app-modules/streaming/README.md | 5 + 15 files changed, 497 insertions(+), 173 deletions(-) delete mode 100644 app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php create mode 100644 app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php create mode 100644 app-modules/integration-slido/src/Stream/SlidoAudience.php create mode 100644 app-modules/integration-slido/src/Stream/SlidoConnection.php create mode 100644 app-modules/integration-slido/src/Stream/SlidoSubscriptionPlan.php create mode 100644 app-modules/integration-slido/tests/Feature/SlidoAudienceTest.php create mode 100644 app-modules/integration-slido/tests/Unit/SlidoSubscriptionPlanTest.php diff --git a/app-modules/integration-slido/src/Broadcasting/SlidoQuestionChanged.php b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionChanged.php index 50bdc0b81..b478bd925 100644 --- a/app-modules/integration-slido/src/Broadcasting/SlidoQuestionChanged.php +++ b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionChanged.php @@ -17,15 +17,18 @@ final class SlidoQuestionChanged implements ShouldBroadcastNow, ShouldRescue use Dispatchable; use InteractsWithSockets; + /** + * @param list $streamers + */ public function __construct( - public Streamer $streamer, + public array $streamers, public SlidoQuestion $question, ) {} /** @return array */ public function broadcastOn(): array { - return [new PrivateChannel($this->streamer->overlayChannel())]; + return array_map(fn (Streamer $streamer): PrivateChannel => new PrivateChannel($streamer->overlayChannel()), $this->streamers); } public function broadcastAs(): string diff --git a/app-modules/integration-slido/src/Broadcasting/SlidoQuestionPatched.php b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionPatched.php index 6be733a0a..dcc09fc76 100644 --- a/app-modules/integration-slido/src/Broadcasting/SlidoQuestionPatched.php +++ b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionPatched.php @@ -17,15 +17,18 @@ final class SlidoQuestionPatched implements ShouldBroadcastNow, ShouldRescue use Dispatchable; use InteractsWithSockets; + /** + * @param list $streamers + */ public function __construct( - public Streamer $streamer, + public array $streamers, public SlidoQuestionPatch $patch, ) {} /** @return array */ public function broadcastOn(): array { - return [new PrivateChannel($this->streamer->overlayChannel())]; + return array_map(fn (Streamer $streamer): PrivateChannel => new PrivateChannel($streamer->overlayChannel()), $this->streamers); } public function broadcastAs(): string diff --git a/app-modules/integration-slido/src/Broadcasting/SlidoQuestionsSynced.php b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionsSynced.php index a5d4c8d46..78970e082 100644 --- a/app-modules/integration-slido/src/Broadcasting/SlidoQuestionsSynced.php +++ b/app-modules/integration-slido/src/Broadcasting/SlidoQuestionsSynced.php @@ -18,17 +18,18 @@ final class SlidoQuestionsSynced implements ShouldBroadcastNow, ShouldRescue use InteractsWithSockets; /** + * @param list $streamers * @param list $questions */ public function __construct( - public Streamer $streamer, + public array $streamers, public array $questions, ) {} /** @return array */ public function broadcastOn(): array { - return [new PrivateChannel($this->streamer->overlayChannel())]; + return array_map(fn (Streamer $streamer): PrivateChannel => new PrivateChannel($streamer->overlayChannel()), $this->streamers); } public function broadcastAs(): string diff --git a/app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php b/app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php deleted file mode 100644 index b4e5014ab..000000000 --- a/app-modules/integration-slido/src/Console/ListenSlidoEventCommand.php +++ /dev/null @@ -1,149 +0,0 @@ -whereHas('user', fn (Builder $query) => $query->where('username', $this->argument('streamer'))) - ->first(); - - if (!$streamer instanceof Streamer) { - $this->error(sprintf("Streamer '%s' não encontrado.", $this->argument('streamer'))); - - return self::FAILURE; - } - - $eventHash = $this->argument('event') ?? $streamer->settings->pub->slidoEventHash; - - if (!is_string($eventHash) || $eventHash === '') { - $this->error('Nenhum evento do Slido. Passe o hash ou configure a cena He4rt Pub no painel.'); - - return self::FAILURE; - } - - $location = $client->locate($eventHash); - $event = $client->event($location); - - $this->info(sprintf('Escutando "%s" (%s) para a overlay de %s.', $event->name, $location->uuid, $this->argument('streamer'))); - - $session = new SlidoStreamSession($client, $feed, $location, $streamer, fn (string $line) => $this->line(sprintf('[%s] %s', now()->format('H:i:s'), $line))); - - $this->connect($session); - - Loop::run(); - - return self::SUCCESS; - } - - private function connect(SlidoStreamSession $session): void - { - try { - $session->syncQuestions(); - } catch (Throwable $throwable) { - $this->warn('Falhou ao sincronizar as perguntas: '.$throwable->getMessage()); - } - - (new Connector(Loop::get()))($session->streamUrl(), [], ['Origin' => self::ORIGIN])->then( - function (WebSocket $socket) use ($session): void { - $this->socket = $socket; - $this->reconnectAttempts = 0; - $this->scheduleTokenRefresh($session); - - $socket->on('message', function (MessageInterface $message) use ($socket, $session): void { - $this->sendAll($socket, $session->handle((string) $message)); - }); - - $socket->on('close', function (?int $code = null, ?string $reason = null) use ($session): void { - $this->warn(sprintf('Conexão fechada (%s %s).', $code ?? '-', $reason ?? '')); - $this->reconnect($session); - }); - }, - function (Throwable $throwable) use ($session): void { - $this->warn('Falhou ao conectar no Slido: '.$throwable->getMessage()); - $this->reconnect($session); - }, - ); - } - - private function reconnect(SlidoStreamSession $session): void - { - $this->socket = null; - - if ($this->refreshTimer instanceof TimerInterface) { - Loop::cancelTimer($this->refreshTimer); - } - - $delay = min(2 ** $this->reconnectAttempts, self::MAX_RECONNECT_DELAY_SECONDS); - $this->reconnectAttempts++; - - $this->line(sprintf('Reconectando em %ds…', $delay)); - - Loop::addTimer($delay, fn () => $this->connect($session)); - } - - private function scheduleTokenRefresh(SlidoStreamSession $session): void - { - if ($this->refreshTimer instanceof TimerInterface) { - Loop::cancelTimer($this->refreshTimer); - } - - $this->refreshTimer = Loop::addTimer($session->secondsUntilRefresh(), function () use ($session): void { - try { - $frames = $session->refreshToken(); - } catch (Throwable $throwable) { - $this->warn('Falhou ao renovar o token: '.$throwable->getMessage()); - $this->socket?->close(); - - return; - } - - if ($this->socket instanceof WebSocket) { - $this->sendAll($this->socket, $frames); - } - - $this->scheduleTokenRefresh($session); - }); - } - - /** - * @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/Console/ServeSlidoEventsCommand.php b/app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php new file mode 100644 index 000000000..07277ea4d --- /dev/null +++ b/app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php @@ -0,0 +1,102 @@ + */ + 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(array_keys($audience), array_keys($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(); + } + + 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/IntegrationSlidoServiceProvider.php b/app-modules/integration-slido/src/IntegrationSlidoServiceProvider.php index 092325821..a360cc1c8 100644 --- a/app-modules/integration-slido/src/IntegrationSlidoServiceProvider.php +++ b/app-modules/integration-slido/src/IntegrationSlidoServiceProvider.php @@ -4,7 +4,7 @@ namespace He4rt\IntegrationSlido; -use He4rt\IntegrationSlido\Console\ListenSlidoEventCommand; +use He4rt\IntegrationSlido\Console\ServeSlidoEventsCommand; use He4rt\IntegrationSlido\Transport\SlidoAuthConnector; use He4rt\IntegrationSlido\Transport\SlidoLookupConnector; use Illuminate\Support\ServiceProvider; @@ -28,7 +28,7 @@ public function register(): void public function boot(): void { if ($this->app->runningInConsole()) { - $this->commands([ListenSlidoEventCommand::class]); + $this->commands([ServeSlidoEventsCommand::class]); } } } 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..3c8bf7e12 --- /dev/null +++ b/app-modules/integration-slido/src/Stream/SlidoConnection.php @@ -0,0 +1,154 @@ +isClosed) { + return; + } + + try { + $this->session->syncQuestions(); + } catch (Throwable $throwable) { + ($this->log)('Falhou ao sincronizar as perguntas: '.$throwable->getMessage()); + } + + (new Connector($this->loop))($this->session->streamUrl(), [], ['Origin' => self::ORIGIN])->then( + function (WebSocket $socket): void { + if ($this->isClosed) { + $socket->close(); + + return; + } + + $this->socket = $socket; + $this->reconnectAttempts = 0; + $this->scheduleTokenRefresh(); + + $socket->on('message', function (MessageInterface $message) use ($socket): void { + $this->sendAll($socket, $this->session->handle((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(); + }); + }, + 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 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 index 156b138cf..0d2b2e06a 100644 --- a/app-modules/integration-slido/src/Stream/SlidoStreamSession.php +++ b/app-modules/integration-slido/src/Stream/SlidoStreamSession.php @@ -21,20 +21,29 @@ final class SlidoStreamSession private ?SlidoParticipantToken $token = null; /** + * @param list $streamers * @param Closure(string): void $log */ public function __construct( private readonly SlidoClient $client, private readonly QuestionFeed $feed, private readonly SlidoEventLocation $location, - private readonly Streamer $streamer, + private array $streamers, private readonly Closure $log, ) {} + /** + * @param list $streamers + */ + public function retarget(array $streamers): void + { + $this->streamers = $streamers; + } + public function streamUrl(): string { $query = http_build_query([ - 'clientId' => mb_substr(md5($this->streamer->getKey()), 0, 15), + 'clientId' => mb_substr(md5($this->location->uuid), 0, 15), 'slidoappVersion' => 'SlidoPresentApp/88.7.0 (web)', 'EIO' => 4, 'transport' => 'websocket', @@ -47,7 +56,7 @@ public function syncQuestions(): void { $questions = $this->client->questions($this->location, $this->token()); - event(new SlidoQuestionsSynced($this->streamer, $questions)); + event(new SlidoQuestionsSynced($this->streamers, $questions)); ($this->log)(sprintf('Sincronizou %d pergunta(s) visíveis.', count($questions))); } @@ -118,7 +127,7 @@ private function broadcast(SocketIoFrame $frame): array $question = $this->feed->questionFrom($frame); if ($question instanceof SlidoQuestion) { - event(new SlidoQuestionChanged($this->streamer, $question)); + event(new SlidoQuestionChanged($this->streamers, $question)); return []; } @@ -126,7 +135,7 @@ private function broadcast(SocketIoFrame $frame): array $patch = $this->feed->patchFrom($frame); if ($patch instanceof SlidoQuestionPatch) { - event(new SlidoQuestionPatched($this->streamer, $patch)); + event(new SlidoQuestionPatched($this->streamers, $patch)); 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/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/SlidoStreamSessionTest.php b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php index 4d65b1bfc..38b10769f 100644 --- a/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php +++ b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php @@ -15,6 +15,7 @@ use He4rt\IntegrationSlido\Transport\Requests\RefreshParticipantToken; use He4rt\IntegrationSlido\Transport\SlidoClient; use He4rt\Streaming\Streamer\Models\Streamer; +use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Support\Facades\Event; use Saloon\Http\Faking\MockClient; use Saloon\Http\Faking\MockResponse; @@ -36,7 +37,7 @@ function streamSession(Streamer $streamer, array &$logs = []): SlidoStreamSessio client: resolve(SlidoClient::class), feed: new QuestionFeed, location: new SlidoEventLocation('jC9L7Lu93Vw3ssNhB92Pvb', STREAM_EVENT_UUID, 'eu1'), - streamer: $streamer, + streamers: [$streamer], log: function (string $line) use (&$logs): void { $logs[] = $line; }, @@ -77,11 +78,9 @@ function questionUpdateFrame(array $params): string ->and($session->handle('2'))->toBe(['3']); }); -test('envia a pergunta atualizada para o canal da overlay do streamer', function (): void { - $streamer = Streamer::factory()->create(); - $session = streamSession($streamer); - - $session->handle(questionUpdateFrame([ +function highlightedQuestionFrame(): string +{ + return questionUpdateFrame([ 'event_question_id' => 122_180_089, 'type' => 'Question', 'text' => 'eaeaeaeaeaeaea', @@ -92,12 +91,32 @@ function questionUpdateFrame(array $params): string 'is_answered' => false, 'date_created' => '2026-10-31T18:23:13.000Z', 'pinned_replies' => [], - ])); + ]); +} - Event::assertDispatched(fn (SlidoQuestionChanged $event): bool => $event->streamer->is($streamer) - && $event->question->id === 122_180_089 +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 - && $event->broadcastOn()[0]->name === 'private-'.$streamer->overlayChannel()); + && 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 { 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/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php index 59a4095ec..697458175 100644 --- a/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php +++ b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php @@ -246,7 +246,7 @@ public function pubSettingsAction(): Action Notification::make() ->title('He4rt Pub atualizada') - ->body('Reinicie o slido:listen para escutar o evento novo.') + ->body('A overlay passa a mostrar as perguntas desse evento em alguns segundos.') ->success() ->send(); }); 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. From 6cc80e08144706a48caad963ca2f8fe35df9ff4f Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 16:37:12 -0300 Subject: [PATCH 06/15] =?UTF-8?q?feat(panel-overlays):=20tira=20a=20respos?= =?UTF-8?q?ta=20da=20modera=C3=A7=C3=A3o=20da=20pergunta=20no=20ar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A doca da He4rt Pub mostra só quem perguntou, os votos e a pergunta. A resposta fixada pela moderação no Slido deixa de aparecer na overlay. --- .../panel-overlays/resources/js/ui/pub/PubDock.tsx | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx b/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx index d147fbbf6..3dc6fe713 100644 --- a/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx @@ -11,13 +11,7 @@ function authorOf(question: SlidoQuestionPayload): string { return question.authorName ?? 'Anônimo'; } -function moderatorReplyOf(question: SlidoQuestionPayload): string | null { - return question.replies.find((reply) => reply.isFromModerator)?.text ?? null; -} - function QuestionOnAir({ question }: { question: SlidoQuestionPayload }) { - const reply = moderatorReplyOf(question); - return ( <>
@@ -27,11 +21,6 @@ function QuestionOnAir({ question }: { question: SlidoQuestionPayload }) {
{question.text}
- {reply ? ( -
- Moderação: {reply} -
- ) : null} ); } From 53d4596909c1d4fade9288a7af970293c681e902 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 16:42:13 -0300 Subject: [PATCH 07/15] fix(panel-overlays): a He4rt Pub encosta nas bordas em qualquer tamanho de fonte MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O Stage reduz o palco de 1920x1080 para caber na janela e centraliza. Quando a fonte do OBS não está exatamente em 16:9, sobra uma faixa transparente nas bordas, e a doca e o chat da Pub, que foram feitos para ficar rentes ao quadro, descolam do canto. Com fillViewport, a escala continua a mesma, mas o palco estica no eixo que sobra. As outras cenas continuam com o palco fixo. --- .../resources/js/pages/Overlays/Pub.tsx | 2 +- .../panel-overlays/resources/js/ui/Stage.tsx | 34 +++++++++++++------ 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx index 14ec01851..bf4bfe800 100644 --- a/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx @@ -30,7 +30,7 @@ export default function PubOverlay({ channel, authEndpoint, recentChat, pub }: P ); return ( - + fitStage(fillViewport)); useEffect(() => { - const onResize = () => setScale(fitScale()); + const onResize = () => setBox(fitStage(fillViewport)); + onResize(); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); - }, []); + }, [fillViewport]); return (
From 9ac6c71f3ffe3d70a73fc68697a14946798327e9 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 16:46:27 -0300 Subject: [PATCH 08/15] =?UTF-8?q?feat(panel-overlays):=20doca=20da=20He4rt?= =?UTF-8?q?=20Pub=20em=20degrau,=20com=20a=20pergunta=20em=20at=C3=A9=203?= =?UTF-8?q?=20linhas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A coluna do QR definia a altura da doca inteira, e uma pergunta curta ocupava o mesmo espaço de uma longa. Agora o QR mantém o tamanho para ser escaneável, e o bloco da pergunta só tem a altura e a largura do conteúdo: a borda amarela acompanha o degrau e a câmera aparece acima de uma pergunta de uma linha. A pergunta vai até três linhas. O clamp saiu da caixa com padding, que deixava a linha seguinte vazar pela sobra de baixo. --- .../panel-overlays/resources/js/ui/pub/PubDock.tsx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx b/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx index 3dc6fe713..a7485fcb7 100644 --- a/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx @@ -18,8 +18,10 @@ function QuestionOnAir({ question }: { question: SlidoQuestionPayload }) { {authorOf(question)} pergunta ▲ {question.score}
-
- {question.text} +
+

+ {question.text} +

); @@ -32,7 +34,7 @@ function QuestionQueue({ queue }: { queue: SlidoQuestionPayload[] }) { {queue.map((question) => (
▲ {question.score} {question.text} @@ -61,9 +63,9 @@ export function PubDock({ event, qrSvg, highlighted, queue }: PubDockProps) { const contentKey = highlighted ? `live-${highlighted.id}` : queue.length > 0 ? 'queue' : 'empty'; return ( -
+
{event && qrSvg ? ( -
+
{highlighted ? ( From de82953a79960b20e5fc9a2cb5c5bbd475f986c7 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 16:49:31 -0300 Subject: [PATCH 09/15] fix(panel-overlays): tira o pixel de sobra na borda esquerda da He4rt Pub MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Com escala fracionária (fonte de 2000x1125, por exemplo), centralizar o palco por flex e escalar a partir do centro deixava meio pixel de sobra, e a coluna x=0 ficava sem a doca. No modo fillViewport o palco agora ancora em 0,0 com a origem do transform no canto, e a largura e a altura lógicas arredondam para cima para a borda direita e a de baixo também encostarem. --- app-modules/panel-overlays/resources/js/ui/Stage.tsx | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/app-modules/panel-overlays/resources/js/ui/Stage.tsx b/app-modules/panel-overlays/resources/js/ui/Stage.tsx index 7dc34858f..1094f75e1 100644 --- a/app-modules/panel-overlays/resources/js/ui/Stage.tsx +++ b/app-modules/panel-overlays/resources/js/ui/Stage.tsx @@ -21,7 +21,7 @@ function fitStage(fillViewport: boolean): StageBox { return { scale, width: STAGE_W, height: STAGE_H }; } - return { scale, width: window.innerWidth / scale, height: window.innerHeight / scale }; + return { scale, width: Math.ceil(window.innerWidth / scale), height: Math.ceil(window.innerHeight / scale) }; } export function Stage({ children, fillViewport = false }: StageProps) { @@ -34,15 +34,19 @@ export function Stage({ children, fillViewport = false }: StageProps) { 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} From c00b58f93c47baa6ea06d0588d2d1ff043624a87 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 16:52:33 -0300 Subject: [PATCH 10/15] feat(panel-overlays): logo original da He4rt Pub na overlay MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Troca o logo montado com o símbolo da He4rt e o Permanent Marker pela arte original da Pub, com o spray branco, roxo e amarelo. O arquivo de origem é um PNG de 315x94 com fundo preto granulado: o fundo foi recortado por luminância, e os respingos do spray continuam. --- .../resources/images/he4rt-pub-logo.png | Bin 0 -> 40277 bytes .../resources/js/ui/He4rtLogo.tsx | 4 ++-- .../resources/js/ui/pub/PubBrand.tsx | 18 ++++++------------ 3 files changed, 8 insertions(+), 14 deletions(-) create mode 100644 app-modules/panel-overlays/resources/images/he4rt-pub-logo.png 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 0000000000000000000000000000000000000000..51b1267131bd25c2b078ac97651a85277c08f259 GIT binary patch literal 40277 zcmV*lKuW)fP)s4nrc50OuUJTme!FND12rApq0|QUa7xP)Z<#1f>LtL;}olkj-Qugn)#E zlmOAcmr?@K+yQVLhGa4c*L9G~iO!OBuuZQRDF-dT)3_a04R7K0-wW;Ibf6m5)eYbaa}M*;rkwffI~{a zbsfax32-jZ+uI9D2^_}(Arw+d2*E)JK_U?Y4>&x}2cZt zz~=xY7*%sf2vzf(h{N{-$+f!AqWE15B;XWE z$92?aT!2yaYyzU*iE{|9`Y42+FG3(Abw2O1Q3zL_CgkIt?xay1F_cxB%6CQR`QN5D6ireJ>C-X67EQ8$%)ygY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ON);8Wu;G-$ z7o+6sPUBQ6tymzFh;ST_$f;UCVyZVTAJw?nDvqPiuv3x%bJ^B`R-#jWS0zVYvl6a} zM*H_l(b<-xDvGN`IUAvJj*!|jgV6#>+&BU#^V}{@&Wt55WvFc2Ek-)CC_;Np+tj=x zFaaL2>t!}N}Nb1(f;KcpR_XOi7STeMp|KO-Ny#YIwP6&XU^PQtM9CqqGium5ExDHcQr;E;KN)ILtwok^ELj$Fwc>k zli=}^G`?eGa9I!{@PwL)vF?h=UPbq8jB4M7h9okXc`26U+HJoQU%P-GU0U?pwmzzK z{e9=MUg~|)_ib3fUWv}Q;5WA$`*e@OZPQFwzu*3BypO`KRL{dKtdfABiV>QsDcsBk z^lOq4GD{)f={RB7@3AaBm`63_2-9(dCv{`J_ZW5q`o0$nO_hVyxa(rXyet@xM@`34 z0aGoWGsA~~zV8u3lziE7!mOpkv(~!HjYVXKZu=nqw+)EJ;8NLr>!3L2e(hrSmYiFB z4B_B#+aM{TMb!3_8)V{BDYV)P{oh9R_@va^#bDTvl~!wy~SPAg|O@6=MJYDJy% zW3lR!TBF|iyR572{FxkW5q#$zwi>6EjV=AATvP74&Huf}y{>-3x-aK$f9a8z{%$UB z1^U_)OB9BOZJ;eeFXISBaBBsm(m#d(rKt24(=j<`{0m`TUDSi7m(u_M002ovPDHLk FV1k#hwcY># literal 0 HcmV?d00001 diff --git a/app-modules/panel-overlays/resources/js/ui/He4rtLogo.tsx b/app-modules/panel-overlays/resources/js/ui/He4rtLogo.tsx index ef13b42b1..a1b1a0411 100644 --- a/app-modules/panel-overlays/resources/js/ui/He4rtLogo.tsx +++ b/app-modules/panel-overlays/resources/js/ui/He4rtLogo.tsx @@ -1,6 +1,6 @@ -export const PATH_A = +const PATH_A = 'M321.871 46.0393L142.46 225.416L107.15 190.106L107.144 190.099L107.137 190.093C102.363 185.487 98.5537 179.976 95.9328 173.881C93.3118 167.787 91.9312 161.232 91.8717 154.598C91.8122 147.964 93.0749 141.385 95.5862 135.244C98.0974 129.104 101.807 123.525 106.498 118.834C111.189 114.143 116.767 110.434 122.908 107.923C129.048 105.411 135.628 104.149 142.261 104.208C148.895 104.268 155.451 105.648 161.545 108.269C167.64 110.89 173.151 114.699 177.757 119.473L178.464 120.206L179.183 119.486L251.253 47.4526L251.969 46.7366L251.244 46.0295C222.277 17.7749 183.344 2.07155 142.88 2.3217C102.416 2.57185 63.6803 18.7554 35.065 47.3659C6.44979 75.9765 -9.74008 114.71 -9.9969 155.174C-10.2537 195.638 5.44322 234.573 33.693 263.545L33.7019 263.554L141.753 371.604L142.46 372.311L143.167 371.604L497.208 17.5631L498.208 16.5632L496.932 15.9537C476.231 6.06282 453.572 0.952379 430.63 1.00033C410.428 0.965204 390.418 4.92639 371.753 12.6559C353.087 20.3856 336.134 31.7312 321.871 46.0393Z'; -export const PATH_B = +const PATH_B = 'M569.434 88.4943L568.824 87.2175L567.824 88.218L430.627 225.45L395.317 190.106L394.61 189.398L393.903 190.105L321.869 262.139L321.162 262.846L321.869 263.553L357.179 298.863L213.818 442.224L213.112 442.93L213.818 443.638L285.852 515.707L286.559 516.414L287.266 515.707L539.384 263.589L538.677 262.882L539.385 263.589C561.877 241.089 576.843 212.171 582.224 180.815C587.605 149.459 583.137 117.206 569.434 88.4943Z'; interface TonePreset { diff --git a/app-modules/panel-overlays/resources/js/ui/pub/PubBrand.tsx b/app-modules/panel-overlays/resources/js/ui/pub/PubBrand.tsx index b6107a049..0d5ff5045 100644 --- a/app-modules/panel-overlays/resources/js/ui/pub/PubBrand.tsx +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubBrand.tsx @@ -1,18 +1,12 @@ -import { PATH_A, PATH_B } from '../He4rtLogo'; +import logoUrl from '../../../images/he4rt-pub-logo.png'; export function PubBrand() { return ( -
- - - - - He4rtPub - -
+ He4rt Pub ); } From ffd9eec7c83b6e955e1b48b3e2fbc6e756dd110d Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 17:08:48 -0300 Subject: [PATCH 11/15] fix(panel-app): reconectar outra conta da Twitch escolhendo a conta certa MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Uma fonte conectada antes da Minha Live (a he4rtdevs, no login) fica sem escopos e sem inscrições EventSub: aparece como ligada, mas não recebe chat nem alertas. Para consertar, o OAuth precisava autorizar essa conta, mas a Twitch reaproveitava a conta logada no navegador sem perguntar. Agora o vínculo pelo painel manda force_verify, e a Twitch mostra com qual conta você está entrando. Em Outras fontes, a fonte sem permissão avisa e ganha o Reconectar como @conta. Depois da autorização, o ExternalIdentityConnected já sincroniza as inscrições dela. --- .../src/OAuth/TwitchOAuthClient.php | 6 +++-- .../tests/Feature/TwitchScopesTest.php | 15 +++++++++++ .../views/pages/streaming/dashboard.blade.php | 15 ++++++++--- .../Streaming/Pages/StreamDashboardPage.php | 25 +++++++++++++++++++ .../Streaming/StreamDashboardDataTest.php | 17 +++++++++++++ 5 files changed, 72 insertions(+), 6 deletions(-) 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/src/Clusters/Streaming/Pages/StreamDashboardPage.php b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamDashboardPage.php index 7b6e3e4e8..c2c503cd5 100644 --- a/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamDashboardPage.php +++ b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamDashboardPage.php @@ -338,6 +338,31 @@ public function toggleSourceAction(): Action }); } + public function reconnectSourceAction(): Action + { + return Action::make('reconnectSource') + ->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/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])); +}); From f34ca079f721f503c3cb1d9e17707bed9e1969ec Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 17:12:18 -0300 Subject: [PATCH 12/15] feat(streaming): cada cena escolhe de quais fontes recebe chat e alertas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O streamer junta todas as fontes ligadas, e o token do OBS é um só: a cena He4rt Pub, transmitida no canal he4rtdevs, mostrava o chat do canal pessoal misturado. As configurações ganham scene_sources, com as fontes de cada cena. Cena sem escolha continua usando todas, e uma fonte escolhida que some faz a cena voltar a usar todas. Os broadcasts de chat, alerta e sessão passam a levar o sourceId, e a overlay recebe a lista de fontes da cena. O chat recente e a live em andamento já vêm filtrados. --- .../Controllers/ShowOverlayController.php | 7 +- .../tests/Feature/ShowOverlayTest.php | 38 ++++++++ app-modules/streaming/CONTEXT.md | 1 + .../src/Broadcasting/AlertTriggered.php | 11 ++- .../src/Broadcasting/ChatMessageReceived.php | 7 +- .../src/Broadcasting/StreamSessionEnded.php | 3 +- .../src/Broadcasting/StreamSessionStarted.php | 3 +- .../src/Chat/Actions/RecordChatMessage.php | 2 +- .../src/Chat/Queries/StreamerChatMessages.php | 28 ++++-- .../src/Overlay/OverlayInitialState.php | 33 +++++-- .../src/Streamer/Data/SceneSources.php | 90 +++++++++++++++++++ .../src/Streamer/Data/StreamerSettings.php | 19 +++- .../src/Streamer/Models/Streamer.php | 14 +++ .../Feature/Chat/RecordChatMessageTest.php | 1 + .../StreamEvent/RecordStreamEventTest.php | 1 + .../tests/Unit/Streamer/SceneSourcesTest.php | 32 +++++++ 16 files changed, 265 insertions(+), 25 deletions(-) create mode 100644 app-modules/streaming/src/Streamer/Data/SceneSources.php create mode 100644 app-modules/streaming/tests/Unit/Streamer/SceneSourcesTest.php diff --git a/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php b/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php index 8a1649ee9..62ec5a9c9 100644 --- a/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php +++ b/app-modules/panel-overlays/src/Http/Controllers/ShowOverlayController.php @@ -28,14 +28,17 @@ public function __invoke( 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, ]); } diff --git a/app-modules/panel-overlays/tests/Feature/ShowOverlayTest.php b/app-modules/panel-overlays/tests/Feature/ShowOverlayTest.php index 5bc188980..a4cbef038 100644 --- a/app-modules/panel-overlays/tests/Feature/ShowOverlayTest.php +++ b/app-modules/panel-overlays/tests/Feature/ShowOverlayTest.php @@ -56,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([ @@ -226,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 1a5f11c40..fdd1b9a83 100644 --- a/app-modules/streaming/CONTEXT.md +++ b/app-modules/streaming/CONTEXT.md @@ -54,6 +54,7 @@ Esses três dependem deste módulo, e este módulo não depende de nenhum deles. | **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`, `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/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/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/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/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 7849147d4..c02ab562e 100644 --- a/app-modules/streaming/src/Streamer/Data/StreamerSettings.php +++ b/app-modules/streaming/src/Streamer/Data/StreamerSettings.php @@ -16,6 +16,7 @@ public function __construct( public PubSettings $pub = new PubSettings, public AlertSettings $alerts = new AlertSettings, public MutedChatters $mutedChatters = new MutedChatters, + public SceneSources $sceneSources = new SceneSources, ) {} /** @@ -26,6 +27,7 @@ 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)), @@ -35,6 +37,7 @@ public static function fromArray(array $payload): self pub: PubSettings::fromArray(self::scenePayload($scenes, OverlayScene::Pub)), alerts: AlertSettings::fromArray($alerts), mutedChatters: MutedChatters::fromArray($mutedChatters), + sceneSources: SceneSources::fromArray($sceneSources), ); } @@ -59,21 +62,30 @@ public function withScene(SceneSettings $settings): self 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, $this->pub, $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->pub, $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 { @@ -87,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/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']]); +}); From 4652804ae62c162c917d34c9435ef5683b04a34e Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 17:17:10 -0300 Subject: [PATCH 13/15] =?UTF-8?q?feat(panel-app):=20bot=C3=A3o=20Fontes=20?= =?UTF-8?q?em=20cada=20cena=20da=20p=C3=A1gina=20de=20Overlays?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cada card de cena ganha o Fontes, que aparece para quem tem duas fontes ou mais. O rótulo mostra a escolha atual (Fontes: todas, Fontes: @he4rtdevs), e o modal marca de quais canais a cena recebe chat e alertas. Na overlay, a assinatura do canal descarta a mensagem e o alerta de uma fonte que a cena não usa; o alerta de teste, sem fonte, passa sempre. Ao salvar, o broadcast sources.updated faz a cena aberta no OBS recarregar com o chat recente já filtrado. --- .../views/pages/streaming/overlays.blade.php | 10 +- .../Streaming/Pages/StreamOverlaysPage.php | 104 ++++++++++++++++++ .../Streaming/StreamOverlaySourcesTest.php | 65 +++++++++++ .../resources/js/hooks/useOverlayFeed.ts | 13 ++- .../resources/js/lib/overlayChannel.ts | 30 ++++- .../resources/js/lib/overlayEvents.ts | 2 +- .../resources/js/pages/Overlays/Chat.tsx | 11 +- .../resources/js/pages/Overlays/Coworking.tsx | 11 +- .../resources/js/pages/Overlays/Pub.tsx | 4 +- .../js/pages/Overlays/StartingSoon.tsx | 3 +- .../resources/js/pages/Overlays/Voice.tsx | 10 +- .../panel-overlays/resources/js/types.ts | 4 + .../Broadcasting/OverlaySourcesUpdated.php | 44 ++++++++ .../Actions/UpdateStreamerSettings.php | 7 ++ .../Streamer/UpdateStreamerSettingsTest.php | 15 ++- 15 files changed, 313 insertions(+), 20 deletions(-) create mode 100644 app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySourcesTest.php create mode 100644 app-modules/streaming/src/Broadcasting/OverlaySourcesUpdated.php 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]) }} +
$overlaySources + */ class StreamOverlaysPage extends Page { private const int SCENE_WIDTH = 1_920; @@ -252,6 +259,60 @@ public function pubSettingsAction(): Action }); } + 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') @@ -390,6 +451,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/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/js/hooks/useOverlayFeed.ts b/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts index 99773623b..07ced29b8 100644 --- a/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts +++ b/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts @@ -30,16 +30,23 @@ export interface OverlayFeedHandlers { onPubQuestionPatch?(dto: PubQuestionPatchDto): 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 { diff --git a/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts b/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts index 6ce55726c..ae265df2e 100644 --- a/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts +++ b/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts @@ -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,6 +59,11 @@ 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())), ) 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/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 index bf4bfe800..6e75d5fe9 100644 --- a/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx @@ -12,12 +12,12 @@ import type { PubPageProps } from '../../types'; const QUEUE_LIMIT = 3; -export default function PubOverlay({ channel, authEndpoint, recentChat, pub }: PubPageProps) { +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 }, + { channel, authEndpoint, scene, sources }, { onChatMessage: chat.push, onChatDeleted: chat.remove, 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 5d092b9bc..e3bd0f8bc 100644 --- a/app-modules/panel-overlays/resources/js/types.ts +++ b/app-modules/panel-overlays/resources/js/types.ts @@ -68,6 +68,7 @@ export interface ChatBadgePayload { } export interface ChatMessagePayload { + sourceId?: string | null; msgId: string; chatterId: string; username: string; @@ -77,6 +78,7 @@ export interface ChatMessagePayload { } export interface SessionPayload { + sourceId?: string; title: string | null; category: string | null; startedAt: string; @@ -85,6 +87,8 @@ export interface SessionPayload { export interface OverlayChannelSource { channel: string; authEndpoint: string; + scene?: string; + sources?: string[] | null; } export interface OverlayPageProps extends OverlayChannelSource { 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/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/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); +}); From 5cd0de4ec3794cdcf8c7246b4bd90809e0407b51 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 17:20:59 -0300 Subject: [PATCH 14/15] fix(integration-slido): ajustes da review do slido:serve e da cena Pub MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sincroniza as perguntas depois que o Slido aceita a assinatura, para não perder o que mudou entre o snapshot e o feed ao vivo - assinatura recusada (ack sem 200 ou erro de conexão) descarta o token e fecha o socket, e a reconexão emite um token novo - exceção num frame ou ao preparar o token não derruba mais o worker - hash do evento só com dígitos continua string na reconciliação - frame 42 com id de ack, data inválida na pergunta e delay de refresh 0 deixam de quebrar o fluxo - o módulo declara saloon, ratchet/pawl e react/event-loop, com as versões que já estavam instaladas - o link do Slido pode ficar vazio para tirar o Slido da overlay - a cena Pub recarrega quando o evento muda no painel ou quando o Reverb reconecta, para o QR e as perguntas não ficarem velhos - a mensagem do chat vai até 3 linhas sem esconder o autor, e um código longo do Slido quebra dentro da doca --- app-modules/integration-slido/composer.json | 5 +++ .../src/Console/ServeSlidoEventsCommand.php | 13 +++++- .../src/Data/SlidoParticipantToken.php | 2 +- .../src/Data/SlidoQuestion.php | 18 +++++++- .../Exceptions/SlidoSubscriptionRejected.php | 15 +++++++ .../src/Stream/SlidoConnection.php | 29 +++++++++---- .../src/Stream/SlidoStreamSession.php | 29 +++++++++++-- .../src/Stream/SocketIoFrame.php | 2 +- .../tests/Feature/SlidoStreamSessionTest.php | 43 +++++++++++++++++++ .../tests/Unit/SocketIoFrameTest.php | 8 ++++ .../Streaming/Pages/StreamOverlaysPage.php | 13 +++--- .../Streaming/StreamOverlaySettingsTest.php | 12 ++++++ .../panel-overlays/resources/js/feed.ts | 7 ++- .../resources/js/hooks/useOverlayFeed.ts | 4 ++ .../resources/js/lib/overlayChannel.ts | 10 +++++ .../resources/js/pages/Overlays/Pub.tsx | 8 ++++ .../resources/js/ui/pub/PubChat.tsx | 26 +++++------ .../resources/js/ui/pub/PubDock.tsx | 2 +- composer.lock | 7 ++- 19 files changed, 215 insertions(+), 38 deletions(-) create mode 100644 app-modules/integration-slido/src/Exceptions/SlidoSubscriptionRejected.php diff --git a/app-modules/integration-slido/composer.json b/app-modules/integration-slido/composer.json index 03b7764af..79335bfc8 100644 --- a/app-modules/integration-slido/composer.json +++ b/app-modules/integration-slido/composer.json @@ -4,6 +4,11 @@ "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/", diff --git a/app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php b/app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php index 07277ea4d..a50dd0da1 100644 --- a/app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php +++ b/app-modules/integration-slido/src/Console/ServeSlidoEventsCommand.php @@ -56,7 +56,7 @@ public function handle(SlidoClient $client, QuestionFeed $feed, SlidoAudience $a */ private function reconcile(SlidoClient $client, QuestionFeed $feed, array $audience, LoopInterface $loop): void { - $plan = SlidoSubscriptionPlan::between(array_keys($audience), array_keys($this->connections)); + $plan = SlidoSubscriptionPlan::between($this->hashesOf($audience), $this->hashesOf($this->connections)); foreach ($plan->closing as $eventHash) { $this->connections[$eventHash]->close(); @@ -95,6 +95,17 @@ private function open(SlidoClient $client, QuestionFeed $feed, string $eventHash $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/SlidoParticipantToken.php b/app-modules/integration-slido/src/Data/SlidoParticipantToken.php index 93e4d1eab..90eccca9d 100644 --- a/app-modules/integration-slido/src/Data/SlidoParticipantToken.php +++ b/app-modules/integration-slido/src/Data/SlidoParticipantToken.php @@ -42,6 +42,6 @@ public function secondsUntilRefresh(): int { $seconds = (int) CarbonImmutable::now()->diffInSeconds($this->expiresAt->subSeconds(self::REFRESH_MARGIN_SECONDS), absolute: false); - return max($seconds, 0); + return max($seconds, 1); } } diff --git a/app-modules/integration-slido/src/Data/SlidoQuestion.php b/app-modules/integration-slido/src/Data/SlidoQuestion.php index 7eb4f2ef3..d08508f4f 100644 --- a/app-modules/integration-slido/src/Data/SlidoQuestion.php +++ b/app-modules/integration-slido/src/Data/SlidoQuestion.php @@ -5,6 +5,7 @@ namespace He4rt\IntegrationSlido\Data; use Carbon\CarbonImmutable; +use Carbon\Exceptions\InvalidFormatException; final readonly class SlidoQuestion { @@ -38,7 +39,7 @@ public static function tryFromPayload(array $payload): ?self $isPublic = ($payload['is_public'] ?? true) === true; $isDeleted = ($payload['date_deleted'] ?? null) !== null; - $createdAt = is_string($payload['date_created'] ?? null) ? $payload['date_created'] : 'now'; + $createdAt = self::createdAtOf($payload['date_created'] ?? null); $pinnedReplies = is_array($payload['pinned_replies'] ?? null) ? $payload['pinned_replies'] : []; return new self( @@ -49,7 +50,7 @@ public static function tryFromPayload(array $payload): ?self isHighlighted: ($payload['is_highlighted'] ?? false) === true, isAnswered: ($payload['is_answered'] ?? false) === true, isVisible: $isPublic && !$isDeleted, - createdAt: CarbonImmutable::parse($createdAt), + createdAt: $createdAt, replies: self::repliesOf($pinnedReplies), ); } @@ -87,6 +88,19 @@ public function toArray(): array ]; } + 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 diff --git a/app-modules/integration-slido/src/Exceptions/SlidoSubscriptionRejected.php b/app-modules/integration-slido/src/Exceptions/SlidoSubscriptionRejected.php new file mode 100644 index 000000000..b2432c1b1 --- /dev/null +++ b/app-modules/integration-slido/src/Exceptions/SlidoSubscriptionRejected.php @@ -0,0 +1,15 @@ +session->syncQuestions(); - } catch (Throwable $throwable) { - ($this->log)('Falhou ao sincronizar as perguntas: '.$throwable->getMessage()); - } - (new Connector($this->loop))($this->session->streamUrl(), [], ['Origin' => self::ORIGIN])->then( function (WebSocket $socket): void { if ($this->isClosed) { @@ -59,10 +54,9 @@ function (WebSocket $socket): void { $this->socket = $socket; $this->reconnectAttempts = 0; - $this->scheduleTokenRefresh(); $socket->on('message', function (MessageInterface $message) use ($socket): void { - $this->sendAll($socket, $this->session->handle((string) $message)); + $this->receive($socket, (string) $message); }); $socket->on('close', function (?int $code = null, ?string $reason = null): void { @@ -73,6 +67,13 @@ function (WebSocket $socket): void { ($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()); @@ -89,6 +90,18 @@ public function close(): void $this->socket = null; } + private function receive(WebSocket $socket, string $raw): void + { + try { + $this->sendAll($socket, $this->session->handle($raw)); + } 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; diff --git a/app-modules/integration-slido/src/Stream/SlidoStreamSession.php b/app-modules/integration-slido/src/Stream/SlidoStreamSession.php index 0d2b2e06a..9492413f5 100644 --- a/app-modules/integration-slido/src/Stream/SlidoStreamSession.php +++ b/app-modules/integration-slido/src/Stream/SlidoStreamSession.php @@ -12,6 +12,7 @@ use He4rt\IntegrationSlido\Data\SlidoParticipantToken; use He4rt\IntegrationSlido\Data\SlidoQuestion; use He4rt\IntegrationSlido\Data\SlidoQuestionPatch; +use He4rt\IntegrationSlido\Exceptions\SlidoSubscriptionRejected; use He4rt\IntegrationSlido\Transport\SlidoClient; use He4rt\Streaming\Streamer\Models\Streamer; use Throwable; @@ -63,6 +64,8 @@ public function syncQuestions(): void /** * @return list + * + * @throws SlidoSubscriptionRejected when Slido refuses the subscription; close the socket to recover */ public function handle(string $raw): array { @@ -72,9 +75,10 @@ public function handle(string $raw): array FrameKind::Open => [SocketIoFrame::CONNECT], FrameKind::Connected => [$this->subscribeFrame()], FrameKind::Ping => [SocketIoFrame::PONG], - FrameKind::Ack => $this->acknowledge($frame), + FrameKind::Ack => $this->acknowledge($frame, $raw), FrameKind::Event => $this->broadcast($frame), - FrameKind::ConnectError, FrameKind::Disconnected, FrameKind::Unknown => $this->ignore($frame, $raw), + FrameKind::ConnectError => $this->reject($raw), + FrameKind::Disconnected, FrameKind::Unknown => $this->ignore($frame, $raw), }; } @@ -112,13 +116,30 @@ private function subscribeFrame(): string /** * @return list */ - private function acknowledge(SocketIoFrame $frame): array + private function acknowledge(SocketIoFrame $frame, string $raw): array { - ($this->log)($frame->isSubscriptionAccepted() ? 'Assinatura aceita pelo Slido.' : 'Slido recusou a assinatura.'); + if (!$frame->isSubscriptionAccepted()) { + return $this->reject($raw); + } + + ($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; + + throw SlidoSubscriptionRejected::withFrame($raw); + } + /** * @return list */ diff --git a/app-modules/integration-slido/src/Stream/SocketIoFrame.php b/app-modules/integration-slido/src/Stream/SocketIoFrame.php index f14a40efe..c38e7695a 100644 --- a/app-modules/integration-slido/src/Stream/SocketIoFrame.php +++ b/app-modules/integration-slido/src/Stream/SocketIoFrame.php @@ -29,7 +29,7 @@ public static function parse(string $raw): self $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(mb_substr($raw, 2)), + 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))), diff --git a/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php index 38b10769f..3ce77dbed 100644 --- a/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php +++ b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php @@ -6,6 +6,7 @@ use He4rt\IntegrationSlido\Broadcasting\SlidoQuestionPatched; use He4rt\IntegrationSlido\Broadcasting\SlidoQuestionsSynced; use He4rt\IntegrationSlido\Data\SlidoEventLocation; +use He4rt\IntegrationSlido\Exceptions\SlidoSubscriptionRejected; use He4rt\IntegrationSlido\Stream\QuestionFeed; use He4rt\IntegrationSlido\Stream\SlidoStreamSession; use He4rt\IntegrationSlido\Transport\Requests\AuthorizeParticipant; @@ -189,3 +190,45 @@ function highlightedQuestionFrame(): string 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); +}); diff --git a/app-modules/integration-slido/tests/Unit/SocketIoFrameTest.php b/app-modules/integration-slido/tests/Unit/SocketIoFrameTest.php index 81da426bd..29066d596 100644 --- a/app-modules/integration-slido/tests/Unit/SocketIoFrameTest.php +++ b/app-modules/integration-slido/tests/Unit/SocketIoFrameTest.php @@ -34,3 +34,11 @@ 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/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php index 00bd145a8..f354de37b 100644 --- a/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php +++ b/app-modules/panel-app/src/Clusters/Streaming/Pages/StreamOverlaysPage.php @@ -229,7 +229,7 @@ public function pubSettingsAction(): Action ->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.') + ->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([ @@ -238,22 +238,23 @@ public function pubSettingsAction(): Action ->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 { - if (!is_string($value) || SlidoEventHash::fromInput($value) === null) { + $isFilledButUnknown = is_string($value) && $value !== '' && SlidoEventHash::fromInput($value) === null; + + if ($isFilledButUnknown) { $fail('Não reconheci esse link do Slido.'); } - }) - ->required(), + }), ]) ->action(function (array $data, UpdateStreamerSettings $updateSettings): void { $streamer = $this->currentStreamer(); $slidoEvent = $data['slido_event'] ?? null; - $eventHash = is_string($slidoEvent) ? SlidoEventHash::fromInput($slidoEvent) : 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('A overlay passa a mostrar as perguntas desse evento em alguns segundos.') + ->body($eventHash === null ? 'A overlay deixa de mostrar o Slido.' : 'A overlay passa a mostrar as perguntas desse evento em alguns segundos.') ->success() ->send(); }); diff --git a/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php b/app-modules/panel-app/tests/Feature/Streaming/StreamOverlaySettingsTest.php index 050132333..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; @@ -159,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-overlays/resources/js/feed.ts b/app-modules/panel-overlays/resources/js/feed.ts index 17bef580c..dea24fb80 100644 --- a/app-modules/panel-overlays/resources/js/feed.ts +++ b/app-modules/panel-overlays/resources/js/feed.ts @@ -165,6 +165,10 @@ export interface PubQuestionPatchDto { changes: SlidoQuestionChanges; } +export interface ChannelReconnectedDto { + kind: 'channelReconnected'; +} + export type FeedEventDto = | ChatMessageDto | ChatMessageDeletedDto @@ -177,4 +181,5 @@ export type FeedEventDto = | LevelProgressDto | PubQuestionsDto | PubQuestionDto - | PubQuestionPatchDto; + | 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 07ced29b8..309c3d10e 100644 --- a/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts +++ b/app-modules/panel-overlays/resources/js/hooks/useOverlayFeed.ts @@ -28,6 +28,7 @@ export interface OverlayFeedHandlers { onPubQuestions?(dto: PubQuestionsDto): void; onPubQuestion?(dto: PubQuestionDto): void; onPubQuestionPatch?(dto: PubQuestionPatchDto): void; + onChannelReconnected?(): void; } export function useOverlayFeed( @@ -87,5 +88,8 @@ function dispatch(dto: FeedEventDto, handlers: OverlayFeedHandlers): void { case 'pubQuestionPatch': handlers.onPubQuestionPatch?.(dto); break; + case 'channelReconnected': + handlers.onChannelReconnected?.(); + break; } } diff --git a/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts b/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts index ae265df2e..dc2cb4ddd 100644 --- a/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts +++ b/app-modules/panel-overlays/resources/js/lib/overlayChannel.ts @@ -75,5 +75,15 @@ export function subscribeOverlayChannel( 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/pages/Overlays/Pub.tsx b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx index 6e75d5fe9..1c8256760 100644 --- a/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx +++ b/app-modules/panel-overlays/resources/js/pages/Overlays/Pub.tsx @@ -26,6 +26,14 @@ export default function PubOverlay({ scene, channel, authEndpoint, sources, rece 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(), }, ); diff --git a/app-modules/panel-overlays/resources/js/ui/pub/PubChat.tsx b/app-modules/panel-overlays/resources/js/ui/pub/PubChat.tsx index 1a0e62e45..4c1eeee70 100644 --- a/app-modules/panel-overlays/resources/js/ui/pub/PubChat.tsx +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubChat.tsx @@ -25,18 +25,20 @@ export function PubChat({ edition, messages }: PubChatProps) { className="font-pub-sans text-[23px] font-medium leading-[1.3] break-words text-pub-chalk [text-shadow:0_2px_10px_rgba(0,0,0,.85)] animate-[pubMessageIn_.4s_ease-out_both]" > {message.username} - {message.fragments.map((fragment, index) => - fragment.kind === 'emote' ? ( - - ) : ( - {fragment.text} - ), - )} + + {message.fragments.map((fragment, index) => + fragment.kind === 'emote' ? ( + + ) : ( + {fragment.text} + ), + )} +
))}
diff --git a/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx b/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx index a7485fcb7..d21258c43 100644 --- a/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx +++ b/app-modules/panel-overlays/resources/js/ui/pub/PubDock.tsx @@ -73,7 +73,7 @@ export function PubDock({ event, qrSvg, highlighted, queue }: PubDockProps) { Pergunte aqui - + slido.com #{event.code}
diff --git a/composer.lock b/composer.lock index ed6a0b156..a25ca541d 100644 --- a/composer.lock +++ b/composer.lock @@ -3866,7 +3866,12 @@ "dist": { "type": "path", "url": "app-modules/integration-slido", - "reference": "78a17dedc2e5592ee5c59747d39aaeb6d1ed9cb1" + "reference": "d41d5a7edb9e555208fa461a3226db283102ff14" + }, + "require": { + "ratchet/pawl": "^0.4.3", + "react/event-loop": "^1.6.0", + "saloonphp/saloon": "^4.5.0" }, "type": "library", "extra": { From 14f37efd2beb6f14299d10e67215d1ced50a323f Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Sat, 31 Oct 2026 17:48:16 -0300 Subject: [PATCH 15/15] =?UTF-8?q?fix(integration-slido):=20backoff=20da=20?= =?UTF-8?q?reconex=C3=A3o=20s=C3=B3=20zera=20com=20a=20assinatura=20aceita?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O contador de tentativas zerava assim que o socket conectava. Quando o Slido recusa a assinatura logo em seguida, o worker reconectava a cada segundo e martelava o Slido. Agora o contador só zera depois do ack aceito, e a recusa mantém o backoff crescendo até 60 s. --- .../src/Stream/SlidoConnection.php | 5 ++++- .../src/Stream/SlidoStreamSession.php | 9 +++++++++ .../tests/Feature/SlidoStreamSessionTest.php | 13 +++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/app-modules/integration-slido/src/Stream/SlidoConnection.php b/app-modules/integration-slido/src/Stream/SlidoConnection.php index bb263cf82..d20888825 100644 --- a/app-modules/integration-slido/src/Stream/SlidoConnection.php +++ b/app-modules/integration-slido/src/Stream/SlidoConnection.php @@ -53,7 +53,6 @@ function (WebSocket $socket): void { } $this->socket = $socket; - $this->reconnectAttempts = 0; $socket->on('message', function (MessageInterface $message) use ($socket): void { $this->receive($socket, (string) $message); @@ -94,6 +93,10 @@ 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(); diff --git a/app-modules/integration-slido/src/Stream/SlidoStreamSession.php b/app-modules/integration-slido/src/Stream/SlidoStreamSession.php index 9492413f5..fdf3550e1 100644 --- a/app-modules/integration-slido/src/Stream/SlidoStreamSession.php +++ b/app-modules/integration-slido/src/Stream/SlidoStreamSession.php @@ -21,6 +21,8 @@ final class SlidoStreamSession { private ?SlidoParticipantToken $token = null; + private bool $isSubscribed = false; + /** * @param list $streamers * @param Closure(string): void $log @@ -41,6 +43,11 @@ public function retarget(array $streamers): void $this->streamers = $streamers; } + public function isSubscribed(): bool + { + return $this->isSubscribed; + } + public function streamUrl(): string { $query = http_build_query([ @@ -122,6 +129,7 @@ private function acknowledge(SocketIoFrame $frame, string $raw): array return $this->reject($raw); } + $this->isSubscribed = true; ($this->log)('Assinatura aceita pelo Slido.'); try { @@ -136,6 +144,7 @@ private function acknowledge(SocketIoFrame $frame, string $raw): array private function reject(string $raw): never { $this->token = null; + $this->isSubscribed = false; throw SlidoSubscriptionRejected::withFrame($raw); } diff --git a/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php index 3ce77dbed..66ae6999e 100644 --- a/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php +++ b/app-modules/integration-slido/tests/Feature/SlidoStreamSessionTest.php @@ -232,3 +232,16 @@ function highlightedQuestionFrame(): string 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(); +});