Search in sources :

Example 1 with Blueprint

use of com.demod.fbsr.Blueprint in project Factorio-FBSR by demodude4u.

the class BlueprintBotDiscordService method handleBlueprintUpgradeBeltsCommand.

private void handleBlueprintUpgradeBeltsCommand(SlashCommandEvent event) {
    String content = event.getCommandString();
    Optional<Attachment> attachment = event.optParamAttachment("file");
    if (attachment.isPresent()) {
        content += " " + attachment.get().getUrl();
    }
    List<BlueprintStringData> blueprintStringDatas = BlueprintFinder.search(content, event.getReporting());
    int upgradedCount = 0;
    for (BlueprintStringData blueprintStringData : blueprintStringDatas) {
        for (Blueprint blueprint : blueprintStringData.getBlueprints()) {
            for (BlueprintEntity blueprintEntity : blueprint.getEntities()) {
                String upgradeName = upgradeBeltsEntityMapping.get(blueprintEntity.getName());
                if (upgradeName != null) {
                    blueprintEntity.json().put("name", upgradeName);
                    upgradedCount++;
                }
            }
        }
    }
    if (upgradedCount > 0) {
        for (BlueprintStringData blueprintStringData : blueprintStringDatas) {
            try {
                event.replyFile(BlueprintStringData.encode(blueprintStringData.json()).getBytes(), "blueprint.txt");
            } catch (IOException e) {
                event.getReporting().addException(e);
            }
        }
        event.reply("Upgraded " + upgradedCount + " entities.");
    } else if (blueprintStringDatas.stream().anyMatch(d -> !d.getBlueprints().isEmpty())) {
        event.replyIfNoException("I couldn't find anything to upgrade!");
    } else {
        event.replyIfNoException("No blueprint found!");
    }
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Arrays(java.util.Arrays) EventReply(com.demod.dcba.EventReply) URL(java.net.URL) FBSR(com.demod.fbsr.FBSR) Permission(net.dv8tion.jda.api.Permission) SlashCommandHandler(com.demod.dcba.SlashCommandHandler) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) DataTable(com.demod.factorio.DataTable) RenderUtils(com.demod.fbsr.RenderUtils) JSONException(org.json.JSONException) Matcher(java.util.regex.Matcher) JSONObject(org.json.JSONObject) Map(java.util.Map) ZipEntry(java.util.zip.ZipEntry) WebUtils(com.demod.fbsr.WebUtils) Message(net.dv8tion.jda.api.entities.Message) BufferedImage(java.awt.image.BufferedImage) DataPrototype(com.demod.factorio.prototype.DataPrototype) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) Collectors(java.util.stream.Collectors) Config(com.demod.factorio.Config) BlueprintEntity(com.demod.fbsr.BlueprintEntity) List(java.util.List) FactorioData(com.demod.factorio.FactorioData) MessageCommandEvent(com.demod.dcba.MessageCommandEvent) Entry(java.util.Map.Entry) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) BlueprintStringData(com.demod.fbsr.BlueprintStringData) ZipOutputStream(java.util.zip.ZipOutputStream) Blueprint(com.demod.fbsr.Blueprint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) WatchdogReporter(com.demod.fbsr.app.WatchdogService.WatchdogReporter) ImmutableList(com.google.common.collect.ImmutableList) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) SlashCommandEvent(com.demod.dcba.SlashCommandEvent) SimpleEntry(java.util.AbstractMap.SimpleEntry) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) MapVersion(com.demod.fbsr.MapVersion) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandReporting(com.demod.dcba.CommandReporting) DCBA(com.demod.dcba.DCBA) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Utils(com.demod.factorio.Utils) DiscordBot(com.demod.dcba.DiscordBot) LuaValue(org.luaj.vm2.LuaValue) AutoCompleteHandler(com.demod.dcba.AutoCompleteHandler) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) ArrayDeque(java.util.ArrayDeque) BlueprintFinder(com.demod.fbsr.BlueprintFinder) ChunkingFilter(net.dv8tion.jda.api.utils.ChunkingFilter) JSONArray(org.json.JSONArray) BlueprintEntity(com.demod.fbsr.BlueprintEntity) Blueprint(com.demod.fbsr.Blueprint) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) BlueprintStringData(com.demod.fbsr.BlueprintStringData) IOException(java.io.IOException) Blueprint(com.demod.fbsr.Blueprint)

