Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unfurling Discord Message Links #221

Merged
merged 8 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export SLACK_TEAM_ID="__SLACK_TEAM_ID__"
export SLACK_REDIRECT_URI="__SLACK_REDIRECT_URI__"
export SLACK_BOT_USER_OAUTH_TOKEN="__SLACK_BOT_USER_OAUTH_TOKEN__"

export DISCORD_BOT_TOKEN="__DISCORD_BOT_TOKEN__"

export SENTRY_BACKEND_DSN="__SENTRY_BACKEND_DSN__"
export SENTRY_FRONTEND_DSN="__SENTRY_BACKEND_DSN__"
export SENTRY_POTAL_DSN="__SENTRY_POTAL_DSN__"
Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ services:
- SLACK_TEAM_ID
- SLACK_REDIRECT_URI
- SLACK_BOT_USER_OAUTH_TOKEN
- DISCORD_BOT_TOKEN
- SENTRY_BACKEND_DSN
- SENTRY_FRONTEND_DSN
- SENTRY_AUTH_TOKEN
Expand Down
4 changes: 2 additions & 2 deletions docker/backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM ubuntu:22.04 as php-local
FROM ubuntu:22.04 AS php-local

ENV DEBIAN_FRONTEND=noninteractive

Expand Down Expand Up @@ -58,7 +58,7 @@ EXPOSE 8080

CMD [ "/bin/bash", "/run.sh" ]

FROM node:18-bullseye as js-build
FROM node:18-bullseye AS js-build

WORKDIR /app

Expand Down
22 changes: 11 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions potal/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,32 @@ func EventsHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params)
return
}

txn.Status = sentry.SpanStatusOK
}()
case *slackevents.LinkSharedEvent:
go event.ProcessLinkSharedEvent(r.Context(), ev)
go func() {
hub := sentry.CurrentHub().Clone()
ctx := sentry.SetHubOnContext(context.Background(), hub)

options := []sentry.SpanOption{
sentry.WithOpName("event.handler"),
sentry.WithTransactionSource(sentry.SourceTask),
sentry.ContinueFromHeaders(transaction.ToSentryTrace(), transaction.ToBaggage()),
}
txn := sentry.StartTransaction(ctx, "EVENT link_shared", options...)
defer txn.Finish()

processedEvent := event.ProcessLinkSharedEvent(txn.Context(), ev)
if processedEvent == nil {
return
}
err := potalhttp.SendRequest(txn.Context(), processedEvent)
if err != nil {
txn.Status = sentry.SpanStatusInternalError
return
}

txn.Status = sentry.SpanStatusOK
}()
}
Expand Down
1 change: 1 addition & 0 deletions potal/internal/event/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const (
appHomeOpened PotalEventType = "app_home_opened"
slashCommand PotalEventType = "slash_command"
interactionCallback PotalEventType = "interaction_callback"
linkShared PotalEventType = "link_shared"
)

