Search in sources :

Example 31 with HttpCallback

use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.

the class TwitchNotificationCommand method preview.

@Command(value = "preview", description = "Preview a twitch notification")
@CommandId(503)
@Examples({ "twitch notification preview 5e45ce6d3688b30ee75201ae" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void preview(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
    Document data = event.getMongo().getTwitchNotification(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong())), Projections.include("streamerId", "message"));
    if (data == null) {
        event.replyFailure("I could not find that notification").queue();
        return;
    }
    String streamerId = data.getString("streamerId");
    Request request = new Request.Builder().url("https://api.twitch.tv/helix/users?id=" + streamerId).addHeader("Authorization", "Bearer " + event.getBot().getTwitchConfig().getToken()).addHeader("Client-Id", event.getBot().getConfig().getTwitchClientId()).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document json = Document.parse(response.body().string());
        List<Document> entries = json.getList("data", Document.class);
        if (entries.isEmpty()) {
            event.replyFailure("The twitch streamer for that notification no longer exists").queue();
            return;
        }
        Document entry = entries.get(0);
        Document message = new JsonFormatter(data.get("message", TwitchManager.DEFAULT_MESSAGE)).addVariable("stream", new TwitchStream("0", TwitchStreamType.LIVE, "https://cdn.discordapp.com/attachments/344091594972069888/969319515714371604/twitch-test-preview.png", "Preview Title", "Preview Game", OffsetDateTime.now())).addVariable("streamer", new TwitchStreamer(entry.getString("id"), entry.getString("display_name"), entry.getString("login"))).parse();
        try {
            MessageUtility.fromWebhookMessage(event.getChannel(), MessageUtility.fromJson(message).build()).queue();
        } catch (IllegalArgumentException e) {
            event.replyFailure(e.getMessage()).queue();
        }
    });
}
Also used : Document(org.bson.Document) TwitchStream(com.sx4.bot.entities.twitch.TwitchStream) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) TwitchManager(com.sx4.bot.managers.TwitchManager) TwitchStreamType(com.sx4.bot.entities.twitch.TwitchStreamType) PagedResult(com.sx4.bot.paged.PagedResult) AggregateOperators(com.sx4.bot.database.mongo.model.AggregateOperators) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) FormatterManager(com.sx4.bot.formatter.FormatterManager) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) TwitchStreamer(com.sx4.bot.entities.twitch.TwitchStreamer) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) java.util(java.util) Command(com.jockie.bot.core.command.Command) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) CommandId(com.sx4.bot.annotations.command.CommandId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Bson(org.bson.conversions.Bson) AdvancedMessage(com.sx4.bot.annotations.argument.AdvancedMessage) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) Argument(com.jockie.bot.core.argument.Argument) Lowercase(com.sx4.bot.annotations.argument.Lowercase) Operators(com.sx4.bot.database.mongo.model.Operators) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) MessageUtility(com.sx4.bot.utility.MessageUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) ErrorCategory(com.mongodb.ErrorCategory) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) TwitchStream(com.sx4.bot.entities.twitch.TwitchStream) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) TwitchStreamer(com.sx4.bot.entities.twitch.TwitchStreamer) Document(org.bson.Document) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Sx4Command(com.sx4.bot.core.Sx4Command) Command(com.jockie.bot.core.command.Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 32 with HttpCallback

use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.

the class YouTubeManager method resubscribeBulk.

public DeleteOneModel<Document> resubscribeBulk(String channelId) {
    long amount = this.bot.getMongo().countYouTubeNotifications(Filters.eq("uploaderId", channelId), new CountOptions().limit(1));
    this.deleteExecutor(channelId);
    DeleteOneModel<Document> model = null;
    if (amount != 0) {
        RequestBody body = new MultipartBody.Builder().addFormDataPart("hub.mode", "subscribe").addFormDataPart("hub.topic", "https://www.youtube.com/xml/feeds/videos.xml?channel_id=" + channelId).addFormDataPart("hub.callback", this.bot.getConfig().getBaseUrl() + "/api/youtube").addFormDataPart("hub.verify", "sync").addFormDataPart("hub.verify_token", this.bot.getConfig().getYouTube()).setType(MultipartBody.FORM).build();
        Request request = new Request.Builder().url("https://pubsubhubbub.appspot.com/subscribe").post(body).build();
        this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            if (response.isSuccessful()) {
                System.out.println("Resubscribed to " + channelId + " for YouTube notifications");
            } else {
                System.err.printf("Failed to resubscribe to %s for YouTube notifications, Code: %d, Message: %s%n", channelId, response.code(), response.body().string());
            }
            response.close();
        });
    } else {
        model = new DeleteOneModel<>(Filters.eq("_id", channelId));
        this.deleteExecutor(channelId);
    }
    return model;
}
Also used : Document(org.bson.Document) BotPermissionException(com.sx4.bot.exceptions.mod.BotPermissionException) Request(okhttp3.Request) java.util(java.util) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) HttpCallback(com.sx4.bot.http.HttpCallback) java.util.concurrent(java.util.concurrent) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Channel(net.dv8tion.jda.api.entities.Channel) RequestBody(okhttp3.RequestBody) HttpException(club.minnced.discord.webhook.exception.HttpException) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) Bson(org.bson.conversions.Bson) OkHttpClient(okhttp3.OkHttpClient) MultipartBody(okhttp3.MultipartBody) Sx4(com.sx4.bot.core.Sx4) YouTubeListener(com.sx4.bot.hooks.YouTubeListener) com.sx4.bot.events.youtube(com.sx4.bot.events.youtube) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) Clock(java.time.Clock) com.mongodb.client.model(com.mongodb.client.model) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage) MultipartBody(okhttp3.MultipartBody) Request(okhttp3.Request) Document(org.bson.Document) RequestBody(okhttp3.RequestBody)