Example 2 with Blueprint

use of com.demod.fbsr.Blueprint in project Factorio-FBSR by demodude4u.

the class BlueprintBotDiscordService method processBlueprints.

private List<EmbedBuilder> processBlueprints(List<BlueprintStringData> blueprintStrings, CommandReporting reporting, JSONObject options) throws IOException {
    List<EmbedBuilder> embedBuilders = new ArrayList<>();
    List<Entry<Optional<String>, BufferedImage>> images = new ArrayList<>();
    for (BlueprintStringData blueprintString : blueprintStrings) {
        System.out.println("Parsing blueprints: " + blueprintString.getBlueprints().size());
        for (Blueprint blueprint : blueprintString.getBlueprints()) {
            try {
                BufferedImage image = FBSR.renderBlueprint(blueprint, reporting, options);
                images.add(new SimpleEntry<>(blueprint.getLabel(), image));
            } catch (Exception e) {
                reporting.addException(e);
            }
        }
    }
    List<Long> renderTimes = blueprintStrings.stream().flatMap(d -> d.getBlueprints().stream()).flatMap(b -> (b.getRenderTime().isPresent() ? Arrays.asList(b.getRenderTime().getAsLong()) : ImmutableList.<Long>of()).stream()).collect(Collectors.toList());
    if (!renderTimes.isEmpty()) {
        reporting.addField(new Field("Render Time", renderTimes.stream().mapToLong(l -> l).sum() + " ms" + (renderTimes.size() > 1 ? (" [" + renderTimes.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]") : ""), true));
    }
    if (images.size() == 0) {
        embedBuilders.add(new EmbedBuilder().setDescription("Blueprint not found!"));
    } else if (images.size() == 1) {
        Entry<Optional<String>, BufferedImage> entry = images.get(0);
        BufferedImage image = entry.getValue();
        String url = WebUtils.uploadToHostingService("blueprint.png", image);
        EmbedBuilder builder = new EmbedBuilder();
        builder.setImage(url);
        embedBuilders.add(builder);
    } else {
        List<Entry<String, String>> links = new ArrayList<>();
        for (Entry<Optional<String>, BufferedImage> entry : images) {
            BufferedImage image = entry.getValue();
            links.add(new SimpleEntry<>(WebUtils.uploadToHostingService("blueprint.png", image), entry.getKey().orElse("")));
        }
        ArrayDeque<String> lines = new ArrayDeque<>();
        for (int i = 0; i < links.size(); i++) {
            Entry<String, String> entry = links.get(i);
            if (entry.getValue() != null && !entry.getValue().trim().isEmpty()) {
                lines.add("[" + entry.getValue().trim() + "](" + entry.getKey() + ")");
            } else {
                lines.add("[Blueprint Image " + (i + 1) + "](" + entry.getKey() + ")");
            }
        }
        while (!lines.isEmpty()) {
            EmbedBuilder builder = new EmbedBuilder();
            for (int i = 0; i < 3 && !lines.isEmpty(); i++) {
                StringBuilder description = new StringBuilder();
                while (!lines.isEmpty()) {
                    if (description.length() + lines.peek().length() + 1 < MessageEmbed.VALUE_MAX_LENGTH) {
                        description.append(lines.pop()).append('\n');
                    } else {
                        break;
                    }
                }
                builder.addField("", description.toString(), true);
            }
            embedBuilders.add(builder);
        }
    }
    if (!blueprintStrings.isEmpty() && !embedBuilders.isEmpty()) {
        List<String> links = new ArrayList<>();
        for (int i = 0; i < blueprintStrings.size(); i++) {
            BlueprintStringData blueprintString = blueprintStrings.get(i);
            String label = blueprintString.getLabel().orElse((blueprintString.getBlueprints().size() > 1 ? "Blueprint Book " : "Blueprint ") + (i + 1));
            String link = WebUtils.uploadToHostingService("blueprint.txt", blueprintString.toString().getBytes());
            links.add("[" + label + "](" + link + ")");
        }
        embedBuilders.get(0).getFields().add(0, new Field("Blueprint String" + (blueprintStrings.size() > 1 ? "s" : ""), links.stream().collect(Collectors.joining("\n")), false));
    }
    return embedBuilders;
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Arrays(java.util.Arrays) EventReply(com.demod.dcba.EventReply) URL(java.net.URL) FBSR(com.demod.fbsr.FBSR) Permission(net.dv8tion.jda.api.Permission) SlashCommandHandler(com.demod.dcba.SlashCommandHandler) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) DataTable(com.demod.factorio.DataTable) RenderUtils(com.demod.fbsr.RenderUtils) JSONException(org.json.JSONException) Matcher(java.util.regex.Matcher) JSONObject(org.json.JSONObject) Map(java.util.Map) ZipEntry(java.util.zip.ZipEntry) WebUtils(com.demod.fbsr.WebUtils) Message(net.dv8tion.jda.api.entities.Message) BufferedImage(java.awt.image.BufferedImage) DataPrototype(com.demod.factorio.prototype.DataPrototype) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) Collectors(java.util.stream.Collectors) Config(com.demod.factorio.Config) BlueprintEntity(com.demod.fbsr.BlueprintEntity) List(java.util.List) FactorioData(com.demod.factorio.FactorioData) MessageCommandEvent(com.demod.dcba.MessageCommandEvent) Entry(java.util.Map.Entry) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) BlueprintStringData(com.demod.fbsr.BlueprintStringData) ZipOutputStream(java.util.zip.ZipOutputStream) Blueprint(com.demod.fbsr.Blueprint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) WatchdogReporter(com.demod.fbsr.app.WatchdogService.WatchdogReporter) ImmutableList(com.google.common.collect.ImmutableList) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) SlashCommandEvent(com.demod.dcba.SlashCommandEvent) SimpleEntry(java.util.AbstractMap.SimpleEntry) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) MapVersion(com.demod.fbsr.MapVersion) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandReporting(com.demod.dcba.CommandReporting) DCBA(com.demod.dcba.DCBA) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Utils(com.demod.factorio.Utils) DiscordBot(com.demod.dcba.DiscordBot) LuaValue(org.luaj.vm2.LuaValue) AutoCompleteHandler(com.demod.dcba.AutoCompleteHandler) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) ArrayDeque(java.util.ArrayDeque) BlueprintFinder(com.demod.fbsr.BlueprintFinder) ChunkingFilter(net.dv8tion.jda.api.utils.ChunkingFilter) JSONArray(org.json.JSONArray) Blueprint(com.demod.fbsr.Blueprint) SimpleEntry(java.util.AbstractMap.SimpleEntry) ArrayList(java.util.ArrayList) BlueprintStringData(com.demod.fbsr.BlueprintStringData) BufferedImage(java.awt.image.BufferedImage) JSONException(org.json.JSONException) IOException(java.io.IOException) ArrayDeque(java.util.ArrayDeque) Blueprint(com.demod.fbsr.Blueprint) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ZipEntry(java.util.zip.ZipEntry) Entry(java.util.Map.Entry) SimpleEntry(java.util.AbstractMap.SimpleEntry) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList)