func (e PotalEventType) String() string {
Expand Down
68 changes: 68 additions & 0 deletions potal/internal/event/linkshared.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package event

import (
"context"

"github.com/getsentry/sentry-go"
"github.com/slack-go/slack/slackevents"
)

type LinkSharedEvent struct {
Type PotalEventType `json:"type"`
User string `json:"user"`
TimeStamp string `json:"ts"`
Channel string `json:"channel"`
MessageTimeStamp string `json:"message_ts"`
ThreadTimeStamp string `json:"thread_ts"`
Links []Link `json:"links"`
EventTimestamp string `json:"event_ts"`
}

type Link struct {
Domain string `json:"domain"`
URL string `json:"url"`
}

func (e LinkSharedEvent) isValid() bool {
// App unfurl domains are configured in the Slack's app settings,
// so we don't need validate the domain here.
return len(e.Links) > 0
}

func ProcessLinkSharedEvent(ctx context.Context, e *slackevents.LinkSharedEvent) *LinkSharedEvent {
hub := sentry.GetHubFromContext(ctx)
txn := sentry.TransactionFromContext(ctx)

span := txn.StartChild("event.process", sentry.WithDescription("Process LinkShared Event"))
defer span.Finish()

links := make([]Link, len(e.Links))
for i, link := range e.Links {
links[i] = Link{
Domain: link.Domain,
URL: link.URL,
}
}

linkSharedEvent := LinkSharedEvent{
Type: linkShared,
User: e.User,
TimeStamp: e.TimeStamp,
Channel: e.Channel,
MessageTimeStamp: e.MessageTimeStamp,
ThreadTimeStamp: e.ThreadTimeStamp,
Links: links,
EventTimestamp: e.EventTimestamp,
}

if !linkSharedEvent.isValid() {
span.Status = sentry.SpanStatusInvalidArgument
return nil
}
span.Status = sentry.SpanStatusOK

hub.Scope().SetExtra("event", linkSharedEvent)
hub.Scope().SetTag("event_type", linkShared.String())

return &linkSharedEvent
}
4 changes: 4 additions & 0 deletions src/Event/AbstractEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace App\Event;

use App\Http\DiscordClient;
use App\Http\SlackClient;
use Cake\ORM\Locator\LocatorAwareTrait;

Expand All @@ -17,8 +18,10 @@ abstract class AbstractEvent
public const TYPE_APP_MENTION = 'app_mention';
public const TYPE_SLASH_COMMAND = 'slash_command';
public const TYPE_INTERACTIONS_CALLBACK = 'interaction_callback';
public const TYPE_LINK_SHARED = 'link_shared';

protected SlackClient $slackClient;
protected DiscordClient $discordClient;

public string $type;
public string $eventTimestamp;
Expand All @@ -29,6 +32,7 @@ abstract class AbstractEvent
public function __construct()
{
$this->slackClient = new SlackClient();
$this->discordClient = new DiscordClient();
}

/**
Expand Down
29 changes: 11 additions & 18 deletions src/Event/EventFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,16 @@
SentrySdk::getCurrentHub()->getTransaction()->getName() . ' - ' . $eventType
);

switch ($eventType) {
case AbstractEvent::TYPE_MESSAGE:
return new MessageEvent($data);
case AbstractEvent::TYPE_DIRECT_MESSAGE:
return new DirectMessageEvent($data);
case AbstractEvent::TYPE_REACTION_ADDED:
return new ReactionAddedEvent($data);
case AbstractEvent::TYPE_APP_MENTION:
return new AppMentionEvent($data);
case AbstractEvent::TYPE_APP_HOME_OPENED:
return new AppHomeOpenedEvent($data);
case AbstractEvent::TYPE_SLASH_COMMAND:
return new SlashCommandEvent($data);
case AbstractEvent::TYPE_INTERACTIONS_CALLBACK:
return new InteractionsCallbackEvent($data);
default:
throw new Exception('Unknown event type');
}
return match ($eventType) {
AbstractEvent::TYPE_MESSAGE => new MessageEvent($data),
AbstractEvent::TYPE_DIRECT_MESSAGE => new DirectMessageEvent($data),
AbstractEvent::TYPE_REACTION_ADDED => new ReactionAddedEvent($data),
AbstractEvent::TYPE_APP_MENTION => new AppMentionEvent($data),
AbstractEvent::TYPE_APP_HOME_OPENED => new AppHomeOpenedEvent($data),
AbstractEvent::TYPE_SLASH_COMMAND => new SlashCommandEvent($data),
AbstractEvent::TYPE_INTERACTIONS_CALLBACK => new InteractionsCallbackEvent($data),
AbstractEvent::TYPE_LINK_SHARED => new LinkSharedEvent($data),

Check warning on line 39 in src/Event/EventFactory.php

View check run for this annotation

Codecov / codecov/patch

src/Event/EventFactory.php#L37-L39

Added lines #L37 - L39 were not covered by tests
default => throw new Exception('Unknown event type'),
};
}
}
82 changes: 82 additions & 0 deletions src/Event/LinkSharedEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);

namespace App\Event;

class LinkSharedEvent extends AbstractEvent
{
public string $user;
public string $timestamp;
public string $channel;
public string $messageTimeStamp;
public string $threadTimeStamp;
public array $links;
public string $eventTimestamp;

/**
* Constructor
*
* @param array $event Event data.
*/
public function __construct(array $event)

Check warning on line 21 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L21

Added line #L21 was not covered by tests
{
parent::__construct();

Check warning on line 23 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L23

Added line #L23 was not covered by tests

$this->type = self::TYPE_LINK_SHARED;
$this->user = $event['user'];
$this->timestamp = $event['ts'];
$this->channel = $event['channel'];
$this->messageTimeStamp = $event['message_ts'];
$this->threadTimeStamp = $event['thread_ts'];
$this->eventTimestamp = $event['event_ts'];
$this->links = $event['links'];

Check warning on line 32 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L25-L32

Added lines #L25 - L32 were not covered by tests
}

/**
* @inheritDoc
*/
public function process(): void

Check warning on line 38 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L38

Added line #L38 was not covered by tests
{
foreach ($this->links as $link) {
$message = $this->fetchDiscordMessage($link['url']);
if ($message !== null) {
$this->slackClient->unfurl(
channel: $this->channel,
timestamp: $this->messageTimeStamp,
unfurls: [
$link['url'] => [
'blocks' => [
[
'type' => 'section',
'text' => [
'type' => 'mrkdwn',
'text' => $message,
],
],
],
],
],
);

Check warning on line 59 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L40-L59

Added lines #L40 - L59 were not covered by tests
}
}
}

/**
* @param string $url The Discord message URL
* @return string|null The message content
*/
private function fetchDiscordMessage(string $url): ?string

Check warning on line 68 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L68

Added line #L68 was not covered by tests
{
if (!preg_match('#^https://discord\.com/channels/\d+/\d+/\d+$#', $url)) {
return null;

Check warning on line 71 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L70-L71

Added lines #L70 - L71 were not covered by tests
}

$parts = explode('/', $url);
$channelId = $parts[5];
$messageId = $parts[6];

Check warning on line 76 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L74-L76

Added lines #L74 - L76 were not covered by tests

$message = $this->discordClient->getMessage($channelId, $messageId);

Check warning on line 78 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L78

Added line #L78 was not covered by tests

return $message;

Check warning on line 80 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L80

Added line #L80 was not covered by tests
}
}
58 changes: 58 additions & 0 deletions src/Http/DiscordClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);

