This commit is contained in:
Tyler Murphy 2022-08-26 06:45:57 -04:00
parent 33f0ab31b1
commit 039cb6258f
8 changed files with 156 additions and 163 deletions

View file

@ -13,18 +13,13 @@ import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback;
import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.components.ActionComponent;
import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.LayoutComponent; import net.dv8tion.jda.api.interactions.components.LayoutComponent;
import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.interactions.components.selections.SelectMenu; import net.dv8tion.jda.api.interactions.components.selections.SelectMenu;
import net.dv8tion.jda.api.interactions.components.selections.SelectOption;
import net.dv8tion.jda.api.requests.restaction.WebhookMessageEditAction;
import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction; import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction;
import net.dv8tion.jda.api.utils.FileUpload; import net.dv8tion.jda.api.utils.FileUpload;
import net.tylermurphy.ken.Ken; import net.tylermurphy.ken.Ken;
import net.tylermurphy.ken.command.Register;
import net.tylermurphy.ken.command.Response;
import net.tylermurphy.ken.command.fun.*; import net.tylermurphy.ken.command.fun.*;
import net.tylermurphy.ken.command.main.*; import net.tylermurphy.ken.command.main.*;
import net.tylermurphy.ken.command.music.*; import net.tylermurphy.ken.command.music.*;
@ -134,7 +129,6 @@ public class Responder extends ListenerAdapter {
.setTitle(":x: **Error**") .setTitle(":x: **Error**")
.setDescription(e.getCause() != null ? e.getCause().getMessage() : e.getMessage()); .setDescription(e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
event.replyEmbeds(builder.build()).setEphemeral(true).queue(); event.replyEmbeds(builder.build()).setEphemeral(true).queue();
e.printStackTrace();
} }
} }
@ -234,7 +228,7 @@ public class Responder extends ListenerAdapter {
} }
private void reply(Response response, IReplyCallback event){ private void reply(Response response, IReplyCallback event){
if(response.error()) { if(response.isError()) {
EmbedBuilder builder = Ken.getInstance().getDefaultEmbed() EmbedBuilder builder = Ken.getInstance().getDefaultEmbed()
.setColor(Color.RED) .setColor(Color.RED)
.setDescription(response.getMessage()); .setDescription(response.getMessage());
@ -248,18 +242,18 @@ public class Responder extends ListenerAdapter {
} }
if(response.hasButtons()) message = message.addActionRow(response.getButtons()); if(response.hasButtons()) message = message.addActionRow(response.getButtons());
if(response.hasSelectMenu()) message = message.addActionRow(response.getSelectMenu()); if(response.hasSelectMenu()) message = message.addActionRow(response.getSelectMenu());
if(response.hasFile()) message = message.addFiles(FileUpload.fromData(response.getFile())); if(response.hasFile()) message = message.addFiles(FileUpload.fromData(response.getFile(),response.getFileName()));
message.setEphemeral(response.isHidden()).queue(); message.setEphemeral(response.isHidden()).queue();
} }
} }
private void edit(Response response, InteractionHook hook){ private void edit(Response response, InteractionHook hook){
if(response.error()) { if(response.isError()) {
EmbedBuilder builder = Ken.getInstance().getDefaultEmbed() EmbedBuilder builder = Ken.getInstance().getDefaultEmbed()
.setColor(Color.RED) .setColor(Color.RED)
.setDescription(response.getMessage()); .setDescription(response.getMessage());
hook.sendMessageEmbeds(builder.build()).queue(); hook.sendMessageEmbeds(builder.build()).queue();
} else if(response.remove()) { } else if(response.isDelete()) {
hook.deleteOriginal().queue(); hook.deleteOriginal().queue();
} else { } else {
if(response.hasEmbed()) { if(response.hasEmbed()) {

View file

@ -4,74 +4,88 @@ import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.interactions.components.selections.SelectMenu; import net.dv8tion.jda.api.interactions.components.selections.SelectMenu;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class Response { public class Response {
private final String message; private String message;
private final String type; private String type;
private final MessageEmbed[] embeds;
private final List<Button> buttons; private MessageEmbed[] embeds;
private final SelectMenu.Builder menu;
private final File file; private List<Button> buttons;
private SelectMenu menu;
private byte[] data;
private String fileName;
private boolean hidden = false; private boolean hidden = false;
private Response(String type, String message, File file, MessageEmbed... embed){
this.type = type;
this.message = message;
this.embeds = embed;
this.file = file;
this.buttons = new ArrayList<>();
menu = SelectMenu.create("null");
}
public static Response error(String message){ public static Response error(String message){
return new Response("error", message, null, null); Response response = new Response();
response.type = "error";
response.message = message;
return response;
} }
public static Response success(String message){ public static Response success(String message){
return new Response("success", message, null, null); Response response = new Response();
response.type = "success";
response.message = message;
return response;
} }
public static Response success(String message, File file){ public static Response success(MessageEmbed... embeds){
return new Response("success", message, file, null); Response response = new Response();
response.type = "success";
response.embeds = embeds;
return response;
} }
public static Response success(MessageEmbed... embed){ public static Response delete() {
return new Response("success", "", null, embed); Response response = new Response();
response.type = "delete";
return response;
} }
public static Response delete() { return new Response("delete", "", null, null); }
public Response addPrimaryButton(String callback, String id, String label){ public Response addPrimaryButton(String callback, String id, String label){
if(buttons == null) buttons = new ArrayList<>();
buttons.add(Button.primary(callback + "_" + id ,label)); buttons.add(Button.primary(callback + "_" + id ,label));
return this; return this;
} }
public Response addSecondaryButton(String callback, String id, String label){ public Response addSecondaryButton(String callback, String id, String label){
if(buttons == null) buttons = new ArrayList<>();
buttons.add(Button.secondary(callback + "_" + id ,label)); buttons.add(Button.secondary(callback + "_" + id ,label));
return this; return this;
} }
public Response addSuccessButton(String callback, String id, String label){ public Response addSuccessButton(String callback, String id, String label){
if(buttons == null) buttons = new ArrayList<>();
buttons.add(Button.success(callback + "_" + id ,label)); buttons.add(Button.success(callback + "_" + id ,label));
return this; return this;
} }
public Response addDangerButton(String callback, String id, String label){ public Response addDangerButton(String callback, String id, String label){
if(buttons == null) buttons = new ArrayList<>();
buttons.add(Button.danger(callback + "_" + id ,label)); buttons.add(Button.danger(callback + "_" + id ,label));
return this; return this;
} }
public Response addSelectMenu(String callback, String id, List<String> options){ public Response addSelectMenu(String callback, String id, List<String> options){
menu.setId(callback + "_" + id); SelectMenu.Builder builder = SelectMenu.create(callback + "_" + id);
for(int i=0; i<options.size(); i = i + 2) { for(int i=0; i<options.size(); i = i + 2) {
menu.addOption(options.get(i), options.get(i+1)); builder.addOption(options.get(i), options.get(i+1));
} }
menu = builder.build();
return this;
}
public Response setFile(byte[] data, String name){
this.data = data;
this.fileName = name;
return this; return this;
} }
@ -80,21 +94,21 @@ public class Response {
return this; return this;
} }
public boolean error(){ public boolean isError(){
return type.equals("error"); return type.equals("error");
} }
public boolean remove() { return type.equals("delete"); } public boolean isDelete() { return type.equals("delete"); }
public boolean isHidden() { return hidden; }
public boolean hasEmbed() { return embeds != null; } public boolean hasEmbed() { return embeds != null; }
public boolean hasFile() { return file != null; } public boolean hasFile() { return data != null; }
public boolean hasButtons() { return !buttons.isEmpty(); } public boolean hasButtons() { return buttons != null; }
public boolean hasSelectMenu() { return !menu.getId().equals("null"); } public boolean hasSelectMenu() { return menu != null; }
public boolean isHidden() { return hidden; }
public Button[] getButtons() { public Button[] getButtons() {
Button[] arr = new Button[buttons.size()]; Button[] arr = new Button[buttons.size()];
@ -103,11 +117,15 @@ public class Response {
} }
public SelectMenu getSelectMenu(){ public SelectMenu getSelectMenu(){
return menu.build(); return menu;
} }
public File getFile(){ public byte[] getFile(){
return file; return data;
}
public String getFileName(){
return fileName;
} }
public String getMessage(){ public String getMessage(){

View file

@ -16,8 +16,8 @@ public class Eject {
@Option(name="member", description="Server member to eject", type=OptionType.USER, required=true) @Option(name="member", description="Server member to eject", type=OptionType.USER, required=true)
public Response execute(Member sender, List<Object> args){ public Response execute(Member sender, List<Object> args){
Member ejected = (Member) args.get(0); Member ejected = (Member) args.get(0);
File file = GifFactory.generateEjectGif(ejected.getUser()); byte[] data = GifFactory.generateEjectGif(ejected.getUser());
return Response.success(ejected.getNickname() +" was ejected by "+sender.getNickname(), file); return Response.success(ejected.getEffectiveName() +" was ejected by "+sender.getEffectiveName()).setFile(data, "eject.gif");
} }
} }

View file

@ -11,17 +11,15 @@ import net.tylermurphy.ken.command.Response;
public class Help { public class Help {
private final int PAGES = 5;
@Command(name="help", description="Gets information about all the commands in the plugin") @Command(name="help", description="Gets information about all the commands in the plugin")
public Response execute(Member sender){ public Response execute(Member sender){
return Response.success(getPage(sender, 1)).addSecondaryButton("help", "previous", "Previous").addSecondaryButton("help", "next", "Next"); return Response.success(pageEmbeds[0].setFooter("Page "+1+"/"+pageEmbeds.length).build()).addSecondaryButton("help", "previous", "Previous").addSecondaryButton("help", "next", "Next").addDangerButton("exit","exit","Exit");
} }
@ButtonCallback(name="help") @ButtonCallback(name="help")
public Response onButton(String id, Message message, Member sender){ public Response onButton(String id, Message message, Member sender){
int page; int page;
int pages = PAGES; int pages = pageEmbeds.length;
if (message != null && message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) { if (message != null && message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) {
page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5)); page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
} else { } else {
@ -31,28 +29,26 @@ public class Help {
page = page - 1 < 1 ? pages : page - 1; page = page - 1 < 1 ? pages : page - 1;
else else
page = page + 1 > pages ? 1 : page + 1; page = page + 1 > pages ? 1 : page + 1;
return Response.success(getPage(sender, page)); return Response.success(pageEmbeds[page-1].setFooter("Page "+page+"/"+pageEmbeds.length).build());
} }
private MessageEmbed getPage(Member sender, int page) {
String name = Ken.getInstance().getConfig().getString("botName"); String name = Ken.getInstance().getConfig().getString("botName");
String supportServer = Ken.getInstance().getConfig().getString("supportServer"); String supportServer = Ken.getInstance().getConfig().getString("supportServer");
EmbedBuilder[] embeds = new EmbedBuilder[]{ EmbedBuilder[] pageEmbeds = new EmbedBuilder[]{
Ken.getInstance().getDefaultEmbed() Ken.getInstance().getDefaultEmbed()
.setAuthor(name + " Command List", sender.getUser().getAvatarUrl()) .setAuthor("Command List")
.appendDescription( .appendDescription(
"These are all the commands that are included with "+name+"\n" + "These are all the commands that are included with "+name+"\n" +
"Read below to see what each command does, and what parameters the\n" + "Read below to see what each command does, and what parameters the\n" +
"command requires. Any questions? Join our [discord support server](https://discord.gg/"+supportServer+")" "command requires. Any questions? Join our [discord support server](https://discord.gg/"+supportServer+")"
).setFooter("Page "+page+"/"+PAGES), ),
Ken.getInstance().getDefaultEmbed() Ken.getInstance().getDefaultEmbed()
.setAuthor(name + " Command List", sender.getUser().getAvatarUrl()) .setAuthor("Command List")
.setTitle(":pen_ballpoint: **Main Commands**") .setTitle(":pen_ballpoint: **Main Commands**")
.appendDescription("**/help** Gives a list of commands\n") .appendDescription("**/help** Gives a list of commands\n")
.appendDescription("**/purge <amount>** Purges an amount of messages from a channel\n") .appendDescription("**/purge <amount>** Purges an amount of messages from a channel\n"),
.setFooter("Page "+page+"/"+PAGES),
Ken.getInstance().getDefaultEmbed() Ken.getInstance().getDefaultEmbed()
.setAuthor(name + " Command List", sender.getUser().getAvatarUrl()) .setAuthor("Command List")
.setTitle(":musical_note: **Music Commands**") .setTitle(":musical_note: **Music Commands**")
.appendDescription("**/play <query>** Plays a song in a voice channel\n") .appendDescription("**/play <query>** Plays a song in a voice channel\n")
.appendDescription("**/join** Make the bot join your audio channel\n") .appendDescription("**/join** Make the bot join your audio channel\n")
@ -66,19 +62,25 @@ public class Help {
.appendDescription("**/loopqueue** Loop the current song queue\n") .appendDescription("**/loopqueue** Loop the current song queue\n")
.appendDescription("**/remove <index>** Remove a song from the queue\n") .appendDescription("**/remove <index>** Remove a song from the queue\n")
.appendDescription("**/nowplaying** See what track is currently playing\n") .appendDescription("**/nowplaying** See what track is currently playing\n")
.appendDescription("**/queue** View the current song queue\n") .appendDescription("**/queue** View the current song queue\n"),
.setFooter("Page "+page+"/"+PAGES),
Ken.getInstance().getDefaultEmbed() Ken.getInstance().getDefaultEmbed()
.setAuthor(name + " Command List", sender.getUser().getAvatarUrl()) .setAuthor("Command List")
.setTitle(":game_die: **Game Commands**") .setTitle(":game_die: **Game Commands**")
.appendDescription("**/d6** Roll a d6 die\n") .appendDescription("**/d6** Roll a d6 die\n")
.appendDescription("**/d8** Roll a d8 die\n") .appendDescription("**/d8** Roll a d8 die\n")
.appendDescription("**/d12** Roll a d12 die\n") .appendDescription("**/d12** Roll a d12 die\n")
.appendDescription("**/d20** Roll a d20 die\n") .appendDescription("**/d20** Roll a d20 die\n")
.appendDescription("**/dice <sides>** Roll a dice with set sides\n") .appendDescription("**/dice <sides>** Roll a dice with set sides\n"),
.setFooter("Page "+page+"/"+PAGES),
Ken.getInstance().getDefaultEmbed() Ken.getInstance().getDefaultEmbed()
.setAuthor(name + " Command List", sender.getUser().getAvatarUrl()) .setAuthor("Command List")
.setTitle(":man_detective: **Self Roles**")
.appendDescription("**/addrolespage <title> <description>** Add a page to the /roles command\n")
.appendDescription("**/deleterolespage <page>** Remove a page from the /roles command\n")
.appendDescription("**/addrole <role> <page>** Add a role to the /roles command\n")
.appendDescription("**/deleterole <role> <page>** Remove a role from the /roles command\n")
.appendDescription("**/roles** Add self roles to yourself\n"),
Ken.getInstance().getDefaultEmbed()
.setAuthor("Command List")
.setTitle(":underage: **NSFW Commands**") .setTitle(":underage: **NSFW Commands**")
.appendDescription("**/hentai <query>** Retrieves a random hentai image\n") .appendDescription("**/hentai <query>** Retrieves a random hentai image\n")
.appendDescription("**/rule34 <query> <page>** Searches on rule34\n") .appendDescription("**/rule34 <query> <page>** Searches on rule34\n")
@ -87,10 +89,7 @@ public class Help {
.appendDescription("**/konachan <query> <page>** Searches on konachan\n") .appendDescription("**/konachan <query> <page>** Searches on konachan\n")
.appendDescription("**/yandere <query> <page>** Searches on yande.re\n") .appendDescription("**/yandere <query> <page>** Searches on yande.re\n")
.appendDescription("**/e621 <query> <page>** Searches on e621\n") .appendDescription("**/e621 <query> <page>** Searches on e621\n")
.appendDescription("**/nhentai <query>** Searches on nhentai\n") .appendDescription("**/nhentai <query>** Searches on nhentai\n"),
.setFooter("Page "+page+"/"+PAGES)
}; };
return embeds[page-1].build();
}
} }

View file

@ -2,7 +2,6 @@ package net.tylermurphy.ken.command.main;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.interactions.components.selections.SelectMenu;
import net.tylermurphy.ken.Ken; import net.tylermurphy.ken.Ken;
import net.tylermurphy.ken.command.Response; import net.tylermurphy.ken.command.Response;
import net.tylermurphy.ken.command.annotation.ButtonCallback; import net.tylermurphy.ken.command.annotation.ButtonCallback;
@ -23,13 +22,18 @@ public class Roles {
return Response.error("Self roles are currently not setup in this server"); return Response.error("Self roles are currently not setup in this server");
} }
int pages = Ken.getInstance().getDatabase().getSelfRoleData().getPages(guild.getIdLong()); int pages = Ken.getInstance().getDatabase().getSelfRoleData().getPages(guild.getIdLong());
return Response.success(getEmbed(data, 1, pages)).addSecondaryButton("roles", "previous", "Previous").addSecondaryButton("roles", "next", "Next").addDangerButton("roles","exit","Exit").addSelectMenu("roles","select",getRoles(data)); return Response.success(getEmbed(data, 1, pages)).addSecondaryButton("roles", "previous", "Previous").addSecondaryButton("roles", "next", "Next").addDangerButton("exit","exit","Exit").addSelectMenu("roles","select",getRoles(data));
}
@ButtonCallback(name="exit")
public Response onExit(Message message){
return Response.delete();
} }
@ButtonCallback(name="roles") @ButtonCallback(name="roles")
public Response onButton(Guild guild, String id, Message message){ public Response onButton(Guild guild, String id, Message message){
int page; int page;
if(message == null || id.equals("exit")) return Response.delete(); if(message == null) return Response.delete();
if (message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) { if (message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) {
page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5)); page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
} else { } else {
@ -44,7 +48,7 @@ public class Roles {
if(data==null){ if(data==null){
return Response.error("Self roles are currently not setup in this server"); return Response.error("Self roles are currently not setup in this server");
} }
return Response.success(getEmbed(data, page, pages)).addSecondaryButton("roles", "previous", "Previous").addSecondaryButton("roles", "next", "Next").addDangerButton("roles","exit","Exit").addSelectMenu("roles","select",getRoles(data)); return Response.success(getEmbed(data, page, pages)).addSecondaryButton("roles", "previous", "Previous").addSecondaryButton("roles", "next", "Next").addDangerButton("exit","exit","Exit").addSelectMenu("roles","select",getRoles(data));
} }
@SelectMenuCallback(name="roles") @SelectMenuCallback(name="roles")

View file

@ -25,7 +25,7 @@ public class Queue {
GuildMusicManager musicManager = playerManager.getGuildMusicManager(guild); GuildMusicManager musicManager = playerManager.getGuildMusicManager(guild);
MessageEmbed queue = getQueuePage(musicManager, 1); MessageEmbed queue = getQueuePage(musicManager, 1);
if(queue == null){ if(queue == null){
return Response.success("Queue is empty"); return Response.error("Queue is empty");
} }
return Response.success(queue).addSecondaryButton("queue", "previous", "Previous").addSecondaryButton("queue", "next", "Next"); return Response.success(queue).addSecondaryButton("queue", "previous", "Previous").addSecondaryButton("queue", "next", "Next");
} }
@ -34,23 +34,23 @@ public class Queue {
public Response onButton(String id, Message message, Guild guild){ public Response onButton(String id, Message message, Guild guild){
PlayerManager playerManager = Ken.getInstance().getPlayerManager(); PlayerManager playerManager = Ken.getInstance().getPlayerManager();
GuildMusicManager musicManager = playerManager.getGuildMusicManager(guild); GuildMusicManager musicManager = playerManager.getGuildMusicManager(guild);
int page, pages; BlockingQueue<AudioTrack> queue = musicManager.scheduler.getQueue();
int page;
int pages = (queue.size()-1)/10+1;
if (message != null && message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) { if (message != null && message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) {
page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5)); page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
pages = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[1]);
} else { } else {
page = 0; page = 0;
pages = (musicManager.scheduler.getQueue().size()-1)/10+1;
} }
if(id.equals("previous")) if(id.equals("previous"))
page = page - 1 < 1 ? pages : page - 1; page = page - 1 < 1 ? pages : page - 1;
else else
page = page + 1 > pages ? 1 : page + 1; page = page + 1 > pages ? 1 : page + 1;
MessageEmbed queue = getQueuePage(musicManager, page); MessageEmbed embed = getQueuePage(musicManager, page);
if(queue == null){ if(embed == null){
return Response.success("Queue is empty"); return Response.success("Queue is empty");
} }
return Response.success(queue); return Response.success(embed);
} }
private MessageEmbed getQueuePage(GuildMusicManager musicManager, int page){ private MessageEmbed getQueuePage(GuildMusicManager musicManager, int page){

View file

@ -1,7 +1,7 @@
package net.tylermurphy.ken.image; package net.tylermurphy.ken.image;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
@ -19,7 +19,7 @@ import net.dv8tion.jda.api.entities.User;
public class GifFactory { public class GifFactory {
public static File generateEjectGif(User u) { public static byte[] generateEjectGif(User u) {
String message; String message;
if(Math.random() > .5) if(Math.random() > .5)
message = u.getName() + " was An Impostor"; message = u.getName() + " was An Impostor";
@ -34,9 +34,8 @@ public class GifFactory {
frames[i] = ImageFactory.GenerateEjectFrame(message, Math.min(i, 23), 24, space1, avatar); frames[i] = ImageFactory.GenerateEjectFrame(message, Math.min(i, 23), 24, space1, avatar);
} }
int rand = (int)(Math.random()*1000000000);
try { try {
return generateFromBI(frames, rand+".gif", 100/12, true); return generateFromBI(frames);
} catch(Exception e) { } catch(Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
@ -44,13 +43,14 @@ public class GifFactory {
} }
private static File generateFromBI(BufferedImage[] images, String output, int delay, boolean loop) private static byte[] generateFromBI(BufferedImage[] images)
throws IIOException, IOException throws IIOException, IOException
{ {
System.out.println('e');
ImageWriter gifWriter = getWriter(); ImageWriter gifWriter = getWriter();
File outfile = new File(output); ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(outfile); ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
IIOMetadata metadata = getMetadata(gifWriter, delay, loop); IIOMetadata metadata = getMetadata(gifWriter);
gifWriter.setOutput(ios); gifWriter.setOutput(ios);
gifWriter.prepareWriteSequence(null); gifWriter.prepareWriteSequence(null);
@ -62,8 +62,8 @@ public class GifFactory {
gifWriter.endWriteSequence(); gifWriter.endWriteSequence();
ios.close(); ios.close();
System.out.println('e');
return outfile; return baos.toByteArray();
} }
@ -76,7 +76,7 @@ public class GifFactory {
throw new IIOException("GIF writer doesn't exist on this JVM!"); throw new IIOException("GIF writer doesn't exist on this JVM!");
} }
private static IIOMetadata getMetadata(ImageWriter writer, int delay, boolean loop) private static IIOMetadata getMetadata(ImageWriter writer)
throws IIOInvalidTreeException throws IIOInvalidTreeException
{ {
ImageTypeSpecifier img_type = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB); ImageTypeSpecifier img_type = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
@ -85,11 +85,10 @@ public class GifFactory {
IIOMetadataNode node_tree = (IIOMetadataNode)metadata.getAsTree(native_format); IIOMetadataNode node_tree = (IIOMetadataNode)metadata.getAsTree(native_format);
IIOMetadataNode graphics_node = getNode("GraphicControlExtension", node_tree); IIOMetadataNode graphics_node = getNode("GraphicControlExtension", node_tree);
graphics_node.setAttribute("delayTime", String.valueOf(delay)); graphics_node.setAttribute("delayTime", String.valueOf(8));
graphics_node.setAttribute("disposalMethod", "none"); graphics_node.setAttribute("disposalMethod", "none");
graphics_node.setAttribute("userInputFlag", "FALSE"); graphics_node.setAttribute("userInputFlag", "FALSE");
if(loop)
makeLoopy(node_tree); makeLoopy(node_tree);
metadata.setFromTree(native_format, node_tree); metadata.setFromTree(native_format, node_tree);
@ -104,7 +103,7 @@ public class GifFactory {
app_node.setAttribute("applicationID", "NETSCAPE"); app_node.setAttribute("applicationID", "NETSCAPE");
app_node.setAttribute("authenticationCode", "2.0"); app_node.setAttribute("authenticationCode", "2.0");
app_node.setUserObject(new byte[]{ 0x1, (byte) (0 & 0xFF), (byte) ((0 >> 8) & 0xFF)}); app_node.setUserObject(new byte[]{ 0x1, (byte) (0), (byte) ((0) & 0xFF)});
app_extensions.appendChild(app_node); app_extensions.appendChild(app_node);
root.appendChild(app_extensions); root.appendChild(app_extensions);
@ -112,7 +111,7 @@ public class GifFactory {
private static IIOMetadataNode getNode(String node_name, IIOMetadataNode root) private static IIOMetadataNode getNode(String node_name, IIOMetadataNode root)
{ {
IIOMetadataNode node = null; IIOMetadataNode node;
for (int i = 0; i < root.getLength(); i++) for (int i = 0; i < root.getLength(); i++)
{ {

View file

@ -60,33 +60,12 @@ public class ImageFactory {
return rotated; return rotated;
} }
private static BufferedImage makeRoundedCorner(BufferedImage image, int cornerRadius) { public static BufferedImage getImageFromURL(String link) {
int w = image.getWidth();
int h = image.getHeight();
BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = output.createGraphics();
g2.setComposite(AlphaComposite.Src);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius));
g2.setComposite(AlphaComposite.SrcAtop);
g2.drawImage(image, 0, 0, null);
g2.dispose();
return output;
}
public static BufferedImage getImageFromURL(String surl) {
try { try {
final URL url = new URL(surl); final URL url = new URL(link);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0");
final BufferedImage image = ImageIO.read(connection.getInputStream()); return ImageIO.read(connection.getInputStream());
return image;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;