use of com.demod.fbsr.BlueprintStringData 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!");
}
}
use of com.demod.fbsr.BlueprintStringData 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;
}
use of com.demod.fbsr.BlueprintStringData 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!");
}
}
use of com.demod.fbsr.BlueprintStringData 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);
}
}
use of com.demod.fbsr.BlueprintStringData 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);
}
Aggregations