Example 3 with Blueprint

use of com.demod.fbsr.Blueprint in project Factorio-FBSR by demodude4u.

the class BlueprintBotDiscordService method handleBlueprintTotalsCommand.

private void handleBlueprintTotalsCommand(SlashCommandEvent event) {
    DataTable table;
    try {
        table = FactorioData.getTable();
    } catch (JSONException | IOException e1) {
        throw new InternalError(e1);
    }
    String content = event.getCommandString();
    Optional<Attachment> attachment = event.optParamAttachment("file");
    if (attachment.isPresent()) {
        content += " " + attachment.get().getUrl();
    }
    List<BlueprintStringData> blueprintStringDatas = BlueprintFinder.search(content, event.getReporting());
    Map<String, Double> totalItems = new LinkedHashMap<>();
    for (BlueprintStringData blueprintStringData : blueprintStringDatas) {
        for (Blueprint blueprint : blueprintStringData.getBlueprints()) {
            Map<String, Double> items = FBSR.generateSummedTotalItems(table, blueprint);
            items.forEach((k, v) -> {
                totalItems.compute(k, ($, old) -> old == null ? v : old + v);
            });
        }
    }
    if (!totalItems.isEmpty()) {
        String responseContent = totalItems.entrySet().stream().sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey())).map(e -> e.getKey() + ": " + RenderUtils.fmtDouble2(e.getValue())).collect(Collectors.joining("\n"));
        String response = "```ldif\n" + responseContent + "```";
        if (response.length() < 2000) {
            event.reply(response);
        } else {
            event.replyFile(responseContent.getBytes(), "totals.txt");
        }
    } else if (blueprintStringDatas.stream().anyMatch(d -> !d.getBlueprints().isEmpty())) {
        event.replyIfNoException("I couldn't find any items!");
    } else {
        event.replyIfNoException("No blueprint found!");
    }
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Arrays(java.util.Arrays) EventReply(com.demod.dcba.EventReply) URL(java.net.URL) FBSR(com.demod.fbsr.FBSR) Permission(net.dv8tion.jda.api.Permission) SlashCommandHandler(com.demod.dcba.SlashCommandHandler) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) DataTable(com.demod.factorio.DataTable) RenderUtils(com.demod.fbsr.RenderUtils) JSONException(org.json.JSONException) Matcher(java.util.regex.Matcher) JSONObject(org.json.JSONObject) Map(java.util.Map) ZipEntry(java.util.zip.ZipEntry) WebUtils(com.demod.fbsr.WebUtils) Message(net.dv8tion.jda.api.entities.Message) BufferedImage(java.awt.image.BufferedImage) DataPrototype(com.demod.factorio.prototype.DataPrototype) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) Collectors(java.util.stream.Collectors) Config(com.demod.factorio.Config) BlueprintEntity(com.demod.fbsr.BlueprintEntity) List(java.util.List) FactorioData(com.demod.factorio.FactorioData) MessageCommandEvent(com.demod.dcba.MessageCommandEvent) Entry(java.util.Map.Entry) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) BlueprintStringData(com.demod.fbsr.BlueprintStringData) ZipOutputStream(java.util.zip.ZipOutputStream) Blueprint(com.demod.fbsr.Blueprint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) WatchdogReporter(com.demod.fbsr.app.WatchdogService.WatchdogReporter) ImmutableList(com.google.common.collect.ImmutableList) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) SlashCommandEvent(com.demod.dcba.SlashCommandEvent) SimpleEntry(java.util.AbstractMap.SimpleEntry) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) MapVersion(com.demod.fbsr.MapVersion) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandReporting(com.demod.dcba.CommandReporting) DCBA(com.demod.dcba.DCBA) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Utils(com.demod.factorio.Utils) DiscordBot(com.demod.dcba.DiscordBot) LuaValue(org.luaj.vm2.LuaValue) AutoCompleteHandler(com.demod.dcba.AutoCompleteHandler) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) ArrayDeque(java.util.ArrayDeque) BlueprintFinder(com.demod.fbsr.BlueprintFinder) ChunkingFilter(net.dv8tion.jda.api.utils.ChunkingFilter) JSONArray(org.json.JSONArray) DataTable(com.demod.factorio.DataTable) Blueprint(com.demod.fbsr.Blueprint) JSONException(org.json.JSONException) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) BlueprintStringData(com.demod.fbsr.BlueprintStringData) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap)

Example 4 with Blueprint

use of com.demod.fbsr.Blueprint in project Factorio-FBSR by demodude4u.

the class BlueprintBotDiscordService method handleBlueprintBookExtractCommand.

private void handleBlueprintBookExtractCommand(SlashCommandEvent event) {
    String content = event.getCommandString();
    Optional<Attachment> attachment = event.optParamAttachment("file");
    if (attachment.isPresent()) {
        content += " " + attachment.get().getUrl();
    }
    List<BlueprintStringData> blueprintStringDatas = BlueprintFinder.search(content, event.getReporting());
    List<Blueprint> blueprints = blueprintStringDatas.stream().flatMap(bs -> bs.getBlueprints().stream()).collect(Collectors.toList());
    List<Entry<String, String>> links = new ArrayList<>();
    for (Blueprint blueprint : blueprints) {
        try {
            blueprint.json().remove("index");
            String url = WebUtils.uploadToHostingService("blueprint.txt", BlueprintStringData.encode(blueprint.json()).getBytes());
            links.add(new SimpleEntry<>(url, blueprint.getLabel().orElse(null)));
        } catch (Exception e) {
            event.getReporting().addException(e);
        }
    }
    List<EmbedBuilder> embedBuilders = new ArrayList<>();
    if (!links.isEmpty()) {
        ArrayDeque<String> lines = links.stream().map(p -> (p.getValue() != null && !p.getValue().isEmpty()) ? ("[" + p.getValue() + "](" + p.getKey() + ")") : p.getKey()).collect(Collectors.toCollection(ArrayDeque::new));
        while (!lines.isEmpty()) {
            EmbedBuilder builder = new EmbedBuilder();
            StringBuilder description = new StringBuilder();
            while (!lines.isEmpty()) {
                if (description.length() + lines.peek().length() + 1 < MessageEmbed.DESCRIPTION_MAX_LENGTH) {
                    description.append(lines.pop()).append('\n');
                } else {
                    break;
                }
            }
            builder.setDescription(description);
            embedBuilders.add(builder);
        }
    } else {
        embedBuilders.add(new EmbedBuilder().setDescription("Blueprint not found!"));
    }
    List<MessageEmbed> embeds = embedBuilders.stream().map(EmbedBuilder::build).collect(Collectors.toList());
    for (MessageEmbed embed : embeds) {
        event.replyEmbed(embed);
    }
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Arrays(java.util.Arrays) EventReply(com.demod.dcba.EventReply) URL(java.net.URL) FBSR(com.demod.fbsr.FBSR) Permission(net.dv8tion.jda.api.Permission) SlashCommandHandler(com.demod.dcba.SlashCommandHandler) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) DataTable(com.demod.factorio.DataTable) RenderUtils(com.demod.fbsr.RenderUtils) JSONException(org.json.JSONException) Matcher(java.util.regex.Matcher) JSONObject(org.json.JSONObject) Map(java.util.Map) ZipEntry(java.util.zip.ZipEntry) WebUtils(com.demod.fbsr.WebUtils) Message(net.dv8tion.jda.api.entities.Message) BufferedImage(java.awt.image.BufferedImage) DataPrototype(com.demod.factorio.prototype.DataPrototype) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) Collectors(java.util.stream.Collectors) Config(com.demod.factorio.Config) BlueprintEntity(com.demod.fbsr.BlueprintEntity) List(java.util.List) FactorioData(com.demod.factorio.FactorioData) MessageCommandEvent(com.demod.dcba.MessageCommandEvent) Entry(java.util.Map.Entry) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) BlueprintStringData(com.demod.fbsr.BlueprintStringData) ZipOutputStream(java.util.zip.ZipOutputStream) Blueprint(com.demod.fbsr.Blueprint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) WatchdogReporter(com.demod.fbsr.app.WatchdogService.WatchdogReporter) ImmutableList(com.google.common.collect.ImmutableList) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) SlashCommandEvent(com.demod.dcba.SlashCommandEvent) SimpleEntry(java.util.AbstractMap.SimpleEntry) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) MapVersion(com.demod.fbsr.MapVersion) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandReporting(com.demod.dcba.CommandReporting) DCBA(com.demod.dcba.DCBA) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Utils(com.demod.factorio.Utils) DiscordBot(com.demod.dcba.DiscordBot) LuaValue(org.luaj.vm2.LuaValue) AutoCompleteHandler(com.demod.dcba.AutoCompleteHandler) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) ArrayDeque(java.util.ArrayDeque) BlueprintFinder(com.demod.fbsr.BlueprintFinder) ChunkingFilter(net.dv8tion.jda.api.utils.ChunkingFilter) JSONArray(org.json.JSONArray) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Blueprint(com.demod.fbsr.Blueprint) ArrayList(java.util.ArrayList) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) BlueprintStringData(com.demod.fbsr.BlueprintStringData) JSONException(org.json.JSONException) IOException(java.io.IOException) ZipEntry(java.util.zip.ZipEntry) Entry(java.util.Map.Entry) SimpleEntry(java.util.AbstractMap.SimpleEntry) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder)

Example 5 with Blueprint

use of com.demod.fbsr.Blueprint in project Factorio-FBSR by demodude4u.

the class WebAPIService method startUp.

@Override
protected void startUp() {
    ServiceFinder.addService(this);
    configJson = Config.get().getJSONObject("webapi");
    String address = configJson.optString("bind", "0.0.0.0");
    int port = configJson.optInt("port", 80);
    On.address(address).port(port);
    On.post("/blueprint").serve((req, resp) -> {
        System.out.println("Web API POST!");
        CommandReporting reporting = new CommandReporting("Web API / " + req.clientIpAddress() + " / " + Optional.ofNullable(req.header("User-Agent", null)).orElse("<Unknown>"), null, Instant.now());
        try {
            JSONObject body = null;
            BufferedImage returnSingleImage = null;
            List<String> infos = new ArrayList<>();
            List<Entry<Optional<String>, String>> imageLinks = new ArrayList<>();
            boolean useLocalStorage = configJson.optBoolean("use-local-storage", false);
            try {
                if (req.body() == null) {
                    resp.code(400);
                    resp.plain("Body is empty!");
                    reporting.addException(new IllegalArgumentException("Body is empty!"));
                    return resp;
                }
                try {
                    body = new JSONObject(new String(req.body()));
                } catch (Exception e) {
                    reporting.addException(e);
                    resp.code(400);
                    resp.plain("Malformed JSON: " + e.getMessage());
                    return resp;
                }
                reporting.setCommand(body.toString(2));
                /*
					 * { "blueprint": "0e...", (required) "max-width": 1234, "max-height": 1234,
					 * "show-info-panels": false } | v { "info": [ "message 1!", "message 2!", ...
					 * ], "images": [ { "label": "Blueprint Label", "link":
					 * "https://cdn.discordapp.com/..." (or) "1563569893008.png" } ] }
					 */
                String content = body.getString("blueprint");
                List<BlueprintStringData> blueprintStrings = BlueprintFinder.search(content, reporting);
                List<Blueprint> blueprints = blueprintStrings.stream().flatMap(s -> s.getBlueprints().stream()).collect(Collectors.toList());
                for (Blueprint blueprint : blueprints) {
                    try {
                        BufferedImage image = FBSR.renderBlueprint(blueprint, reporting, body);
                        if (body.optBoolean("return-single-image")) {
                            returnSingleImage = image;
                            break;
                        }
                        if (useLocalStorage) {
                            File localStorageFolder = new File(configJson.getString("local-storage"));
                            String imageLink = saveToLocalStorage(localStorageFolder, image);
                            imageLinks.add(new SimpleEntry<>(blueprint.getLabel(), imageLink));
                        } else {
                            imageLinks.add(new SimpleEntry<>(blueprint.getLabel(), WebUtils.uploadToHostingService("blueprint.png", image).toString()));
                        }
                    } catch (Exception e) {
                        reporting.addException(e);
                    }
                }
                List<Long> renderTimes = blueprintStrings.stream().flatMap(d -> d.getBlueprints().stream()).flatMap(b -> (b.getRenderTime().isPresent() ? Arrays.asList(b.getRenderTime().getAsLong()) : ImmutableList.<Long>of()).stream()).collect(Collectors.toList());
                if (!renderTimes.isEmpty()) {
                    reporting.addField(new Field("Render Time", renderTimes.stream().mapToLong(l -> l).sum() + " ms" + (renderTimes.size() > 1 ? (" [" + renderTimes.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]") : ""), true));
                }
                if (blueprintStrings.stream().anyMatch(d -> d.getBlueprints().stream().anyMatch(b -> b.isModsDetected()))) {
                    infos.add("(Modded features are shown as question marks)");
                }
            } catch (Exception e) {
                reporting.addException(e);
            }
            if (returnSingleImage != null) {
                resp.contentType(MediaType.IMAGE_PNG);
                try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                    ImageIO.write(returnSingleImage, "PNG", baos);
                    baos.flush();
                    resp.body(baos.toByteArray());
                }
                return resp;
            } else {
                JSONObject result = new JSONObject();
                Utils.terribleHackToHaveOrderedJSONObject(result);
                if (!reporting.getExceptions().isEmpty()) {
                    resp.code(400);
                    infos.add("There was a problem completing your request.");
                    reporting.getExceptions().forEach(Exception::printStackTrace);
                }
                if (!infos.isEmpty()) {
                    result.put("info", new JSONArray(infos));
                }
                if (imageLinks.size() == 1 && !useLocalStorage) {
                    reporting.setImageURL(imageLinks.get(0).getValue());
                }
                if (!imageLinks.isEmpty()) {
                    JSONArray images = new JSONArray();
                    for (Entry<Optional<String>, String> pair : imageLinks) {
                        JSONObject image = new JSONObject();
                        Utils.terribleHackToHaveOrderedJSONObject(image);
                        pair.getKey().ifPresent(l -> image.put("label", l));
                        image.put("link", pair.getValue());
                        images.put(image);
                    }
                    result.put("images", images);
                }
                resp.contentType(MediaType.JSON);
                String responseBody = result.toString(2);
                resp.body(responseBody.getBytes());
                reporting.addField(new Field("Response", responseBody, false));
                return resp;
            }
        } finally {
            ServiceFinder.findService(BlueprintBotDiscordService.class).ifPresent(s -> s.getBot().submitReport(reporting));
        }
    });
    System.out.println("Web API Initialized at " + address + ":" + port);
}
Also used : Arrays(java.util.Arrays) Blueprint(com.demod.fbsr.Blueprint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FBSR(com.demod.fbsr.FBSR) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject) ImmutableList(com.google.common.collect.ImmutableList) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) ImageIO(javax.imageio.ImageIO) MediaType(org.rapidoid.http.MediaType) SimpleEntry(java.util.AbstractMap.SimpleEntry) WebUtils(com.demod.fbsr.WebUtils) BufferedImage(java.awt.image.BufferedImage) App(org.rapidoid.setup.App) CommandReporting(com.demod.dcba.CommandReporting) IOException(java.io.IOException) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Config(com.demod.factorio.Config) File(java.io.File) List(java.util.List) Utils(com.demod.factorio.Utils) Entry(java.util.Map.Entry) Optional(java.util.Optional) BlueprintFinder(com.demod.fbsr.BlueprintFinder) BlueprintStringData(com.demod.fbsr.BlueprintStringData) JSONArray(org.json.JSONArray) On(org.rapidoid.setup.On) ArrayList(java.util.ArrayList) BlueprintStringData(com.demod.fbsr.BlueprintStringData) BufferedImage(java.awt.image.BufferedImage) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) SimpleEntry(java.util.AbstractMap.SimpleEntry) Entry(java.util.Map.Entry) Optional(java.util.Optional) Blueprint(com.demod.fbsr.Blueprint) JSONArray(org.json.JSONArray) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Blueprint(com.demod.fbsr.Blueprint) IOException(java.io.IOException) CommandReporting(com.demod.dcba.CommandReporting) JSONObject(org.json.JSONObject) File(java.io.File)

Aggregations

Blueprint (com.demod.fbsr.Blueprint)11 IOException (java.io.IOException)11 CommandReporting (com.demod.dcba.CommandReporting)10 Config (com.demod.factorio.Config)10 Utils (com.demod.factorio.Utils)10 BlueprintFinder (com.demod.fbsr.BlueprintFinder)10 BlueprintStringData (com.demod.fbsr.BlueprintStringData)10 FBSR (com.demod.fbsr.FBSR)10 WebUtils (com.demod.fbsr.WebUtils)10 ImmutableList (com.google.common.collect.ImmutableList)10 BufferedImage (java.awt.image.BufferedImage)10 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 SimpleEntry (java.util.AbstractMap.SimpleEntry)10 ArrayList (java.util.ArrayList)10 Arrays (java.util.Arrays)10 List (java.util.List)10 Entry (java.util.Map.Entry)10 Optional (java.util.Optional)10 AbstractIdleService (com.google.common.util.concurrent.AbstractIdleService)9 URL (java.net.URL)9