Search in sources :

Example 1 with TwitchSubscriptionType

use of com.sx4.bot.entities.twitch.TwitchSubscriptionType in project Sx4 by sx4-discord-bot.

the class TwitchEndpoint method postTwitch.

@POST
@Path("twitch")
public Response postTwitch(final String body, @HeaderParam("Twitch-Eventsub-Message-Id") String messageId, @HeaderParam("Twitch-Eventsub-Message-Timestamp") String timestamp, @HeaderParam("Twitch-Eventsub-Message-Signature") String signature, @HeaderParam("Twitch-Eventsub-Message-Type") String type) {
    String hash;
    try {
        hash = "sha256=" + HmacUtility.getSignatureHex(this.bot.getConfig().getTwitchEventSecret(), messageId + timestamp + body, HmacUtility.HMAC_SHA256);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        return Response.status(500).build();
    }
    if (!hash.equals(signature)) {
        return Response.status(401).build();
    }
    if (!this.messageIds.add(messageId)) {
        return Response.status(204).build();
    }
    Document data = Document.parse(body);
    Document subscription = data.get("subscription", Document.class);
    TwitchSubscriptionType subscriptionType = TwitchSubscriptionType.fromIdentifier(subscription.getString("type"));
    if (subscriptionType == null) {
        return Response.status(204).build();
    }
    if (type.equals("webhook_callback_verification")) {
        Document subscriptionData = new Document("subscriptionId", subscription.getString("id")).append("streamerId", subscription.getEmbedded(List.of("condition", "broadcaster_user_id"), String.class)).append("type", subscriptionType.getId());
        this.bot.getMongo().insertTwitchSubscription(subscriptionData).whenComplete(MongoDatabase.exceptionally());
        return Response.ok(data.getString("challenge")).build();
    }
    if (subscriptionType == TwitchSubscriptionType.ONLINE) {
        Document event = data.get("event", Document.class);
        String streamId = event.getString("id");
        String streamerName = event.getString("broadcaster_user_name");
        String streamerId = event.getString("broadcaster_user_id");
        String streamerLogin = event.getString("broadcaster_user_login");
        TwitchStreamType streamType = TwitchStreamType.fromIdentifier(event.getString("type"));
        OffsetDateTime streamStart = OffsetDateTime.parse(event.getString("started_at"));
        Request request = new Request.Builder().url("https://api.twitch.tv/helix/streams?user_id=" + streamerId).addHeader("Authorization", "Bearer " + this.bot.getTwitchConfig().getToken()).addHeader("Client-Id", this.bot.getConfig().getTwitchClientId()).build();
        this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            Document json = Document.parse(response.body().string());
            Document stream = json.getList("data", Document.class).stream().filter(d -> d.getString("type").equals(streamType.getIdentifier())).findFirst().orElse(null);
            if (stream == null) {
                System.err.println("Failed to retrieve stream data for streamer id: " + streamerId);
                return;
            }
            String query = "?" + this.random.nextString(5) + "=" + this.random.nextString(5);
            String title = stream.getString("title");
            String game = stream.getString("game_name");
            String preview = "https://static-cdn.jtvnw.net/previews-ttv/live_user_" + streamerLogin + "-1320x744.png" + query;
            this.bot.getTwitchManager().onEvent(new TwitchStreamStartEvent(new TwitchStream(streamId, streamType, preview, title, game, streamStart), new TwitchStreamer(streamerId, streamerName, streamerLogin)));
        });
    } else if (subscriptionType == TwitchSubscriptionType.REVOCATION) {
        String status = subscription.getString("status");
        if (status.equals("user_removed")) {
            this.bot.getMongo().deleteManyTwitchNotifications(Filters.eq("streamerId", subscription.getEmbedded(List.of("condition", "broadcaster_user_id"), String.class))).whenComplete(MongoDatabase.exceptionally());
        }
    }
    return Response.status(204).build();
}
Also used : Document(org.bson.Document) TwitchStream(com.sx4.bot.entities.twitch.TwitchStream) Request(okhttp3.Request) HmacUtility(com.sx4.bot.utility.HmacUtility) POST(javax.ws.rs.POST) TwitchStreamStartEvent(com.sx4.bot.events.twitch.TwitchStreamStartEvent) HttpCallback(com.sx4.bot.http.HttpCallback) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Path(javax.ws.rs.Path) Set(java.util.Set) TwitchStreamType(com.sx4.bot.entities.twitch.TwitchStreamType) RandomString(com.sx4.bot.utility.RandomString) Filters(com.mongodb.client.model.Filters) HashSet(java.util.HashSet) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) Response(javax.ws.rs.core.Response) Sx4(com.sx4.bot.core.Sx4) TwitchSubscriptionType(com.sx4.bot.entities.twitch.TwitchSubscriptionType) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) TwitchStreamer(com.sx4.bot.entities.twitch.TwitchStreamer) HeaderParam(javax.ws.rs.HeaderParam) InvalidKeyException(java.security.InvalidKeyException) TwitchStream(com.sx4.bot.entities.twitch.TwitchStream) TwitchStreamType(com.sx4.bot.entities.twitch.TwitchStreamType) Request(okhttp3.Request) RandomString(com.sx4.bot.utility.RandomString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) Document(org.bson.Document) TwitchSubscriptionType(com.sx4.bot.entities.twitch.TwitchSubscriptionType) TwitchStreamStartEvent(com.sx4.bot.events.twitch.TwitchStreamStartEvent) OffsetDateTime(java.time.OffsetDateTime) TwitchStreamer(com.sx4.bot.entities.twitch.TwitchStreamer) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 2 with TwitchSubscriptionType

use of com.sx4.bot.entities.twitch.TwitchSubscriptionType in project Sx4 by sx4-discord-bot.

the class TwitchManager method subscribe.

public void subscribe(String streamerId, TwitchSubscriptionType type) {
    Document transport = new Document("method", "webhook").append("callback", this.bot.getConfig().getBaseUrl() + "/api/twitch").append("secret", this.bot.getConfig().getTwitchEventSecret());
    Document body = new Document("type", type.getIdentifier()).append("version", "1").append("condition", new Document("broadcaster_user_id", streamerId)).append("transport", transport);
    Request request = new Request.Builder().url("https://api.twitch.tv/helix/eventsub/subscriptions").post(RequestBody.create(MediaType.parse("application/json"), body.toJson())).addHeader("Authorization", "Bearer " + this.bot.getTwitchConfig().getToken()).addHeader("Client-Id", this.bot.getConfig().getTwitchClientId()).build();
    this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (!response.isSuccessful()) {
            System.err.printf("Failed to resubscribe to %s for Twitch notifications, Code: %d, Message: %s%n", streamerId, response.code(), response.body().string());
        } else {
            System.out.println("Subscribed to " + streamerId + " for Twitch notifications");
        }
        response.close();
    });
}
Also used : Document(org.bson.Document) java.util(java.util) TwitchStreamStartEvent(com.sx4.bot.events.twitch.TwitchStreamStartEvent) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) CompletableFuture(java.util.concurrent.CompletableFuture) RequestBody(okhttp3.RequestBody) Filters(com.mongodb.client.model.Filters) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) Bson(org.bson.conversions.Bson) FindOneAndDeleteOptions(com.mongodb.client.model.FindOneAndDeleteOptions) TwitchListener(com.sx4.bot.hooks.TwitchListener) Sx4(com.sx4.bot.core.Sx4) TwitchSubscriptionType(com.sx4.bot.entities.twitch.TwitchSubscriptionType) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage) MediaType(okhttp3.MediaType) BotPermissionException(com.sx4.bot.exceptions.mod.BotPermissionException) Request(okhttp3.Request) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) HttpCallback(com.sx4.bot.http.HttpCallback) Updates(com.mongodb.client.model.Updates) CompletionException(java.util.concurrent.CompletionException) Executors(java.util.concurrent.Executors) HttpException(club.minnced.discord.webhook.exception.HttpException) TwitchEvent(com.sx4.bot.events.twitch.TwitchEvent) OkHttpClient(okhttp3.OkHttpClient) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) Request(okhttp3.Request) Document(org.bson.Document)

Aggregations

Filters (com.mongodb.client.model.Filters)2 Sx4 (com.sx4.bot.core.Sx4)2 TwitchSubscriptionType (com.sx4.bot.entities.twitch.TwitchSubscriptionType)2 TwitchStreamStartEvent (com.sx4.bot.events.twitch.TwitchStreamStartEvent)2 HttpCallback (com.sx4.bot.http.HttpCallback)2 Request (okhttp3.Request)2 Document (org.bson.Document)2 HttpException (club.minnced.discord.webhook.exception.HttpException)1 WebhookMessage (club.minnced.discord.webhook.send.WebhookMessage)1 FindOneAndDeleteOptions (com.mongodb.client.model.FindOneAndDeleteOptions)1 Projections (com.mongodb.client.model.Projections)1 Updates (com.mongodb.client.model.Updates)1 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)1 TwitchStream (com.sx4.bot.entities.twitch.TwitchStream)1 TwitchStreamType (com.sx4.bot.entities.twitch.TwitchStreamType)1 TwitchStreamer (com.sx4.bot.entities.twitch.TwitchStreamer)1 ReadonlyMessage (com.sx4.bot.entities.webhook.ReadonlyMessage)1 WebhookClient (com.sx4.bot.entities.webhook.WebhookClient)1 TwitchEvent (com.sx4.bot.events.twitch.TwitchEvent)1 BotPermissionException (com.sx4.bot.exceptions.mod.BotPermissionException)1