summaryrefslogtreecommitdiff
path: root/src/com/encrox/twitchbot/client/PluginHandler.java
blob: 7a759fb41aba93dc5dc928d5581d55d4837e5182 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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<Plugin> plugins = new ArrayList<Plugin>();
	
	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;
				}
			}
		}
	}

}