package com.encrox.twitchbot.client; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; public class PluginHandler implements Runnable { private Client client; private ArrayList plugins = new ArrayList(); public PluginHandler(Client client) { this.client = client; File path = new File("plugins/"); URL[] urls; ClassLoader cl; try { urls = new URL[] { path.toURI().toURL() }; cl = new URLClassLoader(urls); File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { String name = files[i].getName(); plugins.add((Plugin) cl.loadClass(name.substring(0, name.indexOf('.'))).newInstance()); plugins.get(i).load("en-GB"); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } new Thread(this).start(); String answer = null; while(true) { IRCMessage msg = client.getMessage(); if(msg != null) { System.out.println("[" + msg.getUsername() + "][" + msg.getLevel() + "] " + msg.getMessage()); for(int i = 0, size = plugins.size(); i < size; i++) { answer = plugins.get(i).message(msg.getUsername(), msg.getLevel(), msg.getMessage()); if(answer == null) { client.write(Utils.int_to_ba(1)); client.write(new byte[] { (byte)0x00 }); } else { client.write(Utils.int_to_ba(answer.length())); try { client.write(answer.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println("Answer: " + answer); } } } else { return; } } } public void run() { String post; while(true) { for(int i = 0, size = plugins.size(); i < size; i++) { post = plugins.get(i).post(); if(post != null) { client.post(post); post = null; } } } } }