Example 33 with HttpCallback

use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.

the class FreeGameManager method retrieveFreeGOGGames.

public CompletableFuture<GOGFreeGame> retrieveFreeGOGGames() {
    Request resultRequest = new Request.Builder().url("https://gog.com/en").addHeader("Accept-Language", "en").build();
    CompletableFuture<GOGFreeGame> future = new CompletableFuture<>();
    this.bot.getHttpClient().newCall(resultRequest).enqueue((HttpCallback) resultResponse -> {
        org.jsoup.nodes.Document resultsDocument = Jsoup.parse(resultResponse.body().string());
        Element giveawayElement = resultsDocument.getElementsByAttribute("giveaway-banner").first();
        if (giveawayElement == null) {
            return;
        }
        String url = giveawayElement.attr("ng-href");
        Element countdownElement = giveawayElement.getElementsByClass("giveaway-banner__countdown-timer").first();
        OffsetDateTime end = OffsetDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(countdownElement.attr("end-date"))), ZoneOffset.UTC);
        Element imageElement = giveawayElement.getElementsByAttributeValue("type", "image/png").first();
        String imageSource = imageElement.attr("srcset");
        int commaIndex = imageSource.indexOf(',');
        String image = imageSource.substring(0, commaIndex - 3);
        Request gameRequest = new Request.Builder().url("https://gog.com" + url).addHeader("Cookie", "gog_lc=GB_GBP_en-US").build();
        this.bot.getHttpClient().newCall(gameRequest).enqueue((HttpCallback) gameResponse -> {
            org.jsoup.nodes.Document gameDocument = Jsoup.parse(gameResponse.body().string());
            Element element = gameDocument.getElementsByAttributeValue("type", "application/ld+json").first();
            Document data = Document.parse(element.html());
            int id = Integer.parseInt(data.getString("sku"));
            Document offers = data.get("offers", Document.class);
            String priceText = offers.getString("price");
            int price = (int) (Double.parseDouble(priceText) * 100);
            Element titleElement = gameDocument.getElementsByClass("productcard-basics__title").first();
            String title = titleElement.text();
            Element descriptionElement = gameDocument.getElementsByClass("description").first();
            String description = descriptionElement.textNodes().get(0).text();
            Elements infoElements = gameDocument.getElementsByClass("table__row details__rating details__row ");
            String publisher = infoElements.stream().filter(infoElement -> {
                Element labelElement = infoElement.getElementsByClass("details__category table__row-label").first();
                return labelElement.text().contains("Company:");
            }).map(infoElement -> infoElement.getElementsByClass("details__content table__row-content").first()).flatMap(publishers -> publishers.children().stream()).filter(publisherElement -> publisherElement.attr("href").contains("publishers")).map(Element::text).findFirst().orElse(null);
            GOGFreeGame game = GOGFreeGame.fromData(id, title, description, publisher, url, price, end, "https:" + image.trim());
            if (this.isAnnounced(game)) {
                return;
            }
            future.complete(game);
        });
    });
    return future;
}
Also used : Document(org.bson.Document) java.util(java.util) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Channel(net.dv8tion.jda.api.entities.Channel) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) Bson(org.bson.conversions.Bson) Formatter(com.sx4.bot.formatter.Formatter) UpdateResult(com.mongodb.client.result.UpdateResult) Sx4(com.sx4.bot.core.Sx4) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Element(org.jsoup.nodes.Element) Duration(java.time.Duration) FreeGameUtility(com.sx4.bot.utility.FreeGameUtility) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) ZoneOffset(java.time.ZoneOffset) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Operators(com.sx4.bot.database.mongo.model.Operators) Request(okhttp3.Request) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) HttpCallback(com.sx4.bot.http.HttpCallback) java.util.concurrent(java.util.concurrent) Predicate(java.util.function.Predicate) MessageUtility(com.sx4.bot.utility.MessageUtility) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) HttpException(club.minnced.discord.webhook.exception.HttpException) OkHttpClient(okhttp3.OkHttpClient) OffsetDateTime(java.time.OffsetDateTime) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Jsoup(org.jsoup.Jsoup) Elements(org.jsoup.select.Elements) com.sx4.bot.entities.info.game(com.sx4.bot.entities.info.game) Element(org.jsoup.nodes.Element) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Document(org.bson.Document) Elements(org.jsoup.select.Elements) OffsetDateTime(java.time.OffsetDateTime)