namespace App\Http;

use function Cake\Core\env;
use function Sentry\captureMessage;
use function Sentry\withScope;

class DiscordClient
{
protected const DISCORD_API_URL = 'discord.com/api/v10';

protected Client $client;

/**
* Constructor.
*/
public function __construct()
{
$this->client = new Client([
'host' => self::DISCORD_API_URL,
'scheme' => 'https',
'headers' => [
'Authorization' => 'Bot ' . env('DISCORD_BOT_TOKEN'),
'Content-Type' => 'application/json',
],
]);
}

/**
* @param string $channelId The channel ID
* @param string $messageId The message ID
* @return string|null The message content
* @see https://discord.com/developers/docs/resources/message#get-channel-message
*/
public function getMessage(string $channelId, string $messageId): ?string

Check warning on line 37 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L37

Added line #L37 was not covered by tests
{
$response = $this->client->get("channels/{$channelId}/messages/{$messageId}");

Check warning on line 39 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L39

Added line #L39 was not covered by tests

if ($response->isSuccess()) {
$json = $response->getJson();

Check warning on line 42 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L41-L42

Added lines #L41 - L42 were not covered by tests

return $json['content'] ?? null;

Check warning on line 44 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L44

Added line #L44 was not covered by tests
}

withScope(function ($scope) use ($response, $channelId, $messageId): void {
$scope->setContext('Discord API', [
'channel_id' => $channelId,
'message_id' => $messageId,
'discord_response' => $response->getJson(),
]);
captureMessage('Discord API error: Failed to fetch message');
});

Check warning on line 54 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L47-L54

Added lines #L47 - L54 were not covered by tests

return null;

Check warning on line 56 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L56

Added line #L56 was not covered by tests
}
}
Loading
Loading