Example 34 with HttpCallback

use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.

the class SkinPortManager method retrieveCSRFData.

public void retrieveCSRFData() {
    Request request = new Request.Builder().url("https://skinport.com/api/data").build();
    this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        List<String> cookies = response.headers("Set-Cookie");
        String cookie = cookies.get(0);
        this.cookie = cookie.substring(0, cookie.indexOf(';'));
        Document data = Document.parse(response.body().string());
        this.csrf = data.getString("csrf");
        this.currency = data.getString("currency");
        this.currencies = data.get("rates", Document.class);
    });
}
Also used : Document(org.bson.Document) TimeUnit(java.util.concurrent.TimeUnit) Request(okhttp3.Request) List(java.util.List) Sx4(com.sx4.bot.core.Sx4) HttpCallback(com.sx4.bot.http.HttpCallback) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Executors(java.util.concurrent.Executors) Request(okhttp3.Request) List(java.util.List) Document(org.bson.Document)

Example 35 with HttpCallback

use of com.sx4.bot.http.HttpCallback 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)

Aggregations

HttpCallback (com.sx4.bot.http.HttpCallback)85 Request (okhttp3.Request)83 ModuleCategory (com.sx4.bot.category.ModuleCategory)68 Sx4Command (com.sx4.bot.core.Sx4Command)68 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)68 Permission (net.dv8tion.jda.api.Permission)67 Argument (com.jockie.bot.core.argument.Argument)63 Document (org.bson.Document)51 ImageRequest (com.sx4.bot.entities.image.ImageRequest)35 ImageUtility (com.sx4.bot.utility.ImageUtility)33 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)33 ImageUrl (com.sx4.bot.annotations.argument.ImageUrl)28 PagedResult (com.sx4.bot.paged.PagedResult)24 StandardCharsets (java.nio.charset.StandardCharsets)23 URLEncoder (java.net.URLEncoder)22 java.util (java.util)20 OffsetDateTime (java.time.OffsetDateTime)18 Collectors (java.util.stream.Collectors)18 Bson (org.bson.conversions.Bson)17 Command (com.jockie.bot.core.command.Command)16