From b67904700682f6c5d5d8d77e75b3268c55968c47 Mon Sep 17 00:00:00 2001 From: ShivamMistry Date: Sat, 17 May 2014 20:24:56 +0100 Subject: [PATCH 1/4] remove deprecated's commits --- pom.xml | 5 -- .../org/freecode/irc/votebot/FreeVoteBot.java | 6 +-- .../irc/votebot/PollExpiryAnnouncer.java | 36 ++++++++----- .../freecode/irc/votebot/api/AdminModule.java | 10 ++-- .../freecode/irc/votebot/api/FVBModule.java | 7 +-- .../org/freecode/irc/votebot/dao/PollDAO.java | 2 + .../org/freecode/irc/votebot/dao/VoteDAO.java | 8 +-- .../org/freecode/irc/votebot/entity/Vote.java | 13 +---- .../modules/admin/CreatePollModule.java | 13 +++-- .../votebot/modules/admin/LoadModules.java | 6 +-- .../modules/admin/OpenClosePollModule.java | 52 ++++++++----------- .../votebot/modules/admin/RebuildModule.java | 17 +++--- .../modules/admin/SendMessageModule.java | 18 ++----- .../modules/admin/WorkingDirectoryModule.java | 6 +-- .../votebot/modules/common/PollsModule.java | 37 +++++++------ .../modules/common/StoreTestModule.java | 8 +-- .../votebot/modules/common/VoteModule.java | 32 ++++++++---- src/main/resources/spring/modules.xml | 43 ++++++++++----- 18 files changed, 159 insertions(+), 160 deletions(-) diff --git a/pom.xml b/pom.xml index a99f2d9..c262fc1 100644 --- a/pom.xml +++ b/pom.xml @@ -69,11 +69,6 @@ org.eclipse.jgit 3.1.0.201310021548-r - - ch.qos.logback - logback-classic - 1.1.2 - diff --git a/src/main/java/org/freecode/irc/votebot/FreeVoteBot.java b/src/main/java/org/freecode/irc/votebot/FreeVoteBot.java index 7933b9f..f8bccab 100644 --- a/src/main/java/org/freecode/irc/votebot/FreeVoteBot.java +++ b/src/main/java/org/freecode/irc/votebot/FreeVoteBot.java @@ -305,9 +305,9 @@ public void onJoin(String channel, String nick, String mask) { int id = poll.getId(); long expiry = poll.getExpiry(); Date date = new Date(expiry); - List votes = voteDAO.getVotesOnPoll(id); - String msg = String.format("Open poll #%d: \"%s\", ends: %s, votes: %d", id, question, getDateFormatter().format(date), votes.size()); - pollVotes[i] = new PollVotes(votes.size(), msg); + Vote[] votes = voteDAO.getVotesOnPoll(id); + String msg = String.format("Open poll #%d: \"%s\", ends: %s, votes: %d", id, question, getDateFormatter().format(date), votes.length); + pollVotes[i] = new PollVotes(votes.length, msg); } if (pollVotes.length == 0) { connection.sendNotice(nick, "No new polls to vote in!"); diff --git a/src/main/java/org/freecode/irc/votebot/PollExpiryAnnouncer.java b/src/main/java/org/freecode/irc/votebot/PollExpiryAnnouncer.java index 57c8906..79be48b 100644 --- a/src/main/java/org/freecode/irc/votebot/PollExpiryAnnouncer.java +++ b/src/main/java/org/freecode/irc/votebot/PollExpiryAnnouncer.java @@ -4,8 +4,6 @@ import org.freecode.irc.votebot.entity.Vote; import java.sql.SQLException; -import java.util.Collections; -import java.util.List; import java.util.concurrent.ScheduledFuture; /** @@ -34,30 +32,42 @@ public void run() { try { Poll poll = fvb.getPollDAO().getPoll(id); String question = poll.getQuestion(); - - List votes = fvb.getVoteDAO().getVotesOnPoll(poll.getId()); - int total = votes.size(); - int yesCount = Collections.frequency(votes, Vote.YES); - int noCount = Collections.frequency(votes, Vote.NO); - int abstainCount = Collections.frequency(votes, Vote.ABSTAIN); + Vote[] votes = fvb.getVoteDAO().getVotesOnPoll(id); + int total = votes.length; + int yes = 0, no = 0, abstain = 0; + for (Vote v : votes) { + switch (v.getAnswerIndex()) { + case Vote.YES: + yes++; + break; + case Vote.NO: + no++; + break; + case Vote.ABSTAIN: + abstain++; + break; + default: + break; + } + } if ((hasAnnounced & 1) == 0 && ttl <= 2 * 300000 && ttl >= 0) { hasAnnounced |= 1; fvb.sendMsg(String.format(time_announcement, id, "10 minutes")); - fvb.sendMsg(String.format(poll_information, question, yesCount, noCount, abstainCount)); + fvb.sendMsg(String.format(poll_information, question, yes, no, abstain)); } else if ((hasAnnounced & 3) == 0 && ttl <= MILLIS_IN_AN_HOUR * 2 && ttl >= 0) { hasAnnounced |= 2; fvb.sendMsg(String.format(time_announcement, id, "two hours")); - fvb.sendMsg(String.format(poll_information, question, yesCount, noCount, abstainCount)); + fvb.sendMsg(String.format(poll_information, question, yes, no, abstain)); } else if ((hasAnnounced & 7) == 0 && ttl <= 12 * MILLIS_IN_AN_HOUR && ttl >= 0) { hasAnnounced |= 4; fvb.sendMsg(String.format(time_announcement, id, "twelve hours")); - fvb.sendMsg(String.format(poll_information, question, yesCount, noCount, abstainCount)); + fvb.sendMsg(String.format(poll_information, question, yes, no, abstain)); } else if (ttl <= 0 && ((hasAnnounced & Integer.MAX_VALUE) != Integer.MAX_VALUE)) { hasAnnounced = Integer.MAX_VALUE; - String result = (total >= 5 && yesCount > noCount && yesCount > abstainCount) ? "passed" : "did not pass"; + String result = (total >= 5 && yes > no && yes > abstain) ? "passed" : "did not pass"; fvb.sendMsg(String.format("Poll #%d %s!", id, result)); - fvb.sendMsg(String.format(poll_information, question, yesCount, noCount, abstainCount)); + fvb.sendMsg(String.format(poll_information, question, yes, no, abstain)); getFuture().cancel(true); } } catch (SQLException e) { diff --git a/src/main/java/org/freecode/irc/votebot/api/AdminModule.java b/src/main/java/org/freecode/irc/votebot/api/AdminModule.java index bc90e4d..5d53ecb 100644 --- a/src/main/java/org/freecode/irc/votebot/api/AdminModule.java +++ b/src/main/java/org/freecode/irc/votebot/api/AdminModule.java @@ -5,14 +5,13 @@ import org.freecode.irc.Transmittable; import org.freecode.irc.votebot.FreeVoteBot; import org.freecode.irc.votebot.NoticeFilter; -import org.springframework.beans.factory.annotation.Autowired; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class AdminModule extends CommandModule { - @Autowired + private FreeVoteBot fvb; protected enum Right { @@ -59,11 +58,12 @@ public void run(Notice notice) { askChanServForUserCreds(privmsg); } - protected final FreeVoteBot getFvb() { - return fvb; - } public final void setFvb(FreeVoteBot fvb) { this.fvb = fvb; } + + protected final FreeVoteBot getFvb() { + return fvb; + } } diff --git a/src/main/java/org/freecode/irc/votebot/api/FVBModule.java b/src/main/java/org/freecode/irc/votebot/api/FVBModule.java index a949952..79953ed 100644 --- a/src/main/java/org/freecode/irc/votebot/api/FVBModule.java +++ b/src/main/java/org/freecode/irc/votebot/api/FVBModule.java @@ -2,7 +2,6 @@ import org.freecode.irc.Transmittable; import org.freecode.irc.votebot.KVStore; -import org.springframework.beans.factory.annotation.Autowired; public abstract class FVBModule implements Runnable { private volatile boolean enabled = true; @@ -29,15 +28,17 @@ public void run() { } - @Autowired private KVStore kvStore; - private boolean kvLocal = false; public void setKvLocal(boolean kvLocal) { this.kvLocal = kvLocal; } + public void setKvStore(KVStore kvStore) { + this.kvStore = kvStore; + } + public void store(String key, Object value) { kvStore.store(toKeypath(key), value); } diff --git a/src/main/java/org/freecode/irc/votebot/dao/PollDAO.java b/src/main/java/org/freecode/irc/votebot/dao/PollDAO.java index fe21b89..d7a55b1 100644 --- a/src/main/java/org/freecode/irc/votebot/dao/PollDAO.java +++ b/src/main/java/org/freecode/irc/votebot/dao/PollDAO.java @@ -13,7 +13,9 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.List; +import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; /** * Created with IntelliJ IDEA. diff --git a/src/main/java/org/freecode/irc/votebot/dao/VoteDAO.java b/src/main/java/org/freecode/irc/votebot/dao/VoteDAO.java index ab9de07..9557087 100644 --- a/src/main/java/org/freecode/irc/votebot/dao/VoteDAO.java +++ b/src/main/java/org/freecode/irc/votebot/dao/VoteDAO.java @@ -8,7 +8,6 @@ import java.sql.SQLException; import java.util.ArrayList; -import java.util.Collections; import java.util.List; /** @@ -46,13 +45,14 @@ public void addUsersVote(final String voter, final int pollId, final int answerI getJdbcTemplate().update(ADD_NEW_VOTE, pollId, voter, answerIndex); } - public List getVotesOnPoll(final int pollId) throws SQLException { + public Vote[] getVotesOnPoll(final int pollId) throws SQLException { try { - return getJdbcTemplate().query(GET_VOTES_ON_POLL, + List votes = getJdbcTemplate().query(GET_VOTES_ON_POLL, new Object[]{pollId}, new BeanPropertyRowMapper<>(Vote.class)); + return votes.toArray(new Vote[votes.size()]); } catch (EmptyResultDataAccessException empty) { - return Collections.emptyList(); + return new Vote[]{}; } } diff --git a/src/main/java/org/freecode/irc/votebot/entity/Vote.java b/src/main/java/org/freecode/irc/votebot/entity/Vote.java index 9fbbea7..9c6eec4 100644 --- a/src/main/java/org/freecode/irc/votebot/entity/Vote.java +++ b/src/main/java/org/freecode/irc/votebot/entity/Vote.java @@ -7,11 +7,10 @@ * Time: 7:29 PM */ public class Vote { + private int pollId, answerIndex; public static final int YES = 0; public static final int NO = 1; public static final int ABSTAIN = 2; - - private int pollId, answerIndex; private String voter; public int getPollId() { @@ -37,14 +36,4 @@ public void setPollId(int pollId) { public void setVoter(String voter) { this.voter = voter; } - - @Override - public boolean equals(Object o) { - return (o instanceof Number) && (((Integer) o) == answerIndex); - } - - @Override - public int hashCode() { - return answerIndex; - } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/CreatePollModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/CreatePollModule.java index b61b6c7..c65278d 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/CreatePollModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/CreatePollModule.java @@ -4,20 +4,15 @@ import org.freecode.irc.votebot.PollExpiryAnnouncer; import org.freecode.irc.votebot.api.AdminModule; import org.freecode.irc.votebot.dao.PollDAO; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; +import java.sql.SQLException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class CreatePollModule extends AdminModule { - private static final Logger LOGGER = LoggerFactory.getLogger(CreatePollModule.class); private static final long DEFAULT_LIFE_SPAN = 604800000L; public static final String LIFESPAN_PATTERN = "\\d{1,6}[whsdmWHSDM]?"; public static final String CREATE_POLL_WITH_LIFESPAN_PATTERN = "!createpoll " + LIFESPAN_PATTERN + " .+"; - - @Autowired private PollDAO pollDAO; @Override @@ -56,7 +51,7 @@ public void processMessage(final Privmsg privmsg) { exp.setFuture(future); getFvb().pollFutures.put(id, future); } catch (Exception e) { - LOGGER.error("Failed to create poll" , e); + e.printStackTrace(); } } @@ -98,6 +93,10 @@ public String getParameterRegex() { return ".+"; } + public void setPollDAO(PollDAO pollDAO) { + this.pollDAO = pollDAO; + } + protected Right[] getRights() { return new Right[]{Right.AOP, Right.SOP, Right.FOUNDER, Right.HOP}; } diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/LoadModules.java b/src/main/java/org/freecode/irc/votebot/modules/admin/LoadModules.java index 0dacea9..4f82552 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/LoadModules.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/LoadModules.java @@ -10,8 +10,6 @@ import org.freecode.irc.votebot.ScriptModuleLoader; import org.freecode.irc.votebot.api.AdminModule; import org.freecode.irc.votebot.api.ExternalModule; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import javax.script.ScriptException; import java.io.*; @@ -25,7 +23,7 @@ * Created by shivam on 12/8/13. */ public class LoadModules extends AdminModule { - private static final Logger LOGGER = LoggerFactory.getLogger(LoadModules.class); + private Repository repository; private Git git; private static final String GIT_MODULES_URL = "https://github.com/freecode/FVB-Modules.git"; @@ -50,7 +48,7 @@ public LoadModules() { /*loadedModules.addAll(Arrays.asList(loadModules())); getFvb().addModules(loadedModules);*/ } catch (IOException | URISyntaxException | GitAPIException e) { - LOGGER.error("Failed to load from Modules directory." , e); + e.printStackTrace(); } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/OpenClosePollModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/OpenClosePollModule.java index d0d56a8..b7df115 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/OpenClosePollModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/OpenClosePollModule.java @@ -5,9 +5,6 @@ import org.freecode.irc.votebot.api.AdminModule; import org.freecode.irc.votebot.dao.PollDAO; import org.freecode.irc.votebot.entity.Poll; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import java.sql.SQLException; import java.util.concurrent.Future; @@ -15,9 +12,6 @@ import java.util.concurrent.TimeUnit; public class OpenClosePollModule extends AdminModule { - private static final Logger LOGGER = LoggerFactory.getLogger(OpenClosePollModule.class); - - @Autowired private PollDAO pollDAO; @Override @@ -31,40 +25,34 @@ public void processMessage(Privmsg privmsg) { int id = Integer.parseInt(parts[1]); boolean state = false; String action = "opened"; - if (parts[0].charAt(1) == 'c') { state = true; action = "closed"; } - try { if (pollDAO.setStatusOfPoll(id, state) > 0) { privmsg.send("Poll #" + id + " " + action + "."); - cancelFuture(id); - - if (action.equalsIgnoreCase("opened")) { - submitExpiryAnnouncement(id); + if (action.equalsIgnoreCase("closed")) { + Future future = getFvb().pollFutures.get(id); + if (future != null) { + future.cancel(true); + } + } else if (action.equalsIgnoreCase("opened")) { + Future future = getFvb().pollFutures.get(id); + if (future != null) { + future.cancel(true); + } + Poll poll = pollDAO.getPoll(id); + if (poll.getExpiry() > System.currentTimeMillis()) { + PollExpiryAnnouncer announcer = new PollExpiryAnnouncer(poll.getExpiry(), poll.getId(), getFvb()); + ScheduledFuture f = getFvb().pollExecutor.scheduleAtFixedRate(announcer, 5000L, 500L, TimeUnit.MILLISECONDS); + getFvb().pollFutures.put(id, f); + announcer.setFuture(f); + } } } } catch (SQLException e) { - LOGGER.error("Failed to set status of poll.", e); - } - } - - private void submitExpiryAnnouncement(int id) throws SQLException { - Poll poll = pollDAO.getPoll(id); - if (poll.getExpiry() > System.currentTimeMillis()) { - PollExpiryAnnouncer announcer = new PollExpiryAnnouncer(poll.getExpiry(), poll.getId(), getFvb()); - ScheduledFuture f = getFvb().pollExecutor.scheduleAtFixedRate(announcer, 5000L, 500L, TimeUnit.MILLISECONDS); - getFvb().pollFutures.put(id, f); - announcer.setFuture(f); - } - } - - private void cancelFuture(int id) { - Future future = getFvb().pollFutures.get(id); - if (future != null) { - future.cancel(true); + e.printStackTrace(); } } @@ -77,4 +65,8 @@ public String getName() { protected String getParameterRegex() { return "\\d+"; } + + public void setPollDAO(PollDAO pollDAO) { + this.pollDAO = pollDAO; + } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/RebuildModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/RebuildModule.java index a4e03aa..85003db 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/RebuildModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/RebuildModule.java @@ -2,8 +2,6 @@ import org.freecode.irc.Privmsg; import org.freecode.irc.votebot.api.AdminModule; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -16,9 +14,8 @@ * Date: 11/22/13 * Time: 10:52 PM */ - public class RebuildModule extends AdminModule { - private static final Logger LOGGER = LoggerFactory.getLogger(RebuildModule.class); + private String idAbbrev; private String idDescribe; @@ -26,9 +23,7 @@ public class RebuildModule extends AdminModule { public void init() { String last = readString(LAST_ID); - if (idAbbrev.equalsIgnoreCase(last)) { - return; - } + if (idAbbrev.equalsIgnoreCase(last)) return; int commits = countCommitsSince(last); getFvb().sendMsg("Running " + idDescribe + ", " + commits + " new commits since last run (" + last + ")"); @@ -42,16 +37,16 @@ public void processMessage(Privmsg privmsg) { writer.write("QUIT :Rebuilding!\r\n"); writer.flush(); } catch (IOException e) { - LOGGER.error("Failed to send rebuilding message.", e); + e.printStackTrace(); } try (BufferedReader reader = executeRebuild()) { String line; while ((line = reader.readLine()) != null) { - LOGGER.info(line); + System.out.println(line); } } catch (IOException e) { - LOGGER.error("Failed to read shell output.", e); + e.printStackTrace(); } } @@ -63,7 +58,7 @@ private static int countCommitsSince(String idAbbrev) { String line = new BufferedReader(new InputStreamReader(p.getInputStream())).readLine(); return Integer.parseInt(line); } catch (IOException | NumberFormatException e) { - LOGGER.error("Failed to count commits.", e); + e.printStackTrace(); } return -1; diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/SendMessageModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/SendMessageModule.java index 8aea8dd..601f512 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/SendMessageModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/SendMessageModule.java @@ -2,8 +2,6 @@ import org.freecode.irc.Privmsg; import org.freecode.irc.votebot.api.AdminModule; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Created with IntelliJ IDEA. @@ -12,22 +10,16 @@ * Time: 9:48 PM */ public class SendMessageModule extends AdminModule { - private static final Logger LOGGER = LoggerFactory.getLogger(SendMessageModule.class); - @Override public void processMessage(Privmsg privmsg) { - String message = privmsg.getMessage().substring(4).trim(); - - String[] split = message.split(" ", 2); + String msg = privmsg.getMessage().substring(4).trim(); + String[] split = msg.split(" ", 2); String target = split[0]; - message = split[1]; - - if(message.trim().isEmpty()) { + msg = split[1]; + if(msg.trim().isEmpty()) { return; } - - LOGGER.info("Sending message to " + target + ": " + message); - privmsg.getIrcConnection().send(new Privmsg(target, message, privmsg.getIrcConnection())); + privmsg.getIrcConnection().send(new Privmsg(target, msg, privmsg.getIrcConnection())); } @Override diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/WorkingDirectoryModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/WorkingDirectoryModule.java index ead95a1..5525756 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/WorkingDirectoryModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/WorkingDirectoryModule.java @@ -2,22 +2,18 @@ import org.freecode.irc.Privmsg; import org.freecode.irc.votebot.api.AdminModule; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class WorkingDirectoryModule extends AdminModule { - private static final Logger LOGGER = LoggerFactory.getLogger(WorkingDirectoryModule.class); - @Override public void processMessage(Privmsg privmsg) { try (BufferedReader reader = executePwd()) { privmsg.getIrcConnection().send(new Privmsg(privmsg.getNick(), "PWD: " + reader.readLine(), privmsg.getIrcConnection())); } catch (IOException e) { - LOGGER.error("Failed to print working directory.", e); + e.printStackTrace(); } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/common/PollsModule.java b/src/main/java/org/freecode/irc/votebot/modules/common/PollsModule.java index c2461d4..0e11fa0 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/common/PollsModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/common/PollsModule.java @@ -7,25 +7,16 @@ import org.freecode.irc.votebot.dao.VoteDAO; import org.freecode.irc.votebot.entity.Poll; import org.freecode.irc.votebot.entity.Vote; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import java.sql.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.List; import java.util.Locale; import java.util.TimeZone; public class PollsModule extends CommandModule { - private static final Logger LOGGER = LoggerFactory.getLogger(PollsModule.class); - - @Autowired private PollDAO pollDAO; - @Autowired private VoteDAO voteDAO; @Override @@ -48,21 +39,27 @@ public void processMessage(Privmsg privmsg) { privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), message, privmsg.getIrcConnection())); for (Poll poll : polls) { - List votes = voteDAO.getVotesOnPoll(poll.getId()); - int yesCount = Collections.frequency(votes, Vote.YES); - int noCount = Collections.frequency(votes, Vote.NO); - int abstainCount = Collections.frequency(votes, Vote.ABSTAIN); + Vote[] votes = voteDAO.getVotesOnPoll(poll.getId()); + int yes = 0, no = 0, abstain = 0; + for (Vote vote : votes) { + int i = vote.getAnswerIndex(); + if (i == 0) { + yes++; + } else if (i == 1) { + no++; + } else if (i == 2) { + abstain++; + } + } System.out.println(poll.getExpiry()); String msg = "Poll #" + poll.getId() + ": " + poll.getQuestion() + " Ends: " + getDateFormatter().format(new Date(poll.getExpiry())) + " Created by: " + poll.getCreator() + - " Yes: " + yesCount + " No: " + noCount + " Abstain: " + abstainCount; + " Yes: " + yes + " No: " + no + " Abstain: " + abstain; privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), msg, privmsg.getIrcConnection())); } - privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "End list of polls.", privmsg.getIrcConnection())); } catch (SQLException e) { - LOGGER.error("Failed to open poll.", e); privmsg.send(e.getMessage()); } } @@ -82,4 +79,12 @@ private DateFormat getDateFormatter() { dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London")); return dateFormat; } + + public void setPollDAO(PollDAO pollDAO) { + this.pollDAO = pollDAO; + } + + public void setVoteDAO(VoteDAO voteDAO) { + this.voteDAO = voteDAO; + } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/common/StoreTestModule.java b/src/main/java/org/freecode/irc/votebot/modules/common/StoreTestModule.java index d940c84..001283a 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/common/StoreTestModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/common/StoreTestModule.java @@ -2,12 +2,8 @@ import org.freecode.irc.Privmsg; import org.freecode.irc.votebot.api.CommandModule; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class StoreTestModule extends CommandModule { - private static final Logger LOGGER = LoggerFactory.getLogger(StoreTestModule.class); - @Override public void processMessage(Privmsg privmsg) { String command = privmsg.getMessage().substring(getName().length() + 1).trim(); @@ -29,7 +25,7 @@ public void processMessage(Privmsg privmsg) { store(key, value); privmsg.send(key + ": " + readJson(key)); } catch (Exception e) { - LOGGER.error("Failed to read Json.", e); + e.printStackTrace(); } } else if (command.startsWith("get ")) { try { @@ -37,7 +33,7 @@ public void processMessage(Privmsg privmsg) { privmsg.send(key + ": " + readJson(key)); } catch (Exception e) { - LOGGER.error("Failed to read Json.", e); + e.printStackTrace(); } } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java b/src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java index 55dc0a6..8f9d863 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java @@ -8,14 +8,11 @@ import org.freecode.irc.votebot.dao.VoteDAO; import org.freecode.irc.votebot.entity.Poll; import org.freecode.irc.votebot.entity.Vote; -import org.springframework.beans.factory.annotation.Autowired; import java.sql.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.List; import java.util.Locale; import java.util.TimeZone; @@ -26,10 +23,7 @@ */ public class VoteModule extends CommandModule { - @Autowired private PollDAO pollDAO; - - @Autowired private VoteDAO voteDAO; public void processMessage(Privmsg privmsg) { @@ -77,15 +71,23 @@ public void processMessage(Privmsg privmsg) { closed = "Expired"; } - List votes = voteDAO.getVotesOnPoll(poll.getId()); - int yesCount = Collections.frequency(votes, Vote.YES); - int noCount = Collections.frequency(votes, Vote.NO); - int abstainCount = Collections.frequency(votes, Vote.ABSTAIN); + Vote[] votes = voteDAO.getVotesOnPoll(pollId); + int yes = 0, no = 0, abstain = 0; + for (Vote vote : votes) { + int answerIndex = vote.getAnswerIndex(); + if (answerIndex == 0) { + yes++; + } else if (answerIndex == 1) { + no++; + } else if (answerIndex == 2) { + abstain++; + } + } boolean open = closed.equals("Open"); privmsg.send("Poll #" + poll.getId() + ": " + poll.getQuestion() + " Created by: " + poll.getCreator() + - " Yes: " + yesCount + " No: " + noCount + " Abstain: " + abstainCount + + " Yes: " + yes + " No: " + no + " Abstain: " + abstain + " Status: \u00030" + (open ? "3" : "4") + closed + "\u0003" + (open ? " Ends: " : " Ended: ") + expiry); @@ -181,4 +183,12 @@ private DateFormat getDateFormatter() { public String getName() { return "(vote|v|y|n|a)"; } + + public void setPollDAO(PollDAO pollDAO) { + this.pollDAO = pollDAO; + } + + public void setVoteDAO(VoteDAO voteDAO) { + this.voteDAO = voteDAO; + } } diff --git a/src/main/resources/spring/modules.xml b/src/main/resources/spring/modules.xml index 04102d7..e083a51 100644 --- a/src/main/resources/spring/modules.xml +++ b/src/main/resources/spring/modules.xml @@ -7,19 +7,22 @@ - - - - - - - - - + + + - - - + + + + + + + + + + + + @@ -28,4 +31,20 @@ + + + + + + + + + + + + + + + + \ No newline at end of file From 1ef647b723cdf38ddbe16ac3e34c29565a87dab7 Mon Sep 17 00:00:00 2001 From: ShivamMistry Date: Sat, 17 May 2014 23:48:43 +0100 Subject: [PATCH 2/4] replacing internal api with better external one --- api/com/speed/irc/connection/Server.java | 657 ++++++++++++++++++ .../irc/connection/ServerMessageParser.java | 324 +++++++++ .../irc/connection/ServerMessageReader.java | 118 ++++ .../irc/connection/ServerSupportParser.java | 96 +++ .../irc/connection/ssl/IRCTrustManager.java | 43 ++ api/com/speed/irc/event/EventGenerator.java | 44 ++ api/com/speed/irc/event/EventManager.java | 95 +++ api/com/speed/irc/event/IRCEvent.java | 38 + api/com/speed/irc/event/IRCEventListener.java | 26 + .../speed/irc/event/ListenerProperties.java | 30 + api/com/speed/irc/event/api/ApiEvent.java | 73 ++ api/com/speed/irc/event/api/ApiListener.java | 28 + .../speed/irc/event/api/ExceptionEvent.java | 38 + api/com/speed/irc/event/api/WhoisEvent.java | 57 ++ .../speed/irc/event/api/WhoisListener.java | 31 + .../speed/irc/event/channel/ChannelEvent.java | 162 +++++ .../event/channel/ChannelEventListener.java | 32 + .../irc/event/channel/ChannelUserEvent.java | 61 ++ .../event/channel/ChannelUserListener.java | 40 ++ .../irc/event/channel/ModeChangedEvent.java | 85 +++ .../irc/event/channel/TopicChangedEvent.java | 37 + .../irc/event/generators/JoinGenerator.java | 60 ++ .../irc/event/generators/KickGenerator.java | 54 ++ .../irc/event/generators/ModeGenerator.java | 145 ++++ .../irc/event/generators/NoticeGenerator.java | 58 ++ .../irc/event/generators/PartGenerator.java | 53 ++ .../event/generators/PrivmsgGenerator.java | 75 ++ .../irc/event/generators/WhoisGenerator.java | 60 ++ .../speed/irc/event/message/NoticeEvent.java | 52 ++ .../irc/event/message/NoticeListener.java | 31 + .../event/message/PrivateMessageEvent.java | 57 ++ .../event/message/PrivateMessageListener.java | 30 + .../irc/event/message/RawMessageEvent.java | 54 ++ .../irc/event/message/RawMessageListener.java | 31 + api/com/speed/irc/framework/Bot.java | 166 +++++ .../irc/framework/test/GraphicalUserList.java | 95 +++ .../speed/irc/framework/test/HelloBot.java | 190 +++++ api/com/speed/irc/types/Bot.java | 116 ++++ api/com/speed/irc/types/CTCPReply.java | 53 ++ api/com/speed/irc/types/Channel.java | 488 +++++++++++++ api/com/speed/irc/types/ChannelUser.java | 153 ++++ api/com/speed/irc/types/Conversable.java | 76 ++ api/com/speed/irc/types/Mask.java | 85 +++ api/com/speed/irc/types/Mode.java | 51 ++ api/com/speed/irc/types/ModeList.java | 94 +++ api/com/speed/irc/types/Notice.java | 101 +++ api/com/speed/irc/types/ParsingException.java | 58 ++ api/com/speed/irc/types/Privmsg.java | 98 +++ api/com/speed/irc/types/RawMessage.java | 92 +++ api/com/speed/irc/types/ServerUser.java | 195 ++++++ api/com/speed/irc/types/Whois.java | 96 +++ .../speed/irc/util/ControlCodeFormatter.java | 173 +++++ api/com/speed/irc/util/Numerics.java | 42 ++ pom.xml | 19 + run.sh | 1 + .../java/org/freecode/irc/CtcpRequest.java | 55 -- .../java/org/freecode/irc/CtcpResponse.java | 57 -- .../java/org/freecode/irc/IrcConnection.java | 172 ----- src/main/java/org/freecode/irc/Notice.java | 79 --- src/main/java/org/freecode/irc/Privmsg.java | 87 --- .../java/org/freecode/irc/Transmittable.java | 27 - .../irc/event/CtcpRequestListener.java | 14 - .../irc/event/CtcpResponseListener.java | 13 - .../org/freecode/irc/event/JoinListener.java | 11 - .../freecode/irc/event/NoticeListener.java | 13 - .../freecode/irc/event/NumericListener.java | 23 - .../irc/event/PrivateMessageListener.java | 13 - .../irc/event/internal/DelegateListener.java | 9 - .../irc/event/internal/RawIrcListener.java | 21 - .../irc/event/internal/RawJoinProcessor.java | 31 - .../irc/event/internal/RawLineProcessor.java | 15 - .../event/internal/RawNoticeProcessor.java | 40 -- .../internal/RawPrivateMessageProcessor.java | 39 -- .../org/freecode/irc/votebot/FreeVoteBot.java | 208 +++--- .../freecode/irc/votebot/NoticeFilter.java | 22 +- .../freecode/irc/votebot/api/AdminModule.java | 16 +- .../irc/votebot/api/CommandModule.java | 94 +-- .../freecode/irc/votebot/api/FVBModule.java | 6 +- .../modules/admin/CreatePollModule.java | 11 +- .../modules/admin/JoinChannelModule.java | 4 +- .../votebot/modules/admin/LoadModules.java | 32 +- .../modules/admin/OpenClosePollModule.java | 4 +- .../votebot/modules/admin/RebuildModule.java | 134 ++-- .../modules/admin/SendMessageModule.java | 5 +- .../modules/admin/WorkingDirectoryModule.java | 6 +- .../votebot/modules/common/PollsModule.java | 20 +- .../modules/common/StoreTestModule.java | 12 +- .../votebot/modules/common/TestModule.java | 8 +- .../votebot/modules/common/VersionModule.java | 6 +- .../votebot/modules/common/VoteModule.java | 344 ++++----- .../properties/freevotebot.properties | 2 +- 91 files changed, 5792 insertions(+), 1178 deletions(-) create mode 100755 api/com/speed/irc/connection/Server.java create mode 100644 api/com/speed/irc/connection/ServerMessageParser.java create mode 100644 api/com/speed/irc/connection/ServerMessageReader.java create mode 100644 api/com/speed/irc/connection/ServerSupportParser.java create mode 100644 api/com/speed/irc/connection/ssl/IRCTrustManager.java create mode 100644 api/com/speed/irc/event/EventGenerator.java create mode 100755 api/com/speed/irc/event/EventManager.java create mode 100755 api/com/speed/irc/event/IRCEvent.java create mode 100755 api/com/speed/irc/event/IRCEventListener.java create mode 100644 api/com/speed/irc/event/ListenerProperties.java create mode 100644 api/com/speed/irc/event/api/ApiEvent.java create mode 100644 api/com/speed/irc/event/api/ApiListener.java create mode 100644 api/com/speed/irc/event/api/ExceptionEvent.java create mode 100644 api/com/speed/irc/event/api/WhoisEvent.java create mode 100644 api/com/speed/irc/event/api/WhoisListener.java create mode 100644 api/com/speed/irc/event/channel/ChannelEvent.java create mode 100644 api/com/speed/irc/event/channel/ChannelEventListener.java create mode 100644 api/com/speed/irc/event/channel/ChannelUserEvent.java create mode 100644 api/com/speed/irc/event/channel/ChannelUserListener.java create mode 100644 api/com/speed/irc/event/channel/ModeChangedEvent.java create mode 100644 api/com/speed/irc/event/channel/TopicChangedEvent.java create mode 100644 api/com/speed/irc/event/generators/JoinGenerator.java create mode 100644 api/com/speed/irc/event/generators/KickGenerator.java create mode 100644 api/com/speed/irc/event/generators/ModeGenerator.java create mode 100644 api/com/speed/irc/event/generators/NoticeGenerator.java create mode 100644 api/com/speed/irc/event/generators/PartGenerator.java create mode 100644 api/com/speed/irc/event/generators/PrivmsgGenerator.java create mode 100644 api/com/speed/irc/event/generators/WhoisGenerator.java create mode 100755 api/com/speed/irc/event/message/NoticeEvent.java create mode 100755 api/com/speed/irc/event/message/NoticeListener.java create mode 100755 api/com/speed/irc/event/message/PrivateMessageEvent.java create mode 100755 api/com/speed/irc/event/message/PrivateMessageListener.java create mode 100755 api/com/speed/irc/event/message/RawMessageEvent.java create mode 100755 api/com/speed/irc/event/message/RawMessageListener.java create mode 100644 api/com/speed/irc/framework/Bot.java create mode 100644 api/com/speed/irc/framework/test/GraphicalUserList.java create mode 100644 api/com/speed/irc/framework/test/HelloBot.java create mode 100644 api/com/speed/irc/types/Bot.java create mode 100644 api/com/speed/irc/types/CTCPReply.java create mode 100755 api/com/speed/irc/types/Channel.java create mode 100755 api/com/speed/irc/types/ChannelUser.java create mode 100644 api/com/speed/irc/types/Conversable.java create mode 100644 api/com/speed/irc/types/Mask.java create mode 100644 api/com/speed/irc/types/Mode.java create mode 100644 api/com/speed/irc/types/ModeList.java create mode 100644 api/com/speed/irc/types/Notice.java create mode 100644 api/com/speed/irc/types/ParsingException.java create mode 100644 api/com/speed/irc/types/Privmsg.java create mode 100755 api/com/speed/irc/types/RawMessage.java create mode 100644 api/com/speed/irc/types/ServerUser.java create mode 100644 api/com/speed/irc/types/Whois.java create mode 100644 api/com/speed/irc/util/ControlCodeFormatter.java create mode 100755 api/com/speed/irc/util/Numerics.java delete mode 100644 src/main/java/org/freecode/irc/CtcpRequest.java delete mode 100644 src/main/java/org/freecode/irc/CtcpResponse.java delete mode 100644 src/main/java/org/freecode/irc/IrcConnection.java delete mode 100644 src/main/java/org/freecode/irc/Notice.java delete mode 100644 src/main/java/org/freecode/irc/Privmsg.java delete mode 100644 src/main/java/org/freecode/irc/Transmittable.java delete mode 100644 src/main/java/org/freecode/irc/event/CtcpRequestListener.java delete mode 100644 src/main/java/org/freecode/irc/event/CtcpResponseListener.java delete mode 100644 src/main/java/org/freecode/irc/event/JoinListener.java delete mode 100644 src/main/java/org/freecode/irc/event/NoticeListener.java delete mode 100644 src/main/java/org/freecode/irc/event/NumericListener.java delete mode 100644 src/main/java/org/freecode/irc/event/PrivateMessageListener.java delete mode 100644 src/main/java/org/freecode/irc/event/internal/DelegateListener.java delete mode 100644 src/main/java/org/freecode/irc/event/internal/RawIrcListener.java delete mode 100644 src/main/java/org/freecode/irc/event/internal/RawJoinProcessor.java delete mode 100644 src/main/java/org/freecode/irc/event/internal/RawLineProcessor.java delete mode 100644 src/main/java/org/freecode/irc/event/internal/RawNoticeProcessor.java delete mode 100644 src/main/java/org/freecode/irc/event/internal/RawPrivateMessageProcessor.java diff --git a/api/com/speed/irc/connection/Server.java b/api/com/speed/irc/connection/Server.java new file mode 100755 index 0000000..d7328a0 --- /dev/null +++ b/api/com/speed/irc/connection/Server.java @@ -0,0 +1,657 @@ +package com.speed.irc.connection; + +import com.speed.irc.connection.ssl.IRCTrustManager; +import com.speed.irc.event.EventManager; +import com.speed.irc.event.api.ApiEvent; +import com.speed.irc.types.*; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManager; +import java.io.*; +import java.net.Socket; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.*; +import java.util.concurrent.*; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * A class representing a socket connection to an IRC server with the + * functionality of sending raw commands and messages. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class Server implements Runnable { + private volatile BufferedWriter write; + private volatile BufferedReader read; + protected volatile Socket socket; + protected EventManager eventManager = new EventManager(); + protected Map channels = new HashMap(); + private static SSLContext context; + private List users; + private char[] modeSymbols; + private char[] channelPrefix; + private char[] modeLetters; + private String serverName; + private String nick, realName, user; + private ServerMessageParser parser; + protected HashSet ctcpReplies = new HashSet(); + public Map> whoisWaiting = new HashMap>(); + protected boolean autoConnect; + private int port; + private ScheduledThreadPoolExecutor chanExec; + private ScheduledExecutorService serverExecutor, eventExecutor; + private ModeList userModes; + + /** + * Initialises a server object. Only blocking IO is supported. + * + * @param sock The socket used for communication to the IRC server. + * @throws IOException + */ + public Server(final Socket sock) throws IOException { + socket = sock; + port = sock.getPort(); + setServerName(socket.getRemoteSocketAddress().toString()); + write = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); + read = new BufferedReader(new InputStreamReader(sock.getInputStream())); + chanExec = new ScheduledThreadPoolExecutor(10); + serverExecutor = Executors.newSingleThreadScheduledExecutor(); + eventExecutor = Executors.newSingleThreadScheduledExecutor(); + serverExecutor.scheduleWithFixedDelay(this, 1000, 200, TimeUnit.MILLISECONDS); + eventExecutor.scheduleWithFixedDelay(eventManager, 1000, 100, TimeUnit.MILLISECONDS); + parser = new ServerMessageParser(this); + users = new CopyOnWriteArrayList(); + ctcpReplies.add(ServerMessageParser.CTCP_REPLY_VERSION); + ctcpReplies.add(ServerMessageParser.CTCP_REPLY_TIME); + ctcpReplies.add(ServerMessageParser.CTCP_REPLY_PING); + } + + public Server(final String host, final int port) throws IOException { + this(new Socket(host, port)); + + } + + public Server(final String host, final int port, final boolean ssl) throws IOException { + this(ssl ? context.getSocketFactory().createSocket(host, port) : new Socket(host, port)); + } + + static { + try { + context = SSLContext.getInstance("SSL"); + context.init(new KeyManager[0], new TrustManager[]{new IRCTrustManager()}, new SecureRandom()); + } catch (GeneralSecurityException e) { + e.printStackTrace(); + } + } + + public void parseUserModes(final String modes) { + userModes.parse(modes); + } + + public ModeList getUserModes() { + return userModes; + } + + public boolean isUsingSSL() { + return socket instanceof SSLSocket; + } + + public SSLSocket getSSLSocket() { + return isUsingSSL() ? (SSLSocket) socket : null; + } + + public String getRealName() { + return realName; + } + + public String getUser() { + return user; + } + + /** + * Gets the channel thread executor, used to send WHO requests for channels. + * + * @return the channel thread executor + */ + public ScheduledThreadPoolExecutor getChanExec() { + return chanExec; + } + + /** + * Sends a QUIT command (with no message) to the server and shuts down this + * server connection. + */ + public void quit() { + quit(null); + } + + public void setNick(final String newNick) { + sendRaw("NICK " + newNick); + } + + protected void putNick(final String nick) { + this.nick = nick; + } + + public void register(final String nick) { + register(nick, null, null, null); + } + + public void register(final String nick, final String user) { + register(nick, user, null, null); + } + + public void register(final String nick, final String user, final String realName) { + register(nick, user, realName, null); + } + + public void register(final String nick, String user, String realName, final String pass) { + if (nick == null || nick.isEmpty()) { + quit(); + throw new IllegalArgumentException("Nickname is null or empty"); + } + if (pass != null && !pass.isEmpty()) { + sendRaw("PASS " + pass); + } + if (user == null || user.isEmpty()) { + user = nick; + } + if (realName == null || realName.isEmpty()) { + realName = user; + } + setNick(nick); + sendRaw("USER " + user + " 0 * :" + realName); + this.nick = nick; + this.realName = realName; + this.user = user; + } + + /** + * Sends a QUIT command to the server and shuts down this server connection. + * + * @param message the quit message to send to the server, null or + * "" for no message + */ + public void quit(final String message) { + eventManager.dispatchEvent(new ApiEvent(ApiEvent.SERVER_QUIT, this, this)); + parser.reader.running = false; + try { + if (!socket.isClosed()) { + getWriter().write( + "QUIT" + (message == null || message.trim().isEmpty() ? "\n" : (" :" + message + "\n"))); + getWriter().flush(); + socket.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + for (Channel c : channels.values()) { + if (c.getFuture() != null && !c.getFuture().isDone()) + c.getFuture().cancel(true); + } + try { + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + eventExecutor.shutdownNow(); + parser.execServ.shutdownNow(); + chanExec.shutdownNow(); + serverExecutor.shutdownNow(); + } + + /** + * Sets the logger to log debug output to and turns debugging on. + * + * @param logger the logger to log output to. + */ + public final void setReadDebug(final Logger logger) { + parser.reader.logger = logger; + setReadDebug(true); + } + + /** + * Controls whether the API should log debug output. + * + * @param on true to enable debug output, false otherwise + */ + public final void setReadDebug(boolean on) { + parser.reader.logging = on; + } + + protected final void connect() { + try { + socket = new Socket(serverName, port); + write = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); + read = new BufferedReader(new InputStreamReader(socket.getInputStream())); + Logger logger = null; + boolean log = false; + if (parser.reader.logging) { + logger = parser.reader.logger; + log = parser.reader.logging; + } + parser = new ServerMessageParser(this); + if (logger != null && log) { + setReadDebug(logger); + } + } catch (UnknownHostException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public ServerMessageParser getParser() { + return parser; + } + + public CTCPReply getCtcp(String request) { + synchronized (ctcpReplies) { + for (CTCPReply reply : ctcpReplies) { + if (reply.getRequest().equals(request)) { + return reply; + } + } + } + return null; + } + + /** + * Sets whether the api should auto reconnect if the connection is broken. + * Default is off. + * + * @param on + */ + public void setAutoReconnect(final boolean on) { + this.autoConnect = on; + } + + /** + * Gets the current nick as captured by the message sending thread. + * + * @return the current nick for this server connection. + */ + public String getNick() { + return nick; + } + + /** + * Sets a reply to a CTCP request. + * + * @param request the request to send the reply for + * @param reply the reply to send for the request + */ + public void setCtcpReply(final String request, final String reply) { + synchronized (ctcpReplies) { + ctcpReplies.add(new CTCPReply() { + + public String getReply() { + return reply; + } + + public String getRequest() { + return request; + } + + }); + } + } + + public void removeCtcpReply(final CTCPReply reply) { + synchronized (ctcpReplies) { + ctcpReplies.remove(reply); + } + } + + /** + * Adds an automated CTCP reply to the reply list. + * + * @param reply the CTCPReply to be added to the list + */ + public void addCtcpReply(final CTCPReply reply) { + synchronized (ctcpReplies) { + ctcpReplies.add(reply); + } + } + + /** + * Gets the reply which corresponds to the request. + * + * @param request the request to retrieve the reply for + * @return the reply for the supplied request + */ + public String getCtcpReply(final String request) { + synchronized (ctcpReplies) { + for (CTCPReply reply : ctcpReplies) { + Matcher matcher = Pattern.compile(reply.getRequest(), Pattern.CASE_INSENSITIVE).matcher(request); + if (matcher.matches()) { + if (matcher.groupCount() == 0) + return reply.getReply(); + else { + String resp = reply.getReply(); + StringBuffer response = new StringBuffer(); + boolean flag = false; + for (int i = 0; i < resp.length(); i++) { + char c = resp.charAt(i); + if (c == '$' && (i == 0 || resp.charAt(i - 1) != '\\')) { + flag = true; + continue; + } else if (resp.charAt(i - 1) == '\\') { + response.deleteCharAt(i - 1); + } else if (Character.isDigit(c) && flag) { + int group = Character.getNumericValue(c); + flag = false; + try { + String str = matcher.group(group); + response.append(str); + } catch (IndexOutOfBoundsException e) { + e.printStackTrace(); + } + continue; + + } + response.append(c); + + } + return response.toString(); + } + } + } + } + return null; + } + + /** + * Sends a raw command to the server. + * + * @param raw The raw command to be added to the sending queue. + */ + public void sendRaw(String raw) { + if (raw.startsWith("NICK")) { + nick = raw.replace("NICK", "").replace(":", "").trim(); + } + if ((raw.contains("\n") || raw.contains("\r")) && !raw.endsWith("\r\n")) + raw = raw.replace("\n", "").replace("\r", ""); + if (!raw.endsWith("\r\n")) + raw += "\r\n"; + try { + // System.out.println(raw); + write.write(raw); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Gets the channel map. + * + * @return the channel map. + */ + protected Map getChannelMap() { + return channels; + } + + public Collection getChannels() { + return channels.values(); + } + + public void addChannel(final Channel channel) { + channels.put(channel.getName().toLowerCase(), channel); + } + + /** + * Gets the buffered writer. + * + * @return the buffered writer. + */ + public BufferedWriter getWriter() { + return write; + } + + /** + * Sets the buffered writer. + * + * @param write the new buffered writer. + */ + public void setWrite(final BufferedWriter write) { + this.write = write; + } + + /** + * Gets the buffered reader. + * + * @return the buffered reader. + */ + public BufferedReader getReader() { + return read; + } + + /** + * Sets the buffered reader. + * + * @param read the new buffered reader. + */ + public void setRead(final BufferedReader read) { + this.read = read; + } + + /** + * Checks whether the api is connected to the server. + * + * @return true if we are connected, false if + * unconnected. + */ + public boolean isConnected() { + return !socket.isClosed(); + } + + /** + * Gets the channel access mode symbols (e.g. @ for op) + * + * @return the channel access mode symbols. + */ + public char[] getModeSymbols() { + return modeSymbols; + } + + protected void setModeSymbols(final char[] modeSymbols) { + this.modeSymbols = modeSymbols; + } + + /** + * Gets the channel access mode letters (e.g. v for voice) + * + * @return the channel access mode letters + */ + public char[] getModeLetters() { + return modeLetters; + } + + protected void setModeLetters(final char[] modeLetters) { + this.modeLetters = modeLetters; + } + + /** + * Sends a notice to the specified nick. + * + * @param notice the notice to send, sender can be null. + */ + public void sendNotice(final Notice notice) { + sendRaw("NOTICE " + notice.getTarget() + " :" + notice.getMessage() + "\n"); + } + + /** + * Sends a private message to the server. + * + * @param msg the message to send, sender can be null. + */ + public void sendMessage(final Privmsg msg) { + sendRaw(String.format("PRIVMSG %s :%s", msg.getConversable().getName(), msg.getMessage())); + } + + /** + * Gets a server user object with a supplied nickname. + * + * @param nick the nickname to search for + * @return the ServerUser object, creates a new object if the user wasn't + * found. + */ + public ServerUser getUser(final String nick) { + for (ServerUser u : users) { + if (u.getNick().equalsIgnoreCase(nick)) + return u; + } + return new ServerUser(nick, null, null, this); + } + + /** + * Sends an action to a channel/nick. + * + * @param channel The specified channel/nick you would like to send the action + * to. + * @param action The action you would like to send. + */ + public void sendAction(final String channel, final String action) { + sendRaw("PRIVMSG " + channel + ": \u0001ACTION " + action + "\n"); + } + + /** + * Gets the event manager associated with this server object. + * + * @return the event manager for this server. + */ + public EventManager getEventManager() { + return eventManager; + } + + public void run() { + try { + if (write != null) { + write.flush(); + } + } catch (SocketException e) { + if (autoConnect) { + try { + Thread.sleep(5000); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + try { + socket.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + connect(); + eventManager.dispatchEvent(new ApiEvent(ApiEvent.SERVER_DISCONNECTED, this, this)); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + /** + * Sets the server's host address. + * + * @param serverName the server's host address. + */ + public void setServerName(String serverName) { + this.serverName = serverName; + } + + /** + * Gets the server's host address. + * + * @return the server's host address. + */ + public String getServerName() { + return serverName; + } + + /** + * Joins a channel on this server if we are not already joined to it. + * + * @param channelName The name of the channel. + * @return The channel object. + */ + public Channel joinChannel(final String channelName) { + if (channels.containsKey(channelName.trim())) { + final Channel channel = channels.get(channelName.toLowerCase()); + if (!channel.isRunning()) { + channel.join(); + } + return channel; + } + final Channel channel = new Channel(channelName, this); + channel.join(); + return channel; + } + + /** + * Creates/finds a channel object for the specified channel. + * + * @param channelName the name of the channel. + * @return a channel object. + */ + public Channel getChannel(final String channelName) { + return channels.containsKey(channelName.toLowerCase().trim()) ? channels.get(channelName) : new Channel( + channelName, this); + } + + /** + * Adds a user to the Server's list. + * + * @param user the {@link com.speed.irc.types.ServerUser} object to add to + * this Server. + */ + public void addUser(final ServerUser user) { + users.add(user); + } + + protected void removeUser(final ServerUser user) { + users.remove(user); + } + + public boolean hasChannel(final String name) { + return channels.containsKey(name.toLowerCase()); + } + + public boolean hasChannel(final Channel channel) { + return channels.containsValue(channel); + } + + public void addWhoisWaiting(final ServerUser c) { + whoisWaiting.put(c, new LinkedList()); + } + + public char[] getChannelPrefix() { + return parser.getServerSupport().getChanTypes(); + } +} diff --git a/api/com/speed/irc/connection/ServerMessageParser.java b/api/com/speed/irc/connection/ServerMessageParser.java new file mode 100644 index 0000000..838f01b --- /dev/null +++ b/api/com/speed/irc/connection/ServerMessageParser.java @@ -0,0 +1,324 @@ +package com.speed.irc.connection; + +import com.speed.irc.event.EventGenerator; +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.channel.ChannelUserEvent; +import com.speed.irc.event.channel.TopicChangedEvent; +import com.speed.irc.event.generators.*; +import com.speed.irc.event.message.RawMessageEvent; +import com.speed.irc.types.*; +import com.speed.irc.util.Numerics; + +import java.util.Date; +import java.util.List; +import java.util.concurrent.*; + +/** + * Processes messages sent from the server. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ServerMessageParser implements Runnable, EventGenerator { + private final Server server; + private List generators; + protected ServerMessageReader reader; + protected ScheduledExecutorService execServ; + protected Future future; + private ServerSupportParser serverSupport; + + public static final CTCPReply CTCP_REPLY_VERSION = new CTCPReply() { + + public String getReply() { + return "Speed's IRC API"; + } + + public String getRequest() { + return "VERSION"; + } + + }; + + public static final CTCPReply CTCP_REPLY_TIME = new CTCPReply() { + + public String getReply() { + return new Date().toString(); + } + + public String getRequest() { + return "TIME"; + } + + }; + + public static final CTCPReply CTCP_REPLY_PING = new CTCPReply() { + + public String getReply() { + return ""; + } + + public String getRequest() { + return "PING (.*)"; + } + + }; + + public ServerMessageParser(final Server server) { + this.server = server; + generators = new CopyOnWriteArrayList(); + generators.add(this); + generators.add(new JoinGenerator()); + generators.add(new KickGenerator()); + generators.add(new ModeGenerator()); + generators.add(new NoticeGenerator(server)); + generators.add(new PartGenerator()); + generators.add(new PrivmsgGenerator()); + generators.add(new WhoisGenerator(server)); + reader = new ServerMessageReader(server); + execServ = Executors.newSingleThreadScheduledExecutor(); + new Thread(reader, "Server message reader").start(); + future = execServ.scheduleWithFixedDelay(this, 0, 20, + TimeUnit.MILLISECONDS); + serverSupport = new ServerSupportParser(); + } + + private synchronized void parse(final String s) throws Exception { + final RawMessage message = new RawMessage(s, server); + for (EventGenerator generator : generators) { + if (generator.accept(message)) { + IRCEvent event = generator.generate(message); + if (event != null) + server.eventManager.dispatchEvent(event); + } + } + server.eventManager.dispatchEvent(new RawMessageEvent(message, this)); + + } + + /** + * Submits an event generator to this parser + * + * @param generator generator to add + */ + public void addGenerator(final EventGenerator generator) { + if (!generators.contains(generator)) + generators.add(generator); + } + + /** + * Removes a generator from this serverSupport + * + * @param generator the generator to remove + * @return true if it was removed, false if it failed to be removed + */ + public boolean removeGenerator(final EventGenerator generator) { + return generators.remove(generator); + } + + public void run() { + String s; + if (!reader.isEmpty()) { + s = reader.poll(); + if (s.matches("\\W.+")) + s = s.substring(1); + try { + parse(s); + } catch (Exception e) { + server.eventManager + .dispatchEvent(new com.speed.irc.event.api.ExceptionEvent(new ParsingException( + "Parsing error", e), this, server)); + } + } + + } + + public boolean accept(RawMessage message) { + return message != null; + } + + public IRCEvent generate(RawMessage message) { + String raw = message.getRaw(); + String code = message.getCommand().trim(); + if (raw.startsWith("PING")) { + server.sendRaw(raw.replaceFirst("PING", "PONG") + "\n"); + } else if (message.getCommand().equals(Numerics.SERVER_SUPPORT)) { + serverSupport.parse(message); + if (serverSupport.getSettings().containsKey("PREFIX")) { + String t = serverSupport.getSettings().getProperty("PREFIX"); + String letters = t.split("\\(", 2)[1].split("\\)")[0]; + String symbols = t.split("\\)", 2)[1]; + if (letters.length() == symbols.length()) { + server.setModeLetters(letters.toCharArray()); + server.setModeSymbols(symbols.toCharArray()); + } + } + } else if (code.equals(Numerics.CHANNEL_MODES)) { + String chan_name = message.getRaw().split(" ")[3]; + String modez = message.getRaw().split(" ")[4]; + if (!server.channels.containsKey(chan_name)) { + return null; + } + Channel channel = server.channels.get(chan_name); + channel.chanModeList.parse(modez); + } else if (code.equals(Numerics.CHANNEL_NAMES)) { + String[] parts = message.getRaw().split(" "); + // String secret = parts[3]; + String chan_name = parts[4]; + String users = message.getRaw().split(" :")[1]; + if (!server.channels.containsKey(chan_name)) { + return null; + } + Channel channel = server.channels.get(chan_name); + if (channel.isRunning()) { + for (String s : users.split(" ")) { + if (s.matches("[A-Za-z].*")) { + channel.userBuffer.add(new ChannelUser(s, "", "", "", + channel)); + } else { + char c = s.charAt(0); + channel.userBuffer.add(new ChannelUser(s.substring(1), + Character.toString(c), "", "", channel)); + } + } + } + } else if (code.equals(Numerics.CHANNEL_NAMES_END)) { + Channel channel = server.channels.get(raw.split(" ")[3]); + channel.getUsers().clear(); + channel.getUsers().addAll(channel.userBuffer); + channel.userBuffer.clear(); + } else if (code.equals(Numerics.WHO_RESPONSE)) { + Channel channel = server.channels.get(raw.split(" ")[3]); + String[] temp = raw.split(" "); + String user = temp[4]; + String host = temp[5]; + String nick = temp[7]; + String modes = temp[8]; + boolean away = modes.contains("G"); + boolean oper = modes.contains("*"); + boolean identified = modes.contains("r"); + modes = modes.replaceAll("[A-Za-z]", "").replace("*", ""); + ChannelUser u = new ChannelUser(nick, modes, user, host, channel); + u.setIdentified(identified); + u.setAway(away); + u.setOper(oper); + channel.userBuffer.add(u); + + } else if (code.equals(Numerics.WHO_END)) { + Channel channel = server.channels.get(raw.split(" ")[3]); + channel.users.clear(); + channel.users.addAll(channel.userBuffer); + channel.userBuffer.clear(); + } else if (code.toLowerCase().equals("topic")) { + Channel channel = server.getChannel(raw.split(" ")[2]); + if (!channel.isRunning()) { + channel.setup(); + } + String topicSetter = raw.split(" ")[0]; + long time = System.currentTimeMillis(); + String oldTopic = channel.getTopic(); + channel.setTopicSetter(topicSetter); + channel.setTopicSetTime(time); + String[] temp = raw.split(" :", 2); + channel.setTopic(temp[1]); + if (temp[0].substring(temp[0].indexOf("TOPIC")).contains( + channel.getName())) { + return new TopicChangedEvent(channel, topicSetter, this, new String[]{oldTopic, temp[1]}); + } + } else if (code.equals(Numerics.BANNED_FROM_CHANNEL) + && message.getTarget().equals(server.getNick())) { + Channel channel = server.channels.get(raw.split(" ")[3]); + if (channel != null && channel.isRunning()) + channel.isRunning = false; + } else if (code.equals("QUIT")) { + String nick = raw.split("!")[0]; + String quitMsg = ""; + String[] parts = raw.split(" :", 2); + if (parts.length > 1) { + quitMsg = parts[1]; + } + for (Channel c : server.getChannels()) { + if (c.isRunning && c.getUser(nick) != null) { + server.eventManager.dispatchEvent(new ChannelUserEvent( + this, c, c.getUser(nick), + ChannelUserEvent.USER_QUIT, quitMsg)); + } + } + } else if (code.trim().equalsIgnoreCase("nick")) { + try { + final ServerUser u = server.getUser(message.getSender().split( + "!")[0]); + final String oldNick = u.getNick(); + final String newNick = raw.split(" :")[1].trim(); + if (oldNick.equals(server.getNick())) { + server.putNick(newNick); + } + + if (u instanceof ChannelUser) { + return new ChannelUserEvent(this, + u.getChannel(), (ChannelUser) u, + ChannelUserEvent.USER_NICK_CHANGED, oldNick, newNick); + } else { + // this user is not in a channel, so we need to recreate the + // object + ServerUser n_u = new ServerUser(newNick, u.getHost(), + u.getUser(), server); + server.removeUser(u); + server.addUser(n_u); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + parseNumerics(message); + return null; + } + + private void parseNumerics(RawMessage message) { + String code = message.getCommand(); + if (code.equals(Numerics.CHANNEL_TOPIC)) { + String chanName = message.getRaw().split(" ")[3]; + String topic = message.getRaw().split(" :", 2)[1].trim(); + Channel c = server.getChannel(chanName); + if (!c.isRunning()) { + c.setup(); + } + c.setTopic(topic); + + } else if (code.equals(Numerics.CHANNEL_TOPIC_SET)) { + String[] parts = message.getRaw().split(" "); + String chanName = parts[3]; + String setter = parts[4]; + /* + * if(setter.contains("!")) { setter = setter.split("!")[0]; } + */ + // would use the above code but we want the api to capture as much + // info as possible + // some servers send the mask, some just send the nick + String timestamp = parts[5]; + Channel c = server.getChannel(chanName); + if (!c.isRunning()) { + c.setup(); + } + c.setTopicSetter(setter); + c.setTopicSetTime(Long.parseLong(timestamp) * 1000L); + } + } + + public ServerSupportParser getServerSupport() { + return serverSupport; + } +} \ No newline at end of file diff --git a/api/com/speed/irc/connection/ServerMessageReader.java b/api/com/speed/irc/connection/ServerMessageReader.java new file mode 100644 index 0000000..cadedbf --- /dev/null +++ b/api/com/speed/irc/connection/ServerMessageReader.java @@ -0,0 +1,118 @@ +package com.speed.irc.connection; + +import com.speed.irc.event.api.ApiEvent; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.Queue; +import java.util.logging.Logger; + +/** + * Reads messages from the server and adds them to a queue. Encapsulates the + * queue to prevent it being read and modified before the parser parses the + * messages. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ServerMessageReader implements Runnable { + private final Server server; + private Queue queue = new LinkedList(); + private volatile String current; + protected volatile boolean running = true; + protected Logger logger = Logger.getLogger(Logger.class.getName()); + protected boolean logging; + + /** + * No public access to queue to prevent reading before the parser. Gets the + * next message to be read. + * + * @return the next message + */ + protected String poll() { + return queue.poll(); + } + + /** + * Gets the next item on the queue without removing it from the queue. + * + * @return the next item on queue + */ + public String peek() { + return queue.peek(); + } + + /** + * Checks to see if the queue is empty. + * + * @return true if they queue is empty, else false. + */ + public boolean isEmpty() { + return queue.isEmpty(); + } + + /** + * No public access to queue to prevent reading before the parser. Gets the + * queue + * + * @return the queue + */ + protected Queue getQueue() { + return queue; + } + + public ServerMessageReader(final Server server) { + this.server = server; + } + + public void run() { + try { + while (server.isConnected() && running + && (current = server.getReader().readLine()) != null) { + try { + queue.add(current); + } catch (IllegalStateException e) { + + queue.clear(); + queue.add(current); + } + if (logging) { + logger.info(current); + } + if (current.startsWith("ERROR :Closing Link:")) { + if (server.autoConnect && running) { + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + server.connect(); + server.eventManager.dispatchEvent(new ApiEvent( + ApiEvent.SERVER_DISCONNECTED, server, this)); + break; + } + } + } + } catch (IOException e) { + + server.quit(); + + } + + } + +} diff --git a/api/com/speed/irc/connection/ServerSupportParser.java b/api/com/speed/irc/connection/ServerSupportParser.java new file mode 100644 index 0000000..1ebeb4b --- /dev/null +++ b/api/com/speed/irc/connection/ServerSupportParser.java @@ -0,0 +1,96 @@ +package com.speed.irc.connection; + +import com.speed.irc.types.RawMessage; +import com.speed.irc.util.Numerics; + +import java.util.Properties; + +/** + * Parses the server support message (numeric 005) + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ServerSupportParser { + + private RawMessage[] messages; + private int index; + private Properties settings = new Properties(); + + private static final String CHANTYPES = "CHANTYPES"; + + public ServerSupportParser() { + this.messages = new RawMessage[0]; + index = 0; + } + + private void addMessage(RawMessage message) { + if (!message.getCommand().equals(Numerics.SERVER_SUPPORT)) + throw new IllegalArgumentException("Wrong numeric: " + + message.getCommand()); + RawMessage[] msgs = new RawMessage[index + 1]; + msgs[index] = message; + for (int i = 0; i < index; i++) { + msgs[i] = messages[i]; + } + index++; + messages = msgs; + } + + public void parse(RawMessage msg) { + addMessage(msg); + String message = msg.getRaw(); + if (msg.getRaw().contains(" :are supported by this server")) { + message = msg.getRaw() + .replace(" :are supported by this server", "").trim(); + + } + String[] parts = message.split(" "); + for (String s : parts) { + String key = null; + String value = null; + if (s.contains("=")) { + String[] t = s.split("=", 2); + key = t[0]; + value = t[1]; + } else { + key = s; + value = s; + } + settings.put(key, value); + } + } + + public Properties getSettings() { + return settings; + } + + public char[] getChanTypes() { + if (!getSettings().containsKey(CHANTYPES)) { + return new char[]{'@'}; + } else { + return settings.getProperty(CHANTYPES).toCharArray(); + } + } + + public char[][] getChanModes() { + String s = getSettings().getProperty("CHANMODES"); + String[] modes = s.split(",", 4); + return new char[][]{modes[0].toCharArray(), modes[1].toCharArray(), + modes[2].toCharArray(), modes[3].toCharArray()}; + } +} diff --git a/api/com/speed/irc/connection/ssl/IRCTrustManager.java b/api/com/speed/irc/connection/ssl/IRCTrustManager.java new file mode 100644 index 0000000..5d47b01 --- /dev/null +++ b/api/com/speed/irc/connection/ssl/IRCTrustManager.java @@ -0,0 +1,43 @@ +package com.speed.irc.connection.ssl; + +import javax.net.ssl.X509TrustManager; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +/** + * This trust manager does not check certificates. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class IRCTrustManager implements X509TrustManager { + + public void checkClientTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + + } + + public void checkServerTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + +} diff --git a/api/com/speed/irc/event/EventGenerator.java b/api/com/speed/irc/event/EventGenerator.java new file mode 100644 index 0000000..06fa730 --- /dev/null +++ b/api/com/speed/irc/event/EventGenerator.java @@ -0,0 +1,44 @@ +package com.speed.irc.event; + +import com.speed.irc.types.RawMessage; + +/** + * Represents an EventGenerator submitted to the parser. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public interface EventGenerator { + /** + * Checks whether this generator will generate events for the specified message + * + * @param raw the message to test for compatibility with this generator, + * should not be null + * @return true if the message is compatible, false otherwise + */ + public boolean accept(final RawMessage raw); + + /** + * Generates an event object for the specified raw message + * + * @param raw The raw message to generate events for. Undefined behaviour if + * message is not compatible, and should not be null. + * @return The event generated by this method. + */ + public IRCEvent generate(final RawMessage raw); + +} diff --git a/api/com/speed/irc/event/EventManager.java b/api/com/speed/irc/event/EventManager.java new file mode 100755 index 0000000..8877496 --- /dev/null +++ b/api/com/speed/irc/event/EventManager.java @@ -0,0 +1,95 @@ +package com.speed.irc.event; + +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Manages events in a queue, and sends them to the appropriate listener. + * Also manages a list of listeners. + *

+ *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class EventManager implements Runnable { + + private List listeners = new CopyOnWriteArrayList(); + private BlockingQueue eventQueue = new LinkedBlockingQueue(); + + /** + * Adds an event to the event queue. + * + * @param event the event to be processed by the event queue. + */ + public void dispatchEvent(final IRCEvent event) { + eventQueue.offer(event); + } + + /** + * Adds an event listener to this event manager. + * + * @param listener the listener to be added to this event manager. + */ + public void addListener(final IRCEventListener listener) { + listeners.add(listener); + } + + /** + * Removes an event listener from this event manager. + * + * @param listener the listener to be removed + * @return true if the listener was successfully removed, + * false if it wasn't + */ + public boolean removeListener(final IRCEventListener listener) { + return listeners.remove(listener); + } + + public void run() { + IRCEvent e = eventQueue.poll(); + if (e != null) { + for (IRCEventListener listener : listeners) { + for (Class clz : listener.getClass().getInterfaces()) { + if (clz.getAnnotation(ListenerProperties.class) != null) { + try { + ListenerProperties properties = clz.getAnnotation(ListenerProperties.class); + for (Class clazz : properties.events()) { + if (e.getClass().isAssignableFrom(clazz)) { + e.callListener(listener); + } + } + } catch (Exception e1) { + this.dispatchEvent(new com.speed.irc.event.api.ExceptionEvent(e1, this, null)); + e1.printStackTrace(); + } + } + } + } + } + } + + /** + * Clears the queue of events to be processed. + */ + public void clearQueue() { + eventQueue.clear(); + + } + +} diff --git a/api/com/speed/irc/event/IRCEvent.java b/api/com/speed/irc/event/IRCEvent.java new file mode 100755 index 0000000..9de403e --- /dev/null +++ b/api/com/speed/irc/event/IRCEvent.java @@ -0,0 +1,38 @@ +package com.speed.irc.event; + +/** + * Allows identification as an event. All events must implement this class to be + * dispatched by the event manager. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public interface IRCEvent { + /** + * Gets the object that dispatched this event + * + * @return the object that dispatched the event + */ + public Object getSource(); + + /** + * Invokes the correct method(s) from the listener for this event. + * + * @param listener a listener object that accepts this event + */ + public void callListener(IRCEventListener listener); +} diff --git a/api/com/speed/irc/event/IRCEventListener.java b/api/com/speed/irc/event/IRCEventListener.java new file mode 100755 index 0000000..675d9ea --- /dev/null +++ b/api/com/speed/irc/event/IRCEventListener.java @@ -0,0 +1,26 @@ +package com.speed.irc.event; + +/** + * Event listeners must extend this interface to allow them to be registered as + * an event listener. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public interface IRCEventListener { + +} diff --git a/api/com/speed/irc/event/ListenerProperties.java b/api/com/speed/irc/event/ListenerProperties.java new file mode 100644 index 0000000..afed965 --- /dev/null +++ b/api/com/speed/irc/event/ListenerProperties.java @@ -0,0 +1,30 @@ +package com.speed.irc.event; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Event listeners must use this annotation to allow them to receive the correct + * events. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +@Retention(value = RetentionPolicy.RUNTIME) +public @interface ListenerProperties { + Class[] events(); +} diff --git a/api/com/speed/irc/event/api/ApiEvent.java b/api/com/speed/irc/event/api/ApiEvent.java new file mode 100644 index 0000000..a0d7a82 --- /dev/null +++ b/api/com/speed/irc/event/api/ApiEvent.java @@ -0,0 +1,73 @@ +package com.speed.irc.event.api; + +import com.speed.irc.connection.Server; +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.IRCEventListener; + +/** + * Provides events for many API features. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ApiEvent implements IRCEvent { + public static final int SERVER_DISCONNECTED = 1, EXCEPTION_RECEIVED = 2; + + public static final int SERVER_QUIT = 3; + + private int opcode; + private Server server; + private Object source; + + public ApiEvent(final int opcode, final Server server, final Object src) { + source = src; + this.opcode = opcode; + this.server = server; + } + + /** + * Gets the opcode of the event. + * + * @return the opcode of this event + * @see {@link ApiEvent#SERVER_DISCONNECTED}, + * {@link ApiEvent#EXCEPTION_RECEIVED}, {@link ApiEvent#SERVER_QUIT} + */ + public int getOpcode() { + return opcode; + } + + /** + * Gets the server from which the event was thrown. + * + * @return the server from which the event was thrown + */ + public Server getServer() { + return server; + } + + public Object getSource() { + return source; + } + + public void callListener(final IRCEventListener listener) { + if (listener instanceof ApiListener) {// these checks SHOULDN'T be + // necessary + ((ApiListener) listener).apiEventReceived(this); + } + } + +} diff --git a/api/com/speed/irc/event/api/ApiListener.java b/api/com/speed/irc/event/api/ApiListener.java new file mode 100644 index 0000000..ce9e814 --- /dev/null +++ b/api/com/speed/irc/event/api/ApiListener.java @@ -0,0 +1,28 @@ +package com.speed.irc.event.api; + +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.event.ListenerProperties; + +/** + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +@ListenerProperties(events = ApiEvent.class) +public interface ApiListener extends IRCEventListener { + public void apiEventReceived(ApiEvent e); +} diff --git a/api/com/speed/irc/event/api/ExceptionEvent.java b/api/com/speed/irc/event/api/ExceptionEvent.java new file mode 100644 index 0000000..5d3899c --- /dev/null +++ b/api/com/speed/irc/event/api/ExceptionEvent.java @@ -0,0 +1,38 @@ +package com.speed.irc.event.api; + +import com.speed.irc.connection.Server; + +/** + * Wraps an exception into an event + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ExceptionEvent extends ApiEvent { + private final Exception exception; + + public ExceptionEvent(final Exception e, final Object source, + final Server server) { + super(ApiEvent.EXCEPTION_RECEIVED, server, source); + exception = e; + } + + public Exception getException() { + return exception; + } + +} diff --git a/api/com/speed/irc/event/api/WhoisEvent.java b/api/com/speed/irc/event/api/WhoisEvent.java new file mode 100644 index 0000000..21aa2ba --- /dev/null +++ b/api/com/speed/irc/event/api/WhoisEvent.java @@ -0,0 +1,57 @@ +package com.speed.irc.event.api; + +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.types.Whois; + +/** + * Represents a WHOIS event. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class WhoisEvent implements IRCEvent { + + private final Whois whois; + private final Object source; + + public WhoisEvent(final Whois whois, final Object source) { + this.whois = whois; + this.source = source; + } + + /** + * Gets the WHOIS object that this event represents, not guaranteed to be non-null. + * + * @return the event represented by this object, may be null + */ + public Whois getWhois() { + return whois; + } + + public Object getSource() { + return source; + } + + @Override + public void callListener(IRCEventListener listener) { + if (listener instanceof WhoisListener) { + ((WhoisListener) listener).whoisReceived(this); + } + } + +} diff --git a/api/com/speed/irc/event/api/WhoisListener.java b/api/com/speed/irc/event/api/WhoisListener.java new file mode 100644 index 0000000..eb753d4 --- /dev/null +++ b/api/com/speed/irc/event/api/WhoisListener.java @@ -0,0 +1,31 @@ +package com.speed.irc.event.api; + +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.event.ListenerProperties; + +/** + * Marks the implementing class as a WHOIS event listener. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +@ListenerProperties(events = WhoisEvent.class) +public interface WhoisListener extends IRCEventListener { + + public void whoisReceived(WhoisEvent e); + +} diff --git a/api/com/speed/irc/event/channel/ChannelEvent.java b/api/com/speed/irc/event/channel/ChannelEvent.java new file mode 100644 index 0000000..ff4c849 --- /dev/null +++ b/api/com/speed/irc/event/channel/ChannelEvent.java @@ -0,0 +1,162 @@ +package com.speed.irc.event.channel; + +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.types.Channel; +import com.speed.irc.types.ServerUser; + +/** + * Represents a channel event. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public abstract class ChannelEvent implements IRCEvent { + + /** + * Constants for the ChannelEvent#getCode() method, + * #TOPIC_CHANGED means the event was dispatched because the topic changed + * #MODE_CHANGED means the event was dispatched because a channel mode was changed + */ + public static final int TOPIC_CHANGED = 10, + MODE_CHANGED = 11; + private final int code; + private final Channel channel; + private String[] args; + private final Object source; + private ServerUser sender; + + public ChannelEvent(final Channel channel, final int code, + String senderNick, final Object source, final String... args) { + this.code = code; + this.channel = channel; + this.source = source; + this.sender = channel.getUser(senderNick); + if (this.sender == null) + // e.g. ChanServ etc + this.sender = channel.getServer().getUser(senderNick); + this.args = args; + } + + public ChannelEvent(Channel channel2, int code2, Object source2, + final String... args) { + this.code = code2; + this.channel = channel2; + this.source = source2; + this.args = args; + } + + /** + * Gets the code of this event + * See #TOPIC_CHANGED and #MODE_CHANGED + * + * @return the numeric code for this event + * @see #TOPIC_CHANGED and #MODE_CHANGED + */ + public int getCode() { + return code; + } + + /** + * Gets the channel that this event was dispatched for + * + * @return The channel object that represents the channel this event was + * dispatched for. + */ + public Channel getChannel() { + return channel; + } + + /** + * Gets the user that caused this event + * + * @return The {@link ServerUser} (usually {@link com.speed.irc.types.ChannelUser}) + * that caused this event to be dispatched. + */ + public ServerUser getSender() { + return sender; + } + + public Object getSource() { + return source; + } + + public void callListener(IRCEventListener listener) { + if (listener instanceof ChannelUserListener + && this instanceof ChannelUserEvent) { + final ChannelUserListener l = (ChannelUserListener) listener; + final ChannelUserEvent event = (ChannelUserEvent) this; + switch (event.getCode()) { + case ChannelUserEvent.USER_JOINED: + l.channelUserJoined(event); + break; + case ChannelUserEvent.USER_KICKED: + l.channelUserKicked(event); + break; + case ChannelUserEvent.USER_PARTED: + l.channelUserParted(event); + break; + case ChannelUserEvent.USER_NICK_CHANGED: + l.channelUserNickChanged(event); + break; + case ChannelUserEvent.USER_QUIT: + l.channelUserQuit(event); + break; + } + } else if (listener instanceof ChannelUserListener && this instanceof ModeChangedEvent) { + final ChannelEvent event = this; + final ChannelUserListener l = (ChannelUserListener) listener; + final ModeChangedEvent mce = (ModeChangedEvent) this; + if (event.getCode() == ChannelEvent.MODE_CHANGED && mce.getAffectedUser() != null) { + l.channelUserModeChanged(mce); + } + } else if (listener instanceof ChannelEventListener) { + final ChannelEventListener l = (ChannelEventListener) listener; + final ChannelEvent event = this; + switch (event.getCode()) { + case ChannelEvent.MODE_CHANGED: + l.channelModeChanged((ModeChangedEvent) event); + break; + case ChannelEvent.TOPIC_CHANGED: + l.channelTopicChanged((TopicChangedEvent) event); + break; + } + } + } + + /** + * Get the arguments of this event, usually used internally to parse meaningful + * data. + *

+ * For {@link ModeChangedEvent} this should be the contents of this array: + *

+ * [0]: the mode including whether its + or -. + *

+ * [1]: the mask that was affected by this mode, if there was one at all + *

+ * For {@link TopicChangedEvent} this should be the contents of this array: + *

+ * [0]: the old topic + *

+ * [1]: the new topic + * + * @return the arguments of the event + */ + public String[] getArgs() { + return args; + } +} diff --git a/api/com/speed/irc/event/channel/ChannelEventListener.java b/api/com/speed/irc/event/channel/ChannelEventListener.java new file mode 100644 index 0000000..cecb721 --- /dev/null +++ b/api/com/speed/irc/event/channel/ChannelEventListener.java @@ -0,0 +1,32 @@ +package com.speed.irc.event.channel; + +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.event.ListenerProperties; + +/** + * Implement this interface and register to the event manager to receive channel + * events. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +@ListenerProperties(events = {ChannelEvent.class, TopicChangedEvent.class, ModeChangedEvent.class}) +public interface ChannelEventListener extends IRCEventListener { + public void channelTopicChanged(TopicChangedEvent e); + + public void channelModeChanged(ModeChangedEvent e); +} diff --git a/api/com/speed/irc/event/channel/ChannelUserEvent.java b/api/com/speed/irc/event/channel/ChannelUserEvent.java new file mode 100644 index 0000000..3898aa8 --- /dev/null +++ b/api/com/speed/irc/event/channel/ChannelUserEvent.java @@ -0,0 +1,61 @@ +package com.speed.irc.event.channel; + +import com.speed.irc.types.Channel; +import com.speed.irc.types.ChannelUser; + +/** + * Represents a channel user event. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ChannelUserEvent extends ChannelEvent { + + private ChannelUser user; + public static final int USER_JOINED = 0, USER_PARTED = 1, USER_MODE_CHANGED = 2, USER_KICKED = 3, + USER_NICK_CHANGED = 4, USER_QUIT = 5; + + public ChannelUserEvent(Object source, final Channel channel, final ChannelUser user, final int code) { + super(channel, code, source); + this.user = user; + } + + public ChannelUserEvent(Object source, final Channel channel, final ChannelUser user, final String sender, + final int code, final String... args) { + super(channel, code, sender, source, args); + this.user = user; + } + + public ChannelUserEvent(Object source, final Channel channel, final ChannelUser user, final int code, + final String... args) { + super(channel, code, source, args); + this.user = user; + } + + public ChannelUser getUser() { + return user; + } + + /** + * @return + * @deprecated see {@link #getArgs()} instead + */ + public String[] getArguments() { + return getArgs(); + } + +} diff --git a/api/com/speed/irc/event/channel/ChannelUserListener.java b/api/com/speed/irc/event/channel/ChannelUserListener.java new file mode 100644 index 0000000..13e8aa2 --- /dev/null +++ b/api/com/speed/irc/event/channel/ChannelUserListener.java @@ -0,0 +1,40 @@ +package com.speed.irc.event.channel; + +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.event.ListenerProperties; + +/** + * Implement this interface and register to the event manager to receive channel + * user events. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +@ListenerProperties(events = {ChannelUserEvent.class, ModeChangedEvent.class}) +public interface ChannelUserListener extends IRCEventListener { + public void channelUserJoined(ChannelUserEvent e); + + public void channelUserParted(ChannelUserEvent e); + + public void channelUserModeChanged(ModeChangedEvent e); + + public void channelUserKicked(ChannelUserEvent e); + + public void channelUserNickChanged(ChannelUserEvent e); + + public void channelUserQuit(ChannelUserEvent e); +} diff --git a/api/com/speed/irc/event/channel/ModeChangedEvent.java b/api/com/speed/irc/event/channel/ModeChangedEvent.java new file mode 100644 index 0000000..88aaca5 --- /dev/null +++ b/api/com/speed/irc/event/channel/ModeChangedEvent.java @@ -0,0 +1,85 @@ +package com.speed.irc.event.channel; + +import com.speed.irc.types.Channel; +import com.speed.irc.types.ChannelUser; +import com.speed.irc.types.ModeList; + +/** + * A class representing the change of modes in a Channel. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ModeChangedEvent extends ChannelEvent { + private final ChannelUser affectedUser; + private final ModeList modes; + private final String affectedMask; + private final String rawModes; + + public ModeChangedEvent(Channel channel, String senderNick, Object source, String... args) { + super(channel, ChannelEvent.MODE_CHANGED, senderNick, source, args); + modes = new ModeList(channel.getServer(), args[0]); + affectedMask = args.length == 1 ? channel.getName() : args[1]; + affectedUser = null; + rawModes = args[0]; + } + + public ModeChangedEvent(Channel channel, ChannelUser affectedUser, String senderNick, Object source, String... args) { + super(channel, ChannelEvent.MODE_CHANGED, senderNick, source, args); + this.affectedUser = affectedUser; + this.modes = new ModeList(channel.getServer(), args[0]); + affectedMask = null; + rawModes = args[0]; + } + + /** + * Gets the modes added to the channel + * + * @return the modes added to the channel + */ + public ModeList getNewModes() { + return modes; + } + + /** + * Gets the user affected by this mode change. + * + * @return the user affected by this change if appropriate, else null. + */ + public ChannelUser getAffectedUser() { + return affectedUser; + } + + /** + * Gets the mask affected by this mode change. + * + * @return the mask affected by this change if appropriate, else null. + */ + public String getAffectedMask() { + return affectedMask; + } + + /** + * Gets the raw mode affected by this mode change + * + * @return the mode affected by this change + */ + public String getRowMode() { + return rawModes; + } + +} diff --git a/api/com/speed/irc/event/channel/TopicChangedEvent.java b/api/com/speed/irc/event/channel/TopicChangedEvent.java new file mode 100644 index 0000000..aba4c3b --- /dev/null +++ b/api/com/speed/irc/event/channel/TopicChangedEvent.java @@ -0,0 +1,37 @@ +package com.speed.irc.event.channel; + +import com.speed.irc.types.Channel; + +/** + * Represents a topic changed event. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class TopicChangedEvent extends ChannelEvent { + public TopicChangedEvent(Channel channel, String changerNick, Object source, String... args) { + super(channel, ChannelEvent.TOPIC_CHANGED, changerNick, source, args); + } + + public String getOldTopic() { + return getArgs()[0]; + } + + public String getNewTopic() { + return getArgs()[1]; + } +} diff --git a/api/com/speed/irc/event/generators/JoinGenerator.java b/api/com/speed/irc/event/generators/JoinGenerator.java new file mode 100644 index 0000000..071c3a5 --- /dev/null +++ b/api/com/speed/irc/event/generators/JoinGenerator.java @@ -0,0 +1,60 @@ +package com.speed.irc.event.generators; + +import com.speed.irc.event.EventGenerator; +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.channel.ChannelUserEvent; +import com.speed.irc.types.Channel; +import com.speed.irc.types.ChannelUser; +import com.speed.irc.types.RawMessage; + +/** + * Processes JOIN messages sent from the server. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class JoinGenerator implements EventGenerator { + + public boolean accept(RawMessage raw) { + return raw.getCommand().equals("JOIN"); + } + + public IRCEvent generate(RawMessage raw) { + final String[] parts = raw.getRaw().split("!"); + final String nick = parts[0]; + final String user = parts[1].split("@")[0]; + final String host = parts[1].split("@")[1].split(" ")[0]; + String chan = raw.getRaw().split(" ")[2]; + if (raw.getRaw().split(" ")[2].startsWith(":")) { + chan = chan.substring(1); + } + Channel channel = raw.getServer().getChannel(chan); + if (channel == null) { + channel = new Channel(chan, raw.getServer()); + channel.setup(); + } else if (!channel.isRunning()) { + channel.setup(); + } + if (channel.getUser(nick) != null) { + channel.removeChannelUser(channel.getUser(nick)); + } + final ChannelUser u = new ChannelUser(nick, "", user, host, channel); + return new ChannelUserEvent(this, channel, u, + ChannelUserEvent.USER_JOINED); + } + +} diff --git a/api/com/speed/irc/event/generators/KickGenerator.java b/api/com/speed/irc/event/generators/KickGenerator.java new file mode 100644 index 0000000..6af6fe4 --- /dev/null +++ b/api/com/speed/irc/event/generators/KickGenerator.java @@ -0,0 +1,54 @@ +package com.speed.irc.event.generators; + +import com.speed.irc.event.EventGenerator; +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.channel.ChannelUserEvent; +import com.speed.irc.types.Channel; +import com.speed.irc.types.ChannelUser; +import com.speed.irc.types.RawMessage; + +/** + * Processes KICK messages sent from the server. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class KickGenerator implements EventGenerator { + + public boolean accept(RawMessage raw) { + return raw.getCommand().equals("KICK"); + } + + public IRCEvent generate(RawMessage raw) { + final Channel channel = raw.getServer().getChannel( + raw.getRaw().split(" ")[2]); + if (channel == null) { + return null; + } + final ChannelUser user = channel.getUser(raw.getRaw().split(" ")[3]); + if (user == null) { + return null; + } + String kickMsg = ""; + String[] parts = raw.getRaw().split(" :", 2); + if (parts.length > 1) { + kickMsg = parts[1]; + } + return new ChannelUserEvent(this, channel, user, raw.getSender().split( + "!")[0].trim(), ChannelUserEvent.USER_KICKED, kickMsg); + } +} diff --git a/api/com/speed/irc/event/generators/ModeGenerator.java b/api/com/speed/irc/event/generators/ModeGenerator.java new file mode 100644 index 0000000..87d1810 --- /dev/null +++ b/api/com/speed/irc/event/generators/ModeGenerator.java @@ -0,0 +1,145 @@ +package com.speed.irc.event.generators; + +import com.speed.irc.connection.Server; +import com.speed.irc.event.EventGenerator; +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.channel.ModeChangedEvent; +import com.speed.irc.types.Channel; +import com.speed.irc.types.ChannelUser; +import com.speed.irc.types.Mask; +import com.speed.irc.types.RawMessage; + +import java.util.Arrays; + +/** + * Processes MODE messages sent from the server. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ModeGenerator implements EventGenerator { + + public boolean accept(RawMessage raw) { + return raw.getCommand().equals("MODE"); + } + + public IRCEvent generate(RawMessage message) { + String raw = message.getRaw(); + Server server = message.getServer(); + String sender = message.getSender(); + String name = message.getTarget(); + Channel channel = null; + if (Arrays.binarySearch(server.getChannelPrefix(), name.charAt(0)) >= 0) { + channel = server.getChannel(name); + if (!channel.isRunning()) { + channel.setup(); + } + } + if (name.equals(server.getNick())) { + String modes = raw.split(" :", 2)[1].trim(); + server.parseUserModes(modes); + return null; + } + String senderNick = sender.split("!")[0].trim(); + raw = raw.split(name, 2)[1].trim(); + String[] strings = raw.split(" "); + String modes = strings[0]; + if (strings.length == 1 && channel != null) { + channel.chanModeList.parse(modes); + return new ModeChangedEvent(channel, senderNick, this, modes); + } else { + String[] u = new String[strings.length - 1]; + System.arraycopy(strings, 1, u, 0, u.length); + boolean plus = false; + int index = 0; + for (int i = 0; i < modes.toCharArray().length; i++) { + char c = modes.toCharArray()[i]; + if (c == '+') { + plus = true; + continue; + } else if (c == '-') { + plus = false; + continue; + } + if (c == 'b') { + if (plus) { + channel.bans.add(new Mask(u[index])); + } else { + channel.bans.remove(new Mask(u[index])); + } + server.getEventManager().dispatchEvent( + new ModeChangedEvent(channel, senderNick, this, (plus ? "+" : "-") + + "b", u[index])); + index++; + + continue; + } else if (c == 'e') { + if (plus) { + channel.exempts.add(new Mask(u[index])); + } else { + channel.exempts.remove(new Mask(u[index])); + } + server.getEventManager().dispatchEvent( + new ModeChangedEvent(channel, senderNick, this, (plus ? "+" : "-") + + "e", u[index])); + index++; + + continue; + } else if (c == 'I') { + if (plus) { + channel.invites.add(new Mask(u[index])); + } else { + channel.invites.remove(new Mask(u[index])); + } + server.getEventManager().dispatchEvent( + new ModeChangedEvent(channel, senderNick, this, (plus ? "+" : "-") + + "I", u[index])); + index++; + + continue; + } + if (Arrays.binarySearch(server.getModeLetters(), c) >= 0) { + //this is a known rank, with a nick argument + ChannelUser user = channel.getUser(u[index]); + if (user == null) { + user = new ChannelUser(u[index], "", null, null, channel); + channel.addChannelUser(user); + } + if (user != null) { + if (plus) { + user.addMode(c); + } else { + user.removeMode(c); + } + server.getEventManager().dispatchEvent( + new ModeChangedEvent(channel, user, senderNick, this, + (plus ? "+" : "-") + c)); + + } + } else { + //channel modes + channel.getModeList().parse((plus ? "+" : "-") + c); + } + index++; + + } + + } + return null; + } + +} diff --git a/api/com/speed/irc/event/generators/NoticeGenerator.java b/api/com/speed/irc/event/generators/NoticeGenerator.java new file mode 100644 index 0000000..b53c06f --- /dev/null +++ b/api/com/speed/irc/event/generators/NoticeGenerator.java @@ -0,0 +1,58 @@ +package com.speed.irc.event.generators; + +import com.speed.irc.connection.Server; +import com.speed.irc.event.EventGenerator; +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.message.NoticeEvent; +import com.speed.irc.types.Notice; +import com.speed.irc.types.RawMessage; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Processes NOTICE messages sent from the server. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class NoticeGenerator implements EventGenerator { + private static final Pattern PATTERN_NOTICE = Pattern + .compile("(.+?)!(.+?)@(.+?) NOTICE (.+?) :(.*)"); + private final Server server; + + public NoticeGenerator(Server server) { + this.server = server; + } + + public boolean accept(RawMessage raw) { + return PATTERN_NOTICE.matcher(raw.getRaw()).matches(); + } + + public IRCEvent generate(RawMessage raw) { + final Matcher notice_matcher = PATTERN_NOTICE.matcher(raw.getRaw()); + if (notice_matcher.matches()) { + final String msg = notice_matcher.group(5); + final String sender = notice_matcher.group(1) + '!' + + notice_matcher.group(2) + '@' + notice_matcher.group(3); + final String name = notice_matcher.group(4); + return new NoticeEvent(new Notice(msg, sender, name, server), this); + } + return null; + } + +} diff --git a/api/com/speed/irc/event/generators/PartGenerator.java b/api/com/speed/irc/event/generators/PartGenerator.java new file mode 100644 index 0000000..f22dd46 --- /dev/null +++ b/api/com/speed/irc/event/generators/PartGenerator.java @@ -0,0 +1,53 @@ +package com.speed.irc.event.generators; + +import com.speed.irc.event.EventGenerator; +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.channel.ChannelUserEvent; +import com.speed.irc.types.Channel; +import com.speed.irc.types.ChannelUser; +import com.speed.irc.types.RawMessage; + +/** + * Processes PART messages sent from the server. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class PartGenerator implements EventGenerator { + + public boolean accept(RawMessage raw) { + return raw.getCommand().equals("PART"); + } + + public IRCEvent generate(RawMessage raw) { + final String nick = raw.getSender().split("!")[0]; + Channel channel = raw.getServer() + .getChannel(raw.getRaw().split(" ")[2]); + if (!channel.isRunning()) { + channel.setup(); + } + final ChannelUser user = channel.getUser(nick); + String[] parts = raw.getRaw().split(" :", 2); + String partMsg = ""; + if (parts.length > 1) { + partMsg = parts[1]; + } + return new ChannelUserEvent(this, channel, user, + ChannelUserEvent.USER_PARTED, partMsg); + } + +} diff --git a/api/com/speed/irc/event/generators/PrivmsgGenerator.java b/api/com/speed/irc/event/generators/PrivmsgGenerator.java new file mode 100644 index 0000000..1df4685 --- /dev/null +++ b/api/com/speed/irc/event/generators/PrivmsgGenerator.java @@ -0,0 +1,75 @@ +package com.speed.irc.event.generators; + +import com.speed.irc.connection.Server; +import com.speed.irc.event.EventGenerator; +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.message.PrivateMessageEvent; +import com.speed.irc.types.*; + +import java.util.Arrays; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Processes PRIVMSG messages sent from the server. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class PrivmsgGenerator implements EventGenerator { + private static final Pattern PATTERN_PRIVMSG = Pattern + .compile("(.+?)!(.+?)@(.+?) PRIVMSG (.+?) :(.*)"); + + public boolean accept(RawMessage raw) { + return PATTERN_PRIVMSG.matcher(raw.getRaw()).matches(); + } + + public IRCEvent generate(RawMessage raw) { + final Matcher priv_matcher = PATTERN_PRIVMSG.matcher(raw.getRaw()); + final Server server = raw.getServer(); + if (priv_matcher.matches()) { + final String msg = priv_matcher.group(5); + final String sender = priv_matcher.group(1); + final String user = priv_matcher.group(2); + final String host = priv_matcher.group(3); + final String name = priv_matcher.group(4); + if (msg.startsWith("\u0001")) {// ctcp messages + String request = msg.replace("\u0001", ""); + String reply = server.getCtcpReply(request); + if (reply != null) { + server.sendRaw(String.format( + "NOTICE %s :\u0001%s %s\u0001\n", sender, request, + reply)); + } + } + Conversable conversable = null; + if (Arrays.binarySearch(server.getChannelPrefix(), name.charAt(0)) >= 0) { + conversable = server.getChannel(name); + Channel c = (Channel) conversable; + if (!c.isRunning()) { + c.setup(); + } + } else { + conversable = new ServerUser(sender, host, user, server); + } + return new PrivateMessageEvent( + new Privmsg(msg, sender, conversable), this); + } + return null; + } + +} diff --git a/api/com/speed/irc/event/generators/WhoisGenerator.java b/api/com/speed/irc/event/generators/WhoisGenerator.java new file mode 100644 index 0000000..8c00220 --- /dev/null +++ b/api/com/speed/irc/event/generators/WhoisGenerator.java @@ -0,0 +1,60 @@ +package com.speed.irc.event.generators; + +import com.speed.irc.connection.Server; +import com.speed.irc.event.EventGenerator; +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.api.WhoisEvent; +import com.speed.irc.types.RawMessage; +import com.speed.irc.types.Whois; +import com.speed.irc.util.Numerics; + +import java.util.Collection; + +/** + * Generates WHOIS events. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class WhoisGenerator implements EventGenerator { + private final Server server; + + public WhoisGenerator(final Server server) { + this.server = server; + } + + public boolean accept(RawMessage raw) { + for (String s : Numerics.WHOIS) { + if (s.equals(raw.getCommand())) + return true; + } + return false; + } + + public IRCEvent generate(RawMessage raw) { + String user = raw.getRaw().split(" ")[3]; + Collection messages = server.whoisWaiting.get(server + .getUser(user)); + if (raw.getCommand().equals(Numerics.WHOIS_END)) { + return new WhoisEvent(new Whois(messages, server), this); + } else { + messages.add(raw); + return null; + } + } + +} diff --git a/api/com/speed/irc/event/message/NoticeEvent.java b/api/com/speed/irc/event/message/NoticeEvent.java new file mode 100755 index 0000000..1ac9b55 --- /dev/null +++ b/api/com/speed/irc/event/message/NoticeEvent.java @@ -0,0 +1,52 @@ +package com.speed.irc.event.message; + +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.types.Notice; + +/** + * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class NoticeEvent implements IRCEvent { + protected final Notice notice; + protected final Object source; + + public NoticeEvent(final Notice notice, final Object source) { + this.notice = notice; + this.source = source; + } + + /** + * Gets the notice object represented by this event + * + * @return the notice object represented by this event + */ + public Notice getNotice() { + return notice; + } + + public Object getSource() { + return source; + } + + public void callListener(IRCEventListener listener) { + if (listener instanceof NoticeListener) { + ((NoticeListener) listener).noticeReceived(this); + } + } +} diff --git a/api/com/speed/irc/event/message/NoticeListener.java b/api/com/speed/irc/event/message/NoticeListener.java new file mode 100755 index 0000000..7089a92 --- /dev/null +++ b/api/com/speed/irc/event/message/NoticeListener.java @@ -0,0 +1,31 @@ +package com.speed.irc.event.message; + +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.event.ListenerProperties; + +/** + * Implement this interface and register to the event manager to receive notice + * events. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +@ListenerProperties(events = NoticeEvent.class) +public interface NoticeListener extends IRCEventListener { + public void noticeReceived(NoticeEvent e); + +} diff --git a/api/com/speed/irc/event/message/PrivateMessageEvent.java b/api/com/speed/irc/event/message/PrivateMessageEvent.java new file mode 100755 index 0000000..f426968 --- /dev/null +++ b/api/com/speed/irc/event/message/PrivateMessageEvent.java @@ -0,0 +1,57 @@ +package com.speed.irc.event.message; + +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.types.Privmsg; + +/** + * The wrapper class for an PRIVMSG event. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class PrivateMessageEvent implements IRCEvent { + + protected final Object source; + protected final Privmsg message; + + public PrivateMessageEvent(final Privmsg message, final Object source) { + this.source = source; + this.message = message; + } + + public Object getSource() { + return source; + } + + /** + * Gets the message associated with this event. + * + * @return the message associated with this event. + */ + public Privmsg getMessage() { + return message; + } + + public void callListener(IRCEventListener listener) { + if (listener instanceof PrivateMessageListener) { + ((PrivateMessageListener) listener) + .messageReceived(this); + } + } + +} diff --git a/api/com/speed/irc/event/message/PrivateMessageListener.java b/api/com/speed/irc/event/message/PrivateMessageListener.java new file mode 100755 index 0000000..bbf2bda --- /dev/null +++ b/api/com/speed/irc/event/message/PrivateMessageListener.java @@ -0,0 +1,30 @@ +package com.speed.irc.event.message; + +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.event.ListenerProperties; + +/** + * Implement this interface and register to event manager to receive private + * message events. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +@ListenerProperties(events = PrivateMessageEvent.class) +public interface PrivateMessageListener extends IRCEventListener { + public void messageReceived(PrivateMessageEvent e); +} diff --git a/api/com/speed/irc/event/message/RawMessageEvent.java b/api/com/speed/irc/event/message/RawMessageEvent.java new file mode 100755 index 0000000..e373ad5 --- /dev/null +++ b/api/com/speed/irc/event/message/RawMessageEvent.java @@ -0,0 +1,54 @@ +package com.speed.irc.event.message; + +import com.speed.irc.event.IRCEvent; +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.types.RawMessage; + +/** + * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class RawMessageEvent implements IRCEvent { + + private RawMessage message; + protected Object source; + + public RawMessageEvent(final RawMessage message, final Object source) { + this.message = message; + this.source = source; + } + + /** + * Gets the raw message associated with this event + * + * @return the raw message associated with this event. + */ + public RawMessage getMessage() { + return message; + } + + public Object getSource() { + return source; + } + + public void callListener(IRCEventListener listener) { + if (listener instanceof RawMessageListener) { + ((RawMessageListener) listener).rawMessageReceived(this); + } + } + +} diff --git a/api/com/speed/irc/event/message/RawMessageListener.java b/api/com/speed/irc/event/message/RawMessageListener.java new file mode 100755 index 0000000..f167a08 --- /dev/null +++ b/api/com/speed/irc/event/message/RawMessageListener.java @@ -0,0 +1,31 @@ +package com.speed.irc.event.message; + +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.event.ListenerProperties; + +/** + * Implement this interface and register to the event manager to receive raw + * message events. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +@ListenerProperties(events = RawMessageEvent.class) +public interface RawMessageListener extends IRCEventListener { + public void rawMessageReceived(RawMessageEvent e); + +} diff --git a/api/com/speed/irc/framework/Bot.java b/api/com/speed/irc/framework/Bot.java new file mode 100644 index 0000000..2d250b5 --- /dev/null +++ b/api/com/speed/irc/framework/Bot.java @@ -0,0 +1,166 @@ +package com.speed.irc.framework; + +import com.speed.irc.connection.Server; +import com.speed.irc.event.api.ApiEvent; +import com.speed.irc.event.api.ApiListener; +import com.speed.irc.event.api.ExceptionEvent; +import com.speed.irc.types.Channel; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.logging.Logger; + +/** + * The abstract class for making robots. To create a robot, you can extend this + * class. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public abstract class Bot implements ApiListener { + + private Server server; + protected final int port; + protected Logger logger = Logger.getLogger(Bot.class.getName()); + protected int modes; + + /** + * Gets the port the bot is connected to + * + * @return the port the bot is connected to + */ + public int getPort() { + return port; + } + + /** + * Logs an info message + * + * @param message the message to log + */ + public final void info(final String message) { + logger.info(message); + } + + /** + * Gets the server the bot is connected to + * + * @return the server the bot is connected to + */ + public final Server getServer() { + return server; + } + + /** + * Executed just after connecting to the server and before joining channels + */ + public abstract void onStart(); + + /** + * Initialises a bot. + * + * @param server the server host name to connect to + * @param port the port number + * @param ssl whether to use ssl or not + */ + public Bot(final String server, final int port, boolean ssl) { + this.port = port; + try { + this.server = new Server(server, port, ssl); + this.server.register(getNick(), getUser(), getRealName()); + this.server.getEventManager().addListener(this); + onStart(); + for (Channel s : getChannels()) { + s.join(); + } + } catch (UnknownHostException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public Bot(final String server, final int port) { + this(server, port, false); + } + + /** + * Gets the channels to auto connect to + * + * @return the channels to auto connect to + */ + public abstract Channel[] getChannels(); + + /** + * Gets the nickname the bot should try to connect with + * + * @return the nickname of the bot + */ + public abstract String getNick(); + + /** + * Gets the alternative nickname of the bot + * + * @return the alternative nickname of the bot + */ + public String getAltNick() { + return getNick() + "_"; + } + + /** + * Gets the real name of the bot + * + * @return the real name of bot + */ + public String getRealName() { + return "SpeedsIrcApi"; + } + + /** + * Gets the username of the bot + * + * @return the username of bot + */ + public String getUser() { + return "SpeedsIrcApi"; + } + + private void connect() { + server.register(getNick(), getUser(), getRealName()); + for (Channel s : getChannels()) { + s.join(); + } + } + + /** + * Used to identify to NickServ. + * + * @param password The password assigned to your nick + */ + public void identify(final String password) { + server.sendRaw("PRIVMSG NickServ :identify " + password + "\n"); + } + + public void apiEventReceived(ApiEvent e) { + if (e.getOpcode() == ApiEvent.SERVER_DISCONNECTED) { + connect(); + } else if (e.getOpcode() == ApiEvent.EXCEPTION_RECEIVED) { + ((ExceptionEvent) e).getException().printStackTrace(); + } + } +} diff --git a/api/com/speed/irc/framework/test/GraphicalUserList.java b/api/com/speed/irc/framework/test/GraphicalUserList.java new file mode 100644 index 0000000..e8c58b0 --- /dev/null +++ b/api/com/speed/irc/framework/test/GraphicalUserList.java @@ -0,0 +1,95 @@ +package com.speed.irc.framework.test; + +import com.speed.irc.framework.Bot; +import com.speed.irc.types.Channel; +import com.speed.irc.types.ChannelUser; + +import javax.swing.*; + +/** + * Displays a visual list of all the users in the channel, and associated + * properties. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class GraphicalUserList extends JFrame implements Runnable { + + private Channel mainChannel; + private JList list; + private ListModel model; + + public static void main(String[] args) { + new GraphicalUserList(); + } + + public GraphicalUserList() { + Bot bot = new Bot("irc.rizon.net", 6697, true) { + + public void onStart() { + mainChannel = new Channel("#freecode", getServer()); + getServer().setReadDebug(true); + } + + public Channel[] getChannels() { + return new Channel[]{mainChannel}; + } + + public String getNick() { + return "UserLister"; + } + + }; + setSize(200, 300); + setDefaultCloseOperation(EXIT_ON_CLOSE); + setTitle("User List"); + model = new AbstractListModel() { + + @Override + public int getSize() { + return mainChannel.getUsers().size(); + } + + @Override + public ChannelUser getElementAt(int index) { + return mainChannel.getSortedUsers()[index]; + } + }; + list = new JList(model); + list.setFixedCellHeight(15); + JScrollPane pane = new JScrollPane(list, + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + add(pane); + setVisible(true); + new Thread(this).start(); + } + + public void run() { + while (isVisible() && mainChannel.isJoined()) { + //okay we should REALLY be using API listeners for this but w.e + setTitle("User Lister " + mainChannel.getName() + " " + mainChannel.getModeList().parse()); + repaint(); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + +} diff --git a/api/com/speed/irc/framework/test/HelloBot.java b/api/com/speed/irc/framework/test/HelloBot.java new file mode 100644 index 0000000..321d4f0 --- /dev/null +++ b/api/com/speed/irc/framework/test/HelloBot.java @@ -0,0 +1,190 @@ +package com.speed.irc.framework.test; + +import com.speed.irc.event.api.ApiEvent; +import com.speed.irc.event.api.WhoisEvent; +import com.speed.irc.event.api.WhoisListener; +import com.speed.irc.event.channel.ChannelUserEvent; +import com.speed.irc.event.channel.ChannelUserListener; +import com.speed.irc.event.channel.ModeChangedEvent; +import com.speed.irc.event.message.PrivateMessageEvent; +import com.speed.irc.event.message.PrivateMessageListener; +import com.speed.irc.framework.Bot; +import com.speed.irc.types.*; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.Random; + +/** + * Greets people as they join the channel or speak a greeting. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class HelloBot extends Bot implements ChannelUserListener, + PrivateMessageListener, WhoisListener { + + private static final String[] HELLO_PHRASES = new String[]{"Hello", "Hi", + "Hey", "Yo", "Wassup", "helo", "herro", "hiya", "hai", "heya", + "sup"}; + private static final Random RANDOM_GENERATOR = new Random(); + private volatile Channel[] channels; + private final static String OWNER = "Speed"; + + public HelloBot(final String server, final int port, final boolean ssl) { + super(server, port, ssl); + + } + + @Override + public String getRealName() { + return "Hello Bot"; + } + + public static void main(String[] args) { + new HelloBot("irc.rizon.net", 6697, true); + } + + public Channel[] getChannels() { + return channels; + } + + public String getNick() { + return "HelloBot"; + } + + public void onStart() { + channels = new Channel[]{new Channel("#freecode", getServer())}; + channels[0].setAutoRejoin(true); + // identify("password"); + getServer().setAutoReconnect(true); + getServer().setReadDebug(true); + } + + @Override + public void apiEventReceived(final ApiEvent e) { + super.apiEventReceived(e); + if (e.getOpcode() == ApiEvent.SERVER_QUIT) { + logger.info("WE HAVE QUIT FROM THE SERVER."); + } + } + + public void messageReceived(PrivateMessageEvent e) { + final String message = e.getMessage().getMessage(); + final String sender = e.getMessage().getSender(); + if (message.contains("!raw") && sender.equals(OWNER)) { + getServer().sendRaw(message.replaceFirst("!raw", "").trim()); + } else if (message.equals("!quit") && sender.equals(OWNER)) { + getServer().quit("bai"); + } else if (message.equals("!list") && sender.equals(OWNER)) { + Channel main = channels[0]; + if (main.isRunning()) { + Collection users = main.getUsers(); + for (ChannelUser u : users) { + info(u.getMask().toString() + " - " + + Integer.toBinaryString(u.getRights())); + } + } else { + info("Not in channel"); + } + } else if (message.equals("!rejoin") && sender.equals(OWNER)) { + channels[0].setAutoRejoin(!channels[0].isAutoRejoinOn()); + info(Boolean.toString(channels[0].isAutoRejoinOn())); + } else if (message.startsWith("!verify") && sender.equals(OWNER)) { + e.getMessage() + .getConversable() + .sendMessage( + Boolean.toString(Mask.verify(message.replaceFirst( + "!verify", "").trim()))); + + } else if (message.equals("!print")) { + e.getMessage().getConversable().sendMessage(getServer().getNick()); + } else if (message.equals("!topic")) { + if (e.getMessage().getConversable().isChannel()) { + Channel c = e.getMessage().getConversable().getChannel(); + c.sendMessage("Topic: " + c.getTopic()); + c.sendMessage("Topic set by: " + c.getTopicSetter()); + c.sendMessage("Topic set at: " + + new Date(c.getTopicSetTime()).toString()); + } + } else if (message.startsWith("!whois") && sender.equals(OWNER)) { + String name = message.replace("!whois", "").trim(); + ServerUser user = getServer().getUser(name); + user.requestWhois(); + } + if (e.getMessage().getConversable() == null + || !(e.getMessage().getConversable() instanceof Channel)) { + return; + } + final Channel channel = (Channel) e.getMessage().getConversable(); + final ChannelUser user = channel.getUser(sender); + for (String s : HELLO_PHRASES) { + if (message.toLowerCase().equals(s.toLowerCase()) + || (message.toLowerCase().contains( + getServer().getNick().toLowerCase()) && message + .toLowerCase().contains(s.toLowerCase()))) { + channel.sendMessage(HELLO_PHRASES[RANDOM_GENERATOR + .nextInt(HELLO_PHRASES.length - 1)] + + " " + + sender + + " with rights: " + user.getRights()); + } + + } + } + + public void channelUserJoined(ChannelUserEvent e) { + e.getChannel().sendMessage( + HELLO_PHRASES[RANDOM_GENERATOR + .nextInt(HELLO_PHRASES.length - 1)] + + " " + + e.getUser().getNick()); + } + + public void channelUserParted(ChannelUserEvent e) { + } + + public void channelUserModeChanged(ModeChangedEvent e) { + } + + + public void channelUserKicked(ChannelUserEvent e) { + } + + public void channelUserNickChanged(ChannelUserEvent e) { + final String newNick = e.getArgs()[1]; + final String oldNick = e.getArgs()[0]; + info(oldNick + " changed to " + newNick); + e.getChannel().sendMessage( + HELLO_PHRASES[RANDOM_GENERATOR + .nextInt(HELLO_PHRASES.length - 1)] + " " + newNick); + } + + public void whoisReceived(WhoisEvent e) { + Whois is = e.getWhois(); + channels[0].sendMessage("Whois: " + is.getUser().toString()); + channels[0].sendMessage("Whois: " + Arrays.toString(is.getChannels())); + } + + @Override + public void channelUserQuit(ChannelUserEvent e) { + // TODO Auto-generated method stub + + } + +} diff --git a/api/com/speed/irc/types/Bot.java b/api/com/speed/irc/types/Bot.java new file mode 100644 index 0000000..3051fee --- /dev/null +++ b/api/com/speed/irc/types/Bot.java @@ -0,0 +1,116 @@ +package com.speed.irc.types; + +import com.speed.irc.connection.Server; +import com.speed.irc.event.IRCEventListener; +import com.speed.irc.event.api.ApiEvent; +import com.speed.irc.event.api.ApiListener; +import com.speed.irc.event.api.ExceptionEvent; + +import java.io.IOException; +import java.net.Socket; +import java.net.UnknownHostException; +import java.util.logging.Logger; + +/** + * The abstract class for making robots. To create a robot, you can extend this + * class. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + * @deprecated use {@link com.speed.irc.framework.Bot} instead + */ +public abstract class Bot implements ApiListener { + + protected Server server; + protected final int port; + protected Logger logger = Logger.getLogger(Bot.class.getName()); + protected int modes; + + public int getPort() { + return port; + } + + public final void info(final String message) { + logger.info(message); + } + + public final Server getServer() { + return server; + } + + public abstract void onStart(); + + public Bot(final String server, final int port) { + this.port = port; + try { + this.server = new Server(new Socket(server, port)); + this.server.sendRaw("NICK " + getNick() + "\n"); + this.server.sendRaw("USER " + getUser() + " 0 * :" + getRealName()); + if (this instanceof IRCEventListener) { + this.server.getEventManager().addListener( + (IRCEventListener) this); + } + onStart(); + for (Channel s : getChannels()) { + s.join(); + } + } catch (UnknownHostException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public abstract Channel[] getChannels(); + + public abstract String getNick(); + + public String getRealName() { + return "SpeedsIrcApi"; + } + + public String getUser() { + return "Speed"; + } + + private void connect() { + this.server.sendRaw("NICK " + getNick() + "\n"); + this.server.sendRaw("USER " + getUser() + " " + modes + " * :" + + getRealName() + "\n"); + for (Channel s : getChannels()) { + s.join(); + } + } + + /** + * Used to identify to NickServ. + * + * @param password The password assigned to your nick + */ + public void identify(final String password) { + server.sendRaw("PRIVMSG NickServ :identify " + password + "\n"); + } + + public void apiEventReceived(ApiEvent e) { + if (e.getOpcode() == ApiEvent.SERVER_DISCONNECTED) { + connect(); + } else if (e.getOpcode() == ApiEvent.EXCEPTION_RECEIVED) { + ((ExceptionEvent) e).getException().printStackTrace(); + } + } +} diff --git a/api/com/speed/irc/types/CTCPReply.java b/api/com/speed/irc/types/CTCPReply.java new file mode 100644 index 0000000..e71ebcd --- /dev/null +++ b/api/com/speed/irc/types/CTCPReply.java @@ -0,0 +1,53 @@ +package com.speed.irc.types; + +/** + * Abstract class used to represent CTCP requests and replies, allows CTCP + * replies to be dynamic. + *

+ *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public abstract class CTCPReply { + /** + * Gets the reply message + * + * @return the reply message + */ + public abstract String getReply(); + + /** + * Gets the request message + * + * @return the request message + */ + public abstract String getRequest(); + + @Override + public boolean equals(Object o) { + if (o instanceof CTCPReply) { + return getReply().equals(((CTCPReply) o).getReply()) + && getRequest().equals(((CTCPReply) o).getRequest()); + } + return false; + } + + @Override + public int hashCode() { + return (getReply().hashCode() | getRequest().hashCode()) & 0xffffff; + } +} diff --git a/api/com/speed/irc/types/Channel.java b/api/com/speed/irc/types/Channel.java new file mode 100755 index 0000000..26f439b --- /dev/null +++ b/api/com/speed/irc/types/Channel.java @@ -0,0 +1,488 @@ +package com.speed.irc.types; + +import com.speed.irc.connection.Server; +import com.speed.irc.event.channel.ChannelUserEvent; +import com.speed.irc.event.channel.ChannelUserListener; +import com.speed.irc.event.channel.ModeChangedEvent; + +import java.util.*; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +/** + * Represents a channel + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class Channel extends Conversable implements ChannelUserListener, + Runnable { + protected String name; + protected Server server; + public volatile List users = new LinkedList(); + public volatile List userBuffer = new LinkedList(); + public volatile boolean isRunning = false; + public long whoDelay = 120000L; + private long topicSetTime; + private String topicSetter; + public int autoRejoinDelay = 50; + protected boolean autoRejoin; + public ModeList chanModeList; + public List bans = new LinkedList(); + public List exempts = new LinkedList(); + public List invites = new LinkedList(); + protected String topic; + protected ScheduledFuture future; + + public Future getFuture() { + return future; + } + + /** + * Constructs a channel. + * + * @param name the name of the channel. + * @param server the server object this channel is associated with. + */ + public Channel(final String name, final Server server) { + this.name = name; + this.server = server; + this.server.getEventManager().addListener(this); + this.server.addChannel(this); + chanModeList = new ModeList(server, ""); + } + + /** + * Gets the name of the channel. + * + * @return the name of the channel + */ + public String getName() { + return name; + } + + public ModeList getModeList() { + return chanModeList; + } + + /** + * Gets the list of users in the channel. + * + * @return The list of users in the channel. + */ + public Collection getUsers() { + return users; + } + + /** + * Gets a user from the channel. + * + * @param nick The nick of the ChannelUser to get. + * @return The ChannelUser object associated with the nick or + * null. + */ + public ChannelUser getUser(final String nick) { + for (ChannelUser user : users) { + if (user.getNick().equalsIgnoreCase(nick)) { + return user; + } + } + return null; + } + + /** + * Adds a channel user to this channel. + * + * @param user the user to add + * @return true if it is added, false otherwise. + */ + public boolean addChannelUser(final ChannelUser user) { + return users.add(user); + } + + /** + * Removes a user from the channel. + * + * @param user the user to remove. + * @return true if they were removed, false otherwise. + */ + public boolean removeChannelUser(final ChannelUser user) { + return users.remove(user); + } + + /** + * Checks whether the channel will be auto-rejoined when kicked. + * + * @return true if auto-rejoin is on, false otherwise. + */ + public boolean isAutoRejoinOn() { + return autoRejoin; + } + + /** + * Sets whether rejoining is enabled when kicked + * + * @param on turn auto-rejoin on or not + */ + public void setAutoRejoin(final boolean on) { + autoRejoin = on; + } + + /** + * Leaves the channel. + * + * @param message The part message, can be null for no message. + */ + public void part(final String message) { + isRunning = false; + if (message != null && !message.isEmpty()) + server.sendRaw(String.format("PART %s :%s\n", name, message)); + else + server.sendRaw(String.format("PART %s\n", name)); + } + + public boolean isRunning() { + return isRunning; + } + + public void run() { + if (isRunning) { + server.sendRaw("WHO " + name); + future = server.getChanExec().schedule(this, whoDelay, + TimeUnit.MILLISECONDS); + } + + } + + /** + * Gets the server the channel is on. + * + * @return the server the channel is on + */ + public Server getServer() { + return server; + } + + /** + * Joins the channel. + */ + public void join() { + server.sendRaw("JOIN :" + name); + } + + public void setup() { + server.sendRaw("MODE " + name); + isRunning = true; + if (!server.hasChannel(this)) + server.addChannel(this); + future = server.getChanExec().schedule(this, 5000L, + TimeUnit.MILLISECONDS); + } + + public boolean isJoined() { + return isRunning(); + } + + /** + * Joins the channel using the provided password. + * + * @param password the password to join the channel with + */ + public void join(final String password) { + server.sendRaw("JOIN :" + name + " " + password); + setup(); + } + + /** + * Returns a sorted array of ChannelUser objects. This array is sorted by + * first descending channel rank and then by descending alphabetical order + * (by nick). + * + * @return the sorted array of users + */ + public ChannelUser[] getSortedUsers() { + final Collection users = getUsers(); + ChannelUser[] u = users.toArray(new ChannelUser[users.size()]); + Arrays.sort(u, new Comparator() { + + public int compare(ChannelUser o1, ChannelUser o2) { + int c = o2.getRights() - o1.getRights(); + if (c == 0) { + return o1.getNick().toLowerCase() + .compareTo(o2.getNick().toLowerCase()); + } + return c; + } + }); + return u; + } + + /** + * Bans then kicks the channel user with the reason specified. + * + * @param user the ChannelUser to kick. + * @param reason The reason for kicking the channel user, can be + * null. + */ + public void kickBan(final ChannelUser user, final String reason) { + ban(user); + kick(user, reason); + } + + /** + * Attempts to ban the specified ChannelUser. + * + * @param user the user that should be banned. + */ + public void ban(final ChannelUser user) { + final String banMask = "*!*@" + user.getHost(); + ban(banMask); + } + + /** + * Attempts to ban the specified mask. + * + * @param banMask The ban-mask that should be banned. + */ + public void ban(final String banMask) { + server.sendRaw(String.format("MODE %s +b %s\n", name, banMask)); + } + + /** + * Attempts to kick a channel user. + * + * @param user The ChannelUser that is to be kicked. + * @param reason The reason for kicking the channel user, can be + * null. + */ + public void kick(final ChannelUser user, String reason) { + if (reason == null) { + reason = user.getNick(); + } + server.sendRaw(String.format("KICK %s %s :%s\n", name, user.getNick(), + reason)); + } + + /** + * Attempts to kick a channel user. + * + * @param nick The nick of the user that is to be kicked. + * @param reason The reason for kicking the channel user, can be + * null. + */ + public void kick(final String nick, String reason) { + final ChannelUser user = getUser(nick); + if (user == null) { + return; + } + if (reason == null) { + reason = user.getNick(); + } + server.sendRaw(String.format("KICK %s %s :%s\n", name, user.getNick(), + reason)); + + } + + /** + * Sets the channel's topic. Attempts to send any changes to the server. + * + * @param topic The new channel topic. + */ + public void sendTopic(final String topic) { + server.sendRaw(String.format("TOPIC %s :%s\n", name, topic)); + } + + /** + * Sets the topic in the memory. + * + * @param newTopic the new channel topic + */ + public void setTopic(final String newTopic) { + this.topic = newTopic; + } + + /** + * Gets the topic. + * + * @return the channel's topic + */ + public String getTopic() { + return topic; + } + + @Override + public String toString() { + return name; + } + + @Override + public boolean equals(final Object o) { + return o instanceof Channel + && ((Channel) o).getName().equalsIgnoreCase(getName()); + } + + public Collection getChannelUsers(final Mask mask) { + final List users = new LinkedList(); + for (ChannelUser user : users) { + if (mask.matches(user)) { + users.add(user); + } + } + return users; + } + + public void channelUserJoined(ChannelUserEvent e) { + if (e.getChannel().equals(this)) { + if (getUser(e.getUser().getNick()) == null) { + addChannelUser(e.getUser()); + } else { + ChannelUser user = e.getChannel().getUser(e.getUser().getNick()); + user.user = e.getUser().getUser(); + user.host = e.getUser().getHost(); + } + if (e.getUser().getNick().equals(server.getNick()) && !isRunning()) { + setup(); + } + } + } + + public void channelUserParted(ChannelUserEvent e) { + if (e.getChannel().equals(this)) { + ChannelUser user = e.getUser(); + if (user != null) { + removeChannelUser(user); + if (user.getNick().equals(server.getNick())) { + isRunning = false; + future.cancel(true); + } + } + + } + } + + public void channelUserModeChanged(ModeChangedEvent e) { + } + + public void channelUserKicked(ChannelUserEvent e) { + if (e.getChannel().equals(this)) { + ChannelUser user = e.getUser(); + removeChannelUser(user); + if (user.getNick().equals(server.getNick()) && isAutoRejoinOn()) { + try { + Thread.sleep(autoRejoinDelay); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + isRunning = false; + server.getChannels().remove(this); + join(); + } else if (user.getNick().equals(server.getNick())) { + isRunning = false; + server.getChannels().remove(this); + } + } + } + + /** + * Sets a/many mode(s) on this channel. For example, to give a user voice + * via modes:
+ * MODE #channel +vv-o nick1 nick2 nick2
+ * One would need to use:
+ * setMode("+vv-o", "nick1", "nick2", "nick2") + * + * @param mode the mode(s) to set. + * @param args the arguments of the mode, for example nicknames. + */ + public void setMode(String mode, String... args) { + StringBuilder arg = new StringBuilder(); + for (String s : args) { + arg.append(s).append(' '); + } + server.sendRaw(String.format("MODE %s %s %s", name, mode, + arg.toString())); + } + + /** + * Removes kick exempt from a mask. + * + * @param mask the mask to remove the kick exempt from. + */ + public void removeExempt(String mask) { + setMode("-e", mask); + } + + /** + * Removes kick exempt from a mask. + * + * @param mask the mask to remove the kick exempt from. + */ + public void removeExempt(Mask mask) { + removeExempt(mask.toString()); + } + + public void channelUserNickChanged(ChannelUserEvent e) { + final String newNick = e.getArgs()[1]; + if (e.getUser() != null) { + final ChannelUser user = e.getUser(); + final ChannelUser replace = new ChannelUser(newNick, + user.getModes(), user.getUser(), user.getHost(), + e.getChannel()); + e.getChannel().removeChannelUser(user); + e.getChannel().addChannelUser(replace); + } + } + + /** + * @return the topic set time + */ + public long getTopicSetTime() { + return topicSetTime; + } + + /** + * sets the topic set time, should only really be used internally + * + * @param topicSetTime the topic set time + */ + public void setTopicSetTime(long topicSetTime) { + this.topicSetTime = topicSetTime; + } + + /** + * @return the topic setter + */ + public String getTopicSetter() { + return topicSetter; + } + + /** + * sets the topic setter, should only really be used internally + * + * @param topicSetter the topic setter + */ + public void setTopicSetter(String topicSetter) { + this.topicSetter = topicSetter; + } + + public void channelUserQuit(ChannelUserEvent e) { + if (e.getChannel().equals(this)) { + ChannelUser user = e.getUser(); + removeChannelUser(user); + } + } +} \ No newline at end of file diff --git a/api/com/speed/irc/types/ChannelUser.java b/api/com/speed/irc/types/ChannelUser.java new file mode 100755 index 0000000..3a2b11b --- /dev/null +++ b/api/com/speed/irc/types/ChannelUser.java @@ -0,0 +1,153 @@ +package com.speed.irc.types; + +/** + * Represents a user in a channel. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ChannelUser extends ServerUser { + private String modes; + private ModeList channelModes; + private final Channel channel; + public static final int VOICE_FLAG = 0x1, HALF_OP_FLAG = 0x2, + OP_FLAG = 0x4, ADMIN_FLAG = 0x8, OWNER_FLAG = 0x10; + private int rights; + + public Channel getChannel() { + return channel; + } + + public ChannelUser(final String nick, final String modes, + final String user, final String host, final Channel channel) { + super(nick, host, user, channel.getServer()); + this.channel = channel; + this.channelModes = new ModeList(this.channel.server, ""); + this.modes = (modes); + if (!modes.isEmpty()) + sync(modes); + } + + public void sync(String modes) { + channelModes.clear(); + StringBuilder builder = new StringBuilder("+"); + for (char c : modes.toCharArray()) { + builder.append(channelModes.channelModeSymbolToLetter(c)); + } + channelModes.parse(builder.toString()); + char[] modeSymbols = channel.getServer().getModeSymbols(); + if (modeSymbols.length == 5) { + if (modes.indexOf(modeSymbols[0]) != -1) + rights = rights | OWNER_FLAG; + if (modes.indexOf(modeSymbols[1]) != -1) + rights = rights | ADMIN_FLAG; + if (modes.indexOf(modeSymbols[2]) != -1) + rights = rights | OP_FLAG; + if (modes.indexOf(modeSymbols[3]) != -1) + rights = rights | HALF_OP_FLAG; + if (modes.indexOf(modeSymbols[4]) != -1) + rights = rights | VOICE_FLAG; + } else if (modeSymbols.length == 2) { + if (modes.indexOf(modeSymbols[0]) != -1) + rights = rights | OP_FLAG; + if (modes.indexOf(modeSymbols[1]) != -1) + rights = rights | VOICE_FLAG; + } else if (modeSymbols.length == 3) { + if (modes.indexOf(modeSymbols[0]) != -1) + rights = rights | OP_FLAG; + if (modes.indexOf(modeSymbols[1]) != -1) + rights = rights | HALF_OP_FLAG; + if (modes.indexOf(modeSymbols[2]) != -1) + rights = rights | VOICE_FLAG; + } else if (modeSymbols.length == 4) { + if (modes.indexOf(modeSymbols[0]) != -1) + rights = rights | ADMIN_FLAG; + if (modes.indexOf(modeSymbols[1]) != -1) + rights = rights | OP_FLAG; + if (modes.indexOf(modeSymbols[2]) != -1) + rights = rights | HALF_OP_FLAG; + if (modes.indexOf(modeSymbols[3]) != -1) + rights = rights | VOICE_FLAG; + } + } + + public void addMode(char mode) { + mode = channelModes.channelModeLetterToSymbol(mode); + if (modes.indexOf(mode) < 0) { + modes = modes + mode; + sync(modes); + } + } + + public String getModes() { + return modes; + } + + public void removeExempts() { + for (final Mask mask : channel.exempts) { + if (mask.matches(this)) { + channel.removeExempt(mask); + } + } + } + + public void removeMode(char mode) { + mode = channelModes.channelModeLetterToSymbol(mode); + StringBuilder builder = new StringBuilder(); + for (char c : modes.toCharArray()) { + if (c != mode) { + builder.append(c); + } + } + modes = builder.toString(); + sync(modes); + } + + public boolean isOperator() { + return (getRights() & OP_FLAG) != 0; + } + + public boolean isHalfOperator() { + return (getRights() & HALF_OP_FLAG) != 0; + } + + public boolean isVoiced() { + return (getRights() & VOICE_FLAG) != 0; + } + + public boolean isOwner() { + return (getRights() & OWNER_FLAG) != 0; + } + + public boolean isProtected() { + return (getRights() & ADMIN_FLAG) != 0; + } + + /** + * Useful if you're only checking for a single flag. + * + * @returns the bitmask of the user's flags + */ + public int getRights() { + return rights; + } + + @Override + public String toString() { + return modes + getNick(); + } +} diff --git a/api/com/speed/irc/types/Conversable.java b/api/com/speed/irc/types/Conversable.java new file mode 100644 index 0000000..c34462a --- /dev/null +++ b/api/com/speed/irc/types/Conversable.java @@ -0,0 +1,76 @@ +package com.speed.irc.types; + +import com.speed.irc.connection.Server; + +/** + * An abstract representation of a communicable entity on a server. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public abstract class Conversable { + /** + * Sends a PRIVMSG message to the entity. + * + * @param message the message that is to be sent. + */ + public void sendMessage(final String message) { + getServer().sendMessage(new Privmsg(message, null, this)); + } + + /** + * Sends a NOTICE message to the entity. + * + * @param notice the notice that is to be sent. + */ + public void sendNotice(final String notice) { + getServer() + .sendNotice(new Notice(notice, null, getName(), getServer())); + } + + /** + * Gets the name of the entity. + * + * @return the name of the channel or user. + */ + public abstract String getName(); + + /** + * Gets the server this entity is on. + * + * @return the server. + */ + public abstract Server getServer(); + + public boolean isChannel() { + return this instanceof Channel; + } + + public boolean isUser() { + return this instanceof ServerUser; + } + + public Channel getChannel() { + return isChannel() ? (Channel) this : null; + } + + public ServerUser getServerUser() { + return isUser() ? (ServerUser) this : null; + } + + +} diff --git a/api/com/speed/irc/types/Mask.java b/api/com/speed/irc/types/Mask.java new file mode 100644 index 0000000..f56be2e --- /dev/null +++ b/api/com/speed/irc/types/Mask.java @@ -0,0 +1,85 @@ +package com.speed.irc.types; + +import com.speed.irc.util.ControlCodeFormatter; + +/** + * Class used to encapsulate user masks + *

+ *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class Mask { + + private final String mask; + + /** + * Initialise the user mask + * + * @param mask the mask to use + */ + public Mask(final String mask) { + this.mask = mask.toLowerCase(); + if (!verify(mask)) + throw new IllegalArgumentException("Mask doesn't match *!*@*: " + mask); + } + + public Mask(final String nick, final String user, final String host) { + this.mask = (nick + '!' + user + '@' + host).toLowerCase(); + if (!verify(mask)) + throw new IllegalArgumentException("Arguments are not valid: " + + mask); + } + + /** + * Verifies if the mask is valid + * + * @param mask the mask to check + * @return true if the mask is valid, false if it isn't. + */ + public static boolean verify(final String mask) { + return mask + .matches("[a-zA-Z\\*][\\-\\\\\\[\\]\\^\\`\\*\\w\\|]*?!~?[\\-\\\\\\[\\]\\^\\`\\*\\w\\|]+?@[\\-\\\\\\[\\]\\^\\`\\*\\w\\.\\:" + + ControlCodeFormatter.UNICODE_COLOUR + "]+"); + } + + /** + * Checks if a user matches this mask. + * + * @param user the user to check + * @return true if they do match, false if they don't + */ + public boolean matches(ServerUser user) { + String nickMask = mask.substring(0, mask.indexOf('!')).replace("*", + ".*"); + String userMask = mask.substring(mask.indexOf('!') + 1, + mask.indexOf('@')).replace("*", ".*"); + String hostMask = mask.substring(mask.indexOf('@') + 1) + .replace("", "\\.").replace("*", ".*"); + return user.getNick().toLowerCase().matches(nickMask) + && user.getUser().toLowerCase().matches(userMask) + && user.getHost().toLowerCase().matches(hostMask); + } + + public boolean equals(Object o) { + return o instanceof Mask && ((Mask) o).mask.equals(mask); + } + + public String toString() { + return mask; + } +} diff --git a/api/com/speed/irc/types/Mode.java b/api/com/speed/irc/types/Mode.java new file mode 100644 index 0000000..a7df9ed --- /dev/null +++ b/api/com/speed/irc/types/Mode.java @@ -0,0 +1,51 @@ +package com.speed.irc.types; + +import com.speed.irc.connection.Server; + +/** + * A class representing a single user and channel mode. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class Mode { + + private final char mode; + private final boolean plus; + + public Mode(final String s) { + if (!s.matches("[\\+-][A-Za-z]")) { + throw new IllegalArgumentException("Incorrect mode format"); + } + this.mode = s.charAt(1); + this.plus = s.charAt(0) == '+'; + } + + public Mode(final boolean plus, final char mode) { + this.plus = plus; + this.mode = mode; + } + + public ModeList newModeList(final Server server) { + return new ModeList(server, toString()); + } + + + public String toString() { + return String.valueOf(plus ? '+' : '-') + mode; + } +} diff --git a/api/com/speed/irc/types/ModeList.java b/api/com/speed/irc/types/ModeList.java new file mode 100644 index 0000000..98278f8 --- /dev/null +++ b/api/com/speed/irc/types/ModeList.java @@ -0,0 +1,94 @@ +package com.speed.irc.types; + +import com.speed.irc.connection.Server; + +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; + +/** + * A class representing user and channel modes. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ModeList { + private Set modes = new CopyOnWriteArraySet(); + private final Server server; + + public ModeList(final Server server, final String modes) { + this.server = server; + if (!modes.isEmpty()) + parse(modes); + } + + + protected void clear() { + modes.clear(); + } + + public char channelModeLetterToSymbol(char letter) { + for (int i = 0; i < server.getModeLetters().length; i++) { + if (server.getModeLetters()[i] == letter) { + return server.getModeSymbols()[i]; + } + } + return '0'; + } + + public char channelModeSymbolToLetter(char symbol) { + for (int i = 0; i < server.getModeSymbols().length; i++) { + if (server.getModeSymbols()[i] == symbol) { + return server.getModeLetters()[i]; + } + } + return '0'; + } + + public String parse() { + if (modes.size() > 0) { + StringBuilder builder = new StringBuilder(modes.size()); + for (char c : modes) { + builder.append(c); + } + return '+' + builder.toString(); + } else { + return ""; + } + } + + public void parse(String modes) { + boolean plus = false; + for (int i = 0; i < modes.toCharArray().length; i++) { + char c = modes.toCharArray()[i]; + if (c == '+') { + plus = true; + continue; + } else if (c == '-') { + plus = false; + continue; + } + if (plus) { + + this.modes.add(c); + } else { + if (this.modes.contains(c)) + this.modes.remove(c); + + } + } + } +} diff --git a/api/com/speed/irc/types/Notice.java b/api/com/speed/irc/types/Notice.java new file mode 100644 index 0000000..b36d34d --- /dev/null +++ b/api/com/speed/irc/types/Notice.java @@ -0,0 +1,101 @@ +package com.speed.irc.types; + +import com.speed.irc.connection.Server; + +import java.util.Arrays; + +/** + * A wrapper class for NOTICE messages. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see {@link http://www.gnu.org/licenses/}. + * + * @author Shivam Mistry + */ +public class Notice { + private final String message, sender, target; + private final Server server; + + /** + * @param message The actual message. + * @param sender The nick of the person who the notice was sent to/from. + * @param target The channel the notice was sent to/from. + * @param server The server the notice should be sent on. + */ + public Notice(final String message, final String sender, + final String target, final Server server) { + this.message = message; + this.target = target; + this.sender = sender; + this.server = server; + } + + /** + * Gets the message parsed from the raw command. + * + * @return the message + */ + public String getMessage() { + return message; + } + + /** + * Get the sender of the notice. + * + * @return the nick of the notice sender + * @deprecated see {@link #getSenderNick()} instead + */ + public String getSender() { + return sender; + } + + /** + * Gets the nick of the sender + * + * @return the senders nick + */ + public String getSenderNick() { + return sender; + } + + /** + * Gets the target of the notice. + * + * @return the target of the notice. + */ + public Conversable getTarget() { + return Arrays.binarySearch(server.getChannelPrefix(), target.charAt(0)) >= 0 ? server.getChannel(target) : server + .getUser(target.toLowerCase()); + } + + /** + * Gets the channel the notice was sent to or from + * + * @return the channel the notice was sent to or from + * @deprecated see {@link #getTarget()} instead + */ + public String getChannel() { + return target; + } + + /** + * Gets the server this notice was sent on. + * + * @return the server this notice was sent on. + */ + public Server getServer() { + return server; + } +} diff --git a/api/com/speed/irc/types/ParsingException.java b/api/com/speed/irc/types/ParsingException.java new file mode 100644 index 0000000..1ddbd92 --- /dev/null +++ b/api/com/speed/irc/types/ParsingException.java @@ -0,0 +1,58 @@ +package com.speed.irc.types; + +/** + * Represents an exception being thrown while parsing. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ParsingException extends Exception { + + private static final long serialVersionUID = 2238835287734082797L; + private final String msg; + private final Exception e; + + /** + * Initialises a ParsingException. + * + * @param msg the message + * @param e the exception + */ + public ParsingException(final String msg, final Exception e) { + this.msg = msg; + this.e = e; + + } + + public void printStackTrace() { + e.printStackTrace(); + } + + public String getMessage() { + return msg; + } + + /** + * Gets the exception + * + * @return the exception. + */ + public Exception getException() { + return e; + } + +} diff --git a/api/com/speed/irc/types/Privmsg.java b/api/com/speed/irc/types/Privmsg.java new file mode 100644 index 0000000..f07945f --- /dev/null +++ b/api/com/speed/irc/types/Privmsg.java @@ -0,0 +1,98 @@ +package com.speed.irc.types; + +import java.util.Arrays; + +/** + * A wrapper class for PRIVMSGs. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class Privmsg { + + private final String message, sender; + private Conversable conversable; + + /** + * @param message The actual message. + * @param sender The nick of the person who the message was sent to/from. + * @param conversable The channel the message was sent to/from. + */ + public Privmsg(final String message, final String sender, + final Conversable conversable) { + this.message = message; + this.conversable = conversable; + this.sender = sender; + } + + + /* + * Gets the message sent + * + * @return the message + */ + public String getMessage() { + return message; + } + + /** + * Gets the sender + * + * @return the sender + */ + public String getSender() { + return sender; + } + + /** + * Gets the conversable object of the sender/channel + * + * @return the conversable object + */ + public Conversable getConversable() { + return conversable; + } + + /** + * Checks whether the message is a private message + * + * @return true if the message was sent privately, false otherwise + */ + public boolean isPrivateMessage() { + return !isChannelMessage(); + } + + /** + * Checks whether the message is a channel message + * + * @return true if the message was sent to a channel, + * false otherwise + */ + public boolean isChannelMessage() { + return Arrays.binarySearch(getConversable().getServer().getChannelPrefix(), getConversable().getName().charAt(0)) >= 0; + } + + /** + * Check if the message is a CTCP request/reply + * + * @return true if the message was a CTCP request/reply + */ + public boolean isCtcpMessage() { + return message.startsWith("\u0001"); + } + +} diff --git a/api/com/speed/irc/types/RawMessage.java b/api/com/speed/irc/types/RawMessage.java new file mode 100755 index 0000000..64dff17 --- /dev/null +++ b/api/com/speed/irc/types/RawMessage.java @@ -0,0 +1,92 @@ +package com.speed.irc.types; + +import com.speed.irc.connection.Server; + +/** + * Represents a raw message. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class RawMessage { + + private String raw, code, sender, target; + private Server server; + + /** + * Initialises a wrapper for raw messages. + * + * @param raw the raw message + * @param server the server the raw message was sent from + */ + public RawMessage(String raw, final Server server) { + this.raw = raw; + this.server = server; + String[] strings = raw.split(" "); + code = strings[1]; + sender = strings[0]; + if (strings.length > 2) + target = strings[2]; + + } + + /** + * Gets the raw message. + * + * @return the raw message. + */ + public String getRaw() { + return raw; + } + + /** + * Gets the command/code of this raw message. + * + * @return the command or code of this raw message. + */ + public String getCommand() { + return code; + } + + /** + * Gets the target of this raw message. + * + * @return the target of the message. + */ + public String getTarget() { + return target; + } + + /** + * Gets the sender of the message + * + * @return the sender of the message, in the form *!*@* + */ + public String getSender() { + return sender; + } + + /** + * Gets the server the raw message was sent on. + * + * @return the server the raw message was sent on. + */ + public Server getServer() { + return server; + } + +} diff --git a/api/com/speed/irc/types/ServerUser.java b/api/com/speed/irc/types/ServerUser.java new file mode 100644 index 0000000..5556c7a --- /dev/null +++ b/api/com/speed/irc/types/ServerUser.java @@ -0,0 +1,195 @@ +package com.speed.irc.types; + +import com.speed.irc.connection.Server; + +/** + * A representation of a user an a server. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ServerUser extends Conversable { + protected String nick, host, user; + private Server server; + private boolean identified, away, oper; + private String realName; + + /** + * Initialises a server user. + * + * @param nick the nick of the user + * @param host the host of the user + * @param user the username of the user + * @param server the server the user is on + */ + public ServerUser(final String nick, final String host, final String user, + final Server server) { + this.nick = nick; + this.host = host; + this.user = user; + this.server = server; + getServer().addUser(this); + } + + public String toString() { + return String.format("%s!%s@%s", nick, user, host); + } + + /** + * Gets the mask of this user. + * + * @return the mask of the user + */ + public Mask getMask() { + return new Mask(getNick(), + getUser() == null || getUser().isEmpty() ? "*" : getUser(), + getHost() == null || getHost().isEmpty() ? "*" : getHost()); + } + + public void sendMessage(final String message) { + server.sendRaw(String.format("PRIVMSG %s :%s", nick, message)); + } + + public void sendNotice(final String notice) { + server.sendNotice(new Notice(notice, null, nick, server)); + } + + public String getName() { + return nick; + } + + /** + * Gets the nick of this user. + * + * @return the nick of the user + */ + public String getNick() { + return nick; + } + + /** + * Gets the host of the user. + * + * @return the users host. + */ + public String getHost() { + return host; + } + + /** + * Gets the username of this user. + * + * @return the username of this user + */ + public String getUser() { + return user; + } + + /** + * Gets the server this user is on + * + * @return the server this user is on + */ + public Server getServer() { + return server; + } + + /** + * Returns whether the user is identified. Some servers will not send this + * mode for users that are. + * + * @return whether the user is identified. + */ + public boolean isIdentified() { + return identified; + } + + /** + * Sets whether the user is identified. + * + * @param identified returns true if they are identified, false otherwise. + */ + public void setIdentified(boolean identified) { + this.identified = identified; + } + + /** + * Returns whether the user is away. + * + * @return whether the user is away. + */ + public boolean isAway() { + return away; + } + + /** + * Sets whether the user is away. + * + * @param away returns true if they are away, false otherwise. + */ + public void setAway(boolean away) { + this.away = away; + } + + /** + * Returns whether the user is a server operator. + * + * @return whether the user is a server operator. + */ + public boolean isOper() { + return oper; + } + + /** + * Sets whether the user is a server operator. + * + * @param oper returns true if they are an operator, false otherwise. + */ + public void setOper(boolean oper) { + this.oper = oper; + } + + public void setRealName(String realName) { + this.realName = realName; + } + + public String getRealName() { + return realName; + } + + public boolean equals(final Object o) { + if (!(o instanceof ServerUser)) + return false; + else { + ServerUser other = (ServerUser) o; + + return other != null && other.getNick().equalsIgnoreCase(nick); + } + } + + @Override + public int hashCode() { + return (getNick().hashCode() | getHost().hashCode() | getUser() + .hashCode()) & 0xfffffff; + } + + public void requestWhois() { + getServer().sendRaw("WHOIS " + getName()); + getServer().addWhoisWaiting(this); + } + +} diff --git a/api/com/speed/irc/types/Whois.java b/api/com/speed/irc/types/Whois.java new file mode 100644 index 0000000..be7fdb3 --- /dev/null +++ b/api/com/speed/irc/types/Whois.java @@ -0,0 +1,96 @@ +package com.speed.irc.types; + +import com.speed.irc.connection.Server; +import com.speed.irc.util.Numerics; + +import java.util.Collection; +import java.util.Collections; + +/** + * Represents a collection of WHOIS replies. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class Whois { + private Collection whois; + private Channel[] channels; + private ServerUser user; + private Server server; + + public Whois(final Collection whois, final Server server) { + this.whois = whois; + this.server = server; + parse(); + + } + + public ServerUser getUser() { + return user; + } + + public Channel[] getChannels() { + return channels; + } + + public Server getServer() { + return server; + } + + private void parse() { + for (RawMessage m : whois) { + if (user == null) { + user = server.getUser(m.getRaw().split(" ")[3]); + } + if (m.getCommand().equals(Numerics.WHOIS_CHANNELS)) { + String[] channels = m.getRaw().split(" :", 2)[1].split(" "); + this.channels = new Channel[channels.length]; + for (int i = 0; i < channels.length; i++) { + String name = channels[i]; + String mode = ""; + if (name.charAt(0) != '#') { + mode += name.charAt(0); + name = name.substring(1); + } + Channel c = new Channel(name, server); + if (c.getUser(user.getNick()) == null) { + c.addChannelUser(new ChannelUser(user.getNick(), mode, + user.getUser(), user.getHost(), c)); + } else { + ChannelUser cu = c.getUser(user.getNick()); + cu.addMode(mode.charAt(0)); + } + this.channels[i] = c; + } + } else if (m.getCommand().equals(Numerics.WHOIS_NAME)) { + String msg = m.getRaw(); + String[] parts = msg.split(" "); + String nick = parts[3]; + String user = parts[4]; + String host = parts[5]; + String realName = msg.split(" :", 2)[1]; + this.user = new ServerUser(nick, host, user, server); + this.user.setRealName(realName); + } + } + } + + public Collection getMessages() { + return Collections.unmodifiableCollection(whois); + } + +} diff --git a/api/com/speed/irc/util/ControlCodeFormatter.java b/api/com/speed/irc/util/ControlCodeFormatter.java new file mode 100644 index 0000000..8f60a6c --- /dev/null +++ b/api/com/speed/irc/util/ControlCodeFormatter.java @@ -0,0 +1,173 @@ +package com.speed.irc.util; + +import java.awt.*; + +/** + * Formats messages with control codes, using a specified 'format' character. + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public class ControlCodeFormatter { + public static final char UNICODE_COLOUR = '\u0003'; + public static final char UNICODE_BOLD = '\u0002'; + public static final char UNICODE_UNDERLINE = '\u001F'; + + private static char format_character = '$'; + + private char formatChar; + + public ControlCodeFormatter() { + formatChar = '$'; + } + + public ControlCodeFormatter(final char format_char) { + formatChar = format_char; + } + + public enum Colour { + WHITE, BLACK, NAVY_BLUE, GREEN, RED, CRIMSON_RED, MAGENTA, BROWN, YELLOW, LIME, TEAL, AQUA, ROYAL_BLUE, PINK, DARK_GREY, LIGHT_GREY; + public static final Color[] COLORS = new Color[]{Color.WHITE, + Color.BLACK, new Color(0x000080), Color.GREEN, Color.RED, + new Color(0xE8000D), Color.MAGENTA, new Color(0x8b4513), + Color.YELLOW, new Color(0x32cd32), new Color(0x008080), + new Color(0x00FFFF), new Color(0x4169e1), Color.PINK, + Color.DARK_GRAY, Color.LIGHT_GRAY}; + } + + /** + * Sets the default character to be replaced with colour control code in + * {@link #format(String, Colour...)} + * + * @param c the new format character + */ + public void setFormatChar(final char c) { + formatChar = c; + } + + /** + * Gets the default character to be replaced with colour control code in + * {@link #format(String, Colour...)} + * + * @return the format character + */ + public char getFormatChar() { + return formatChar; + } + + /** + * Sets the default character to be replaced with colour control code in + * {@link #format(String, Colour...)} + * + * @param c the new format character + * @deprecated Use the instance instead {@link #setFormatChar(char)} + */ + public static void setFormatCharacter(final char c) { + format_character = c; + } + + /** + * Gets the default character to be replaced with colour control code in + * {@link #format(String, Colour...)} + * + * @return the format character + * @deprecated Use the instance instead {@link #getFormatChar()} + */ + public static char getFormatCharacter() { + return format_character; + } + + /** + * Formats the string with the colours specified. Default format character + * is '$' and any format character is escaped using '\'. + * + * @param s The string to be formatted. + * @param colours The colours to format the string with. + * @return the formatted string + */ + public String formatString(final String s, final Colour... colours) { + final StringBuilder builder = new StringBuilder(); + if (colours.length == 0) + return s; + int replaced = 0; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (replaced >= colours.length) { + if (c == '\\' && s.charAt(i + 1) == formatChar) { + builder.append(formatChar); + i++; + } else { + builder.append(c); + } + continue; + } else if (c == formatChar) { + if (i != 0 && s.charAt(i - 1) == '\\') { + builder.deleteCharAt(builder.lastIndexOf("\\")); + builder.append(c); + continue; + } + builder.append(UNICODE_COLOUR).append(colours[replaced++].ordinal()); + + } else { + builder.append(c); + } + } + return builder.toString() + ControlCodeFormatter.UNICODE_COLOUR; + } + + /** + * Formats the string with the colours specified. Default format character + * is '$' and any format character is escaped using '\'. + *

+ * Will be retained for fast formatting using the default char $ + * + * @param s The string to be formatted. + * @param colours The colours to format the string with. + * @return the formatted string + */ + public static String format(final String s, final Colour... colours) { + final StringBuilder builder = new StringBuilder(); + if (colours.length == 0) + return s; + int replaced = 0; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (replaced >= colours.length) { + if (c == '\\' && s.charAt(i + 1) == format_character) { + builder.append(format_character); + i++; + } else { + builder.append(c); + } + continue; + } else if (c == format_character) { + if (i != 0) { + if (s.charAt(i - 1) == '\\') { + builder.deleteCharAt(builder.lastIndexOf("\\")); + builder.append(c); + continue; + } + } + builder.append(UNICODE_COLOUR).append(colours[replaced++].ordinal()); + + } else { + builder.append(c); + } + } + return builder.toString() + ControlCodeFormatter.UNICODE_COLOUR; + } +} diff --git a/api/com/speed/irc/util/Numerics.java b/api/com/speed/irc/util/Numerics.java new file mode 100755 index 0000000..ffe2300 --- /dev/null +++ b/api/com/speed/irc/util/Numerics.java @@ -0,0 +1,42 @@ +package com.speed.irc.util; + +/** + * Stores IRC numerics used by the API internal classes. Numerics are stored as + * strings to allow easy comparison. (numerics are parsed as strings) + *

+ * This file is part of Speed's IRC API. + *

+ * Speed's IRC API is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Speed's IRC API is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with Speed's IRC API. If not, see . + * + * @author Shivam Mistry + */ +public interface Numerics { + String WHO_RESPONSE = "352"; + String WHO_END = "315"; + String CHANNEL_NAMES = "353"; + String CHANNEL_TOPIC = "332", CHANNEL_TOPIC_SET = "333"; + String CHANNEL_NAMES_END = "366"; + String SERVER_SUPPORT = "005"; + String NOT_AN_OPERATOR = "482"; + String CHANNEL_MODES = "324"; + String CHANNEL_IS_FULL = "471", INVITE_ONLY_CHANNEL = "473", + BANNED_FROM_CHANNEL = "474", BAD_CHANNEL_KEY = "475", + BAD_CHANNEL_MASK = "476"; + // whois numerics + String WHOIS_NAME = "311", WHOIS_CHANNELS = "319", WHOIS_SERVER = "312", + WHOIS_OPERATOR = "313", WHOIS_IDLE = "317"; + String WHOIS_END = "318"; + String[] WHOIS = new String[]{WHOIS_NAME, WHOIS_CHANNELS, WHOIS_SERVER, + WHOIS_OPERATOR, WHOIS_IDLE, WHOIS_END}; +} diff --git a/pom.xml b/pom.xml index c262fc1..22629ca 100644 --- a/pom.xml +++ b/pom.xml @@ -84,6 +84,25 @@ + + org.codehaus.mojo + build-helper-maven-plugin + 1.7 + + + add-source + generate-sources + + add-source + + + + api + + + + + org.apache.maven.plugins maven-dependency-plugin diff --git a/run.sh b/run.sh index d9e05d9..17b7815 100755 --- a/run.sh +++ b/run.sh @@ -8,5 +8,6 @@ git pull >> git.log mvn clean package nohup java -cp `cat target/classpath.cp`:target/FreeVoteBot-1.0.0.jar org.freecode.irc.votebot.BootStrap > /dev/null 2>&1 & #nohup java -cp `cat target/classpath.cp`:target/FreeVoteBot-1.0.0.jar org.freecode.irc.votebot.BootStrap & +#java -cp `cat target/classpath.cp`:target/FreeVoteBot-1.0.0.jar org.freecode.irc.votebot.BootStrap pid=$! echo $pid > freevotepid diff --git a/src/main/java/org/freecode/irc/CtcpRequest.java b/src/main/java/org/freecode/irc/CtcpRequest.java deleted file mode 100644 index d9a9ebf..0000000 --- a/src/main/java/org/freecode/irc/CtcpRequest.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.freecode.irc; - -/** - * User: Shivam - * Date: 25/07/13 - * Time: 14:23 - */ -public class CtcpRequest extends Privmsg { - public static final char CTCP = '\u0001'; - private final String command; - private final String arguments; - - public CtcpRequest(String rawLine, IrcConnection connection) { - super(rawLine, connection); - String message = getMessage(); - if (message.charAt(0) == CTCP && message.charAt(message.length() - 1) == CTCP) { - message = message.replace(String.valueOf(CTCP), "").trim(); - String[] sstr = message.split(" ", 2); - if (sstr.length > 0) { - command = sstr[0]; - arguments = sstr.length > 1 ? sstr[1] : null; - } else { - throw new IllegalArgumentException("Not a valid CTCP request"); - } - } else { - throw new IllegalArgumentException("Not a valid CTCP request"); - } - } - - public CtcpRequest(IrcConnection connection, String target, String command, String arguments) { - super(target, CTCP + command + " " + arguments + CTCP, connection); - this.command = command; - this.arguments = arguments; - } - - public String getCommand() { - return command; - } - - public String getArguments() { - return arguments; - } - - public static boolean isCtcpRequest(final String raw) { - String[] parts = raw.split(" ", 4); - if (parts.length == 4 && parts[1].equalsIgnoreCase("PRIVMSG")) { - String msg = parts[3]; - if (msg.startsWith(":")) { - msg = msg.substring(1); - } - return msg.charAt(0) == CTCP && msg.charAt(msg.length() - 1) == CTCP; - } - return false; - } -} diff --git a/src/main/java/org/freecode/irc/CtcpResponse.java b/src/main/java/org/freecode/irc/CtcpResponse.java deleted file mode 100644 index 98bc446..0000000 --- a/src/main/java/org/freecode/irc/CtcpResponse.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.freecode.irc; - -import static org.freecode.irc.CtcpRequest.CTCP; - -/** - * User: Shivam - * Date: 28/07/13 - * Time: 21:48 - */ -public class CtcpResponse extends Notice { - - private final String command; - private final String response; - - public CtcpResponse(String rawLine, IrcConnection connection) { - super(rawLine, connection); - String message = getMessage(); - if (message.charAt(0) == CTCP && message.charAt(message.length() - 1) == CTCP) { - message = message.replace(String.valueOf(CTCP), "").trim(); - String[] sstr = message.split(" ", 2); - if (sstr.length > 0) { - command = sstr[0]; - response = sstr.length > 1 ? sstr[1] : null; - } else { - throw new IllegalArgumentException("Not a valid CTCP response"); - } - } else { - throw new IllegalArgumentException("Not a valid CTCP response"); - } - } - - public CtcpResponse(IrcConnection connection, final String target, final String command, final String response) { - super(target, CTCP + command + " " + response + CTCP, connection); - this.command = command; - this.response = response; - } - public String getCommand() { - return command; - } - - public String getResponse() { - return response; - } - - - public static boolean isCtcpResponse(final String raw) { - String[] parts = raw.split(" ", 4); - if (parts.length == 4 && parts[1].equalsIgnoreCase("NOTICE")) { - String msg = parts[3]; - if (msg.startsWith(":")) { - msg = msg.substring(1); - } - return msg.charAt(0) == CTCP && msg.charAt(msg.length() - 1) == CTCP; - } - return false; - } -} diff --git a/src/main/java/org/freecode/irc/IrcConnection.java b/src/main/java/org/freecode/irc/IrcConnection.java deleted file mode 100644 index c1ec022..0000000 --- a/src/main/java/org/freecode/irc/IrcConnection.java +++ /dev/null @@ -1,172 +0,0 @@ -package org.freecode.irc; - -import org.freecode.irc.event.internal.*; - -import java.io.*; -import java.net.Socket; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.*; - -/** - * User: Shivam - * Date: 16/06/13 - * Time: 22:30 - */ -public class IrcConnection implements Runnable { - - private BufferedReader reader; - private BufferedWriter writer; - private Socket socket; - private String host; - private int port; - private volatile List listeners; - private volatile List delegateListeners; - private ScheduledExecutorService executor; - private Future readerFuture; - public static final int ERR_NICKNAMEINUSE = 433; - private ConcurrentLinkedQueue rawLines = new ConcurrentLinkedQueue<>(); - private final ScheduledFuture writerFuture; - - public IrcConnection(final String host, final int port) throws IOException { - this.host = host; - this.port = port; - this.socket = new Socket(host, port); - reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); - writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); - listeners = new LinkedList<>(); - delegateListeners = new LinkedList<>(); - executor = Executors.newScheduledThreadPool(2); - addListener(new RawPrivateMessageProcessor(this)); - addListener(new RawNoticeProcessor(this)); - addListener(new RawJoinProcessor(this)); - readerFuture = executor.scheduleAtFixedRate(this, 100L, 100L, TimeUnit.MILLISECONDS); - writerFuture = executor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - if (socket.isOutputShutdown()) { - writerFuture.cancel(true); - return; - } - if (!rawLines.isEmpty()) { - String s = rawLines.poll(); - System.out.println("Out: " + s); - try { - writer.write(s); - writer.newLine(); - writer.flush(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - } - }, 100L, 100L, TimeUnit.MILLISECONDS); - } - - public void joinChannel(String channel) { - try { - sendRaw("JOIN :" + channel); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void addListener(final DelegateListener listener) { - delegateListeners.add(listener); - } - - public void removeListener(final DelegateListener listener) { - delegateListeners.remove(listener); - } - - - public void addListener(final RawIrcListener listener) { - listeners.add(listener); - } - - public void removeListener(final RawIrcListener listener) { - listeners.remove(listener); - } - - public void register(final String nick, final String user, final String realName) throws IOException { - sendRaw("NICK " + nick); - sendRaw("USER " + user + " 0 * :" + realName); - } - - public List getDelegates(Class type) { - List list = new LinkedList<>(); - for (DelegateListener l : delegateListeners) { - if (type.isAssignableFrom(l.getClass())) { - list.add(type.cast(l)); - } - } - return list; - } - - public void sendMessage(String target, String message) { - try { - sendRaw(String.format("PRIVMSG %s :%s", target, message)); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void sendRaw(String s) throws IOException { - if (s.endsWith("\n")) { - s = s.replaceAll("[\n\r]", ""); - } - if (!socket.isOutputShutdown()) { - rawLines.offer(s); - } - } - - - public void run() { - if (socket.isInputShutdown()) { - readerFuture.cancel(true); - } else { - - try { - String raw = reader.readLine(); - System.out.println(raw); - if (!Character.isLetterOrDigit(raw.charAt(0))) { - raw = raw.substring(1); - } - if (raw.startsWith("PING ")) { - sendRaw(raw.replaceFirst("PING", "PONG")); - } else { - for (RawIrcListener listener : listeners) { - if (listener.qualifies(raw)) { - listener.execute(raw); - } - } - } - - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - - public void send(final Transmittable transmittable) { - try { - sendRaw(transmittable.getRaw()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void sendNotice(String target, String message) { - try { - sendRaw(String.format("NOTICE %s :%s", target, message)); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public BufferedWriter getWriter() { - return writer; - } -} diff --git a/src/main/java/org/freecode/irc/Notice.java b/src/main/java/org/freecode/irc/Notice.java deleted file mode 100644 index cf860aa..0000000 --- a/src/main/java/org/freecode/irc/Notice.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.freecode.irc; - -/** - * User: Shivam - * Date: 28/07/13 - * Time: 21:42 - */ -public class Notice extends Transmittable { - - private final String target; - private final String message; - private final String senderMask; - private final String user; - private final String nick; - private final String host; - private final IrcConnection connection; - - public Notice(String rawLine, IrcConnection connection) { - this.connection = connection; - final String[] parts = rawLine.split(" ", 4); - senderMask = parts[0]; - if(senderMask.contains("!")) { - nick = senderMask.substring(0, senderMask.indexOf('!')); - user = senderMask.substring(senderMask.indexOf('!') + 1, senderMask.indexOf('@')); - host = senderMask.substring(senderMask.indexOf('@') + 1); - } else { - nick = senderMask; - user = null; - host = null; - } - message = parts[3].substring(1); - target = parts[2]; - } - - public Notice(final String target, final String message, final IrcConnection connection) { - this.connection = connection; - this.message = message; - this.target = target; - this.senderMask = null; - this.user = null; - this.nick = null; - this.host = null; - } - public String getTarget() { - return target; - } - - public String getMessage() { - return message; - } - - public String getSenderMask() { - return senderMask; - } - - public String getUser() { - return user; - } - - public String getNick() { - return nick; - } - - public String getHost() { - return host; - } - - public IrcConnection getIrcConnection() { - return connection; - } - - public String getRaw() { - return String.format("NOTICE %s :%s", target, message); - } - - public String getCommand() { - return "NOTICE"; - } -} diff --git a/src/main/java/org/freecode/irc/Privmsg.java b/src/main/java/org/freecode/irc/Privmsg.java deleted file mode 100644 index 0fe5fca..0000000 --- a/src/main/java/org/freecode/irc/Privmsg.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.freecode.irc; - -/** - * User: Shivam - * Date: 17/06/13 - * Time: 00:48 - */ -public class Privmsg extends Transmittable { - private final String target; - private final String message; - private final String senderMask; - private final String user; - private final String nick; - private final String host; - private final IrcConnection connection; - - public Privmsg(final String rawLine, final IrcConnection connection) { - this.connection = connection; - final String[] parts = rawLine.split(" ", 4); - senderMask = parts[0]; - if(senderMask.contains("!")) { - nick = senderMask.substring(0, senderMask.indexOf('!')); - user = senderMask.substring(senderMask.indexOf('!') + 1, senderMask.indexOf('@')); - host = senderMask.substring(senderMask.indexOf('@') + 1); - } else { - nick = senderMask; - user = null; - host = null; - } - message = parts[3].substring(1); - target = parts[2]; - } - - public Privmsg(final String target, final String message, final IrcConnection connection) { - this.connection = connection; - this.message = message; - this.target = target; - this.senderMask = null; - this.user = null; - this.nick = null; - this.host = null; - } - - public String getTarget() { - return target; - } - - public String getMessage() { - return message; - } - - public String getSenderMask() { - return senderMask; - } - - public String getUser() { - return user; - } - - public String getNick() { - return nick; - } - - public String getHost() { - return host; - } - - public IrcConnection getIrcConnection() { - return connection; - } - - public String getRaw() { - return String.format("PRIVMSG %s :%s", target, message); - } - - public String getCommand() { - return "PRIVMSG"; - } - - public void send(String msg) { - String target1 = getTarget(); - if(Character.isLetter(target1.charAt(0))) { - target1 = getNick(); - } - getIrcConnection().send(new Privmsg(target1, msg, connection)); - } -} diff --git a/src/main/java/org/freecode/irc/Transmittable.java b/src/main/java/org/freecode/irc/Transmittable.java deleted file mode 100644 index 222b652..0000000 --- a/src/main/java/org/freecode/irc/Transmittable.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.freecode.irc; - -/** - * User: Shivam - * Date: 28/07/13 - * Time: 21:40 - */ -public abstract class Transmittable { - public abstract String getRaw(); - public abstract String getCommand(); - public boolean isNotice(){ - return this instanceof Notice; - } - - public boolean isPrivmsg() { - return this instanceof Privmsg; - } - - public Privmsg asPrivmsg() { - return isPrivmsg() ? (Privmsg) this : null; - } - - public Notice asNotice() { - return isNotice() ? (Notice) this : null; - } - -} diff --git a/src/main/java/org/freecode/irc/event/CtcpRequestListener.java b/src/main/java/org/freecode/irc/event/CtcpRequestListener.java deleted file mode 100644 index 038cc67..0000000 --- a/src/main/java/org/freecode/irc/event/CtcpRequestListener.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.freecode.irc.event; - -import org.freecode.irc.CtcpRequest; -import org.freecode.irc.event.internal.DelegateListener; - -/** - * User: Shivam - * Date: 28/07/13 - * Time: 20:44 - */ -public interface CtcpRequestListener extends DelegateListener { - - public void onCtcpRequest(CtcpRequest request); -} diff --git a/src/main/java/org/freecode/irc/event/CtcpResponseListener.java b/src/main/java/org/freecode/irc/event/CtcpResponseListener.java deleted file mode 100644 index 3113053..0000000 --- a/src/main/java/org/freecode/irc/event/CtcpResponseListener.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.freecode.irc.event; - -import org.freecode.irc.CtcpResponse; -import org.freecode.irc.event.internal.DelegateListener; - -/** - * User: Shivam - * Date: 29/07/13 - * Time: 15:57 - */ -public interface CtcpResponseListener extends DelegateListener { - public void onCtcpResponse(CtcpResponse response); -} diff --git a/src/main/java/org/freecode/irc/event/JoinListener.java b/src/main/java/org/freecode/irc/event/JoinListener.java deleted file mode 100644 index ddafa99..0000000 --- a/src/main/java/org/freecode/irc/event/JoinListener.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.freecode.irc.event; - -import org.freecode.irc.event.internal.DelegateListener; - -/** - * Created by shivam on 26/04/14. - */ -public interface JoinListener extends DelegateListener { - - public void onJoin(String channel, String nick, String mask); -} diff --git a/src/main/java/org/freecode/irc/event/NoticeListener.java b/src/main/java/org/freecode/irc/event/NoticeListener.java deleted file mode 100644 index f521f20..0000000 --- a/src/main/java/org/freecode/irc/event/NoticeListener.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.freecode.irc.event; - -import org.freecode.irc.Notice; -import org.freecode.irc.event.internal.DelegateListener; - -/** - * User: Shivam - * Date: 29/07/13 - * Time: 15:56 - */ -public interface NoticeListener extends DelegateListener { - public void onNotice(Notice n); -} diff --git a/src/main/java/org/freecode/irc/event/NumericListener.java b/src/main/java/org/freecode/irc/event/NumericListener.java deleted file mode 100644 index 5b3643c..0000000 --- a/src/main/java/org/freecode/irc/event/NumericListener.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.freecode.irc.event; - -import org.freecode.irc.IrcConnection; -import org.freecode.irc.event.internal.RawIrcListener; - -/** - * User: Shivam - * Date: 16/06/13 - * Time: 23:12 - */ -public abstract class NumericListener extends RawIrcListener { - public NumericListener(IrcConnection connection) { - super(connection); - } - - public abstract int getNumeric(); - - @Override - public boolean qualifies(final String raw) { - String[] parts = raw.split(" "); - return parts.length > 2 && parts[1].matches("\\d+") && Integer.parseInt(parts[1]) == getNumeric(); - } -} diff --git a/src/main/java/org/freecode/irc/event/PrivateMessageListener.java b/src/main/java/org/freecode/irc/event/PrivateMessageListener.java deleted file mode 100644 index 352f9dd..0000000 --- a/src/main/java/org/freecode/irc/event/PrivateMessageListener.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.freecode.irc.event; - -import org.freecode.irc.Privmsg; -import org.freecode.irc.event.internal.DelegateListener; - -/** - * User: Shivam - * Date: 17/06/13 - * Time: 01:02 - */ -public interface PrivateMessageListener extends DelegateListener { - public void onPrivmsg(Privmsg privmsg); -} diff --git a/src/main/java/org/freecode/irc/event/internal/DelegateListener.java b/src/main/java/org/freecode/irc/event/internal/DelegateListener.java deleted file mode 100644 index eea0747..0000000 --- a/src/main/java/org/freecode/irc/event/internal/DelegateListener.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.freecode.irc.event.internal; - -/** - * User: Shivam - * Date: 17/06/13 - * Time: 00:55 - */ -public interface DelegateListener { -} diff --git a/src/main/java/org/freecode/irc/event/internal/RawIrcListener.java b/src/main/java/org/freecode/irc/event/internal/RawIrcListener.java deleted file mode 100644 index 835f2c3..0000000 --- a/src/main/java/org/freecode/irc/event/internal/RawIrcListener.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.freecode.irc.event.internal; - -import org.freecode.irc.IrcConnection; - -/** - * User: Shivam - * Date: 16/06/13 - * Time: 23:09 - */ -public abstract class RawIrcListener { - - protected IrcConnection connection; - - public RawIrcListener(IrcConnection connection) { - this.connection = connection; - } - - public abstract boolean qualifies(final String rawLine); - - public abstract void execute(final String rawLine); -} diff --git a/src/main/java/org/freecode/irc/event/internal/RawJoinProcessor.java b/src/main/java/org/freecode/irc/event/internal/RawJoinProcessor.java deleted file mode 100644 index 183c546..0000000 --- a/src/main/java/org/freecode/irc/event/internal/RawJoinProcessor.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.freecode.irc.event.internal; - -import org.freecode.irc.IrcConnection; -import org.freecode.irc.event.JoinListener; - -/** - * Created by shivam on 26/04/14. - */ -public class RawJoinProcessor extends RawIrcListener { - - public RawJoinProcessor(IrcConnection connection) { - super(connection); - } - - public boolean qualifies(String rawLine) { - String[] parts = rawLine.split(" ", 3); - return parts.length == 3 && parts[1].equalsIgnoreCase("join"); - } - - public void execute(String rawLine) { - String[] parts = rawLine.split(" ", 3); - String mask = parts[0]; - String channel = parts[2].startsWith(":") ? parts[2].substring(1) : - parts[2]; - String nick = mask.contains("!") ? mask.split("!")[0] : mask; - for (JoinListener listener : connection.getDelegates(JoinListener.class)) { - listener.onJoin(channel, nick, mask); - } - - } -} diff --git a/src/main/java/org/freecode/irc/event/internal/RawLineProcessor.java b/src/main/java/org/freecode/irc/event/internal/RawLineProcessor.java deleted file mode 100644 index c1be75a..0000000 --- a/src/main/java/org/freecode/irc/event/internal/RawLineProcessor.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.freecode.irc.event.internal; - -import org.freecode.irc.IrcConnection; - -/** - * User: Shivam - * Date: 17/06/13 - * Time: 00:53 - */ -public abstract class RawLineProcessor extends RawIrcListener { - - public RawLineProcessor(IrcConnection connection) { - super(connection); - } -} diff --git a/src/main/java/org/freecode/irc/event/internal/RawNoticeProcessor.java b/src/main/java/org/freecode/irc/event/internal/RawNoticeProcessor.java deleted file mode 100644 index 6fecbf9..0000000 --- a/src/main/java/org/freecode/irc/event/internal/RawNoticeProcessor.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.freecode.irc.event.internal; - -import org.freecode.irc.CtcpResponse; -import org.freecode.irc.IrcConnection; -import org.freecode.irc.Notice; -import org.freecode.irc.event.CtcpResponseListener; -import org.freecode.irc.event.NoticeListener; - -/** - * User: Shivam - * Date: 29/07/13 - * Time: 15:51 - */ -public class RawNoticeProcessor extends RawLineProcessor { - - public RawNoticeProcessor(IrcConnection connection) { - super(connection); - } - - public boolean qualifies(String rawLine) { - final String[] parts = rawLine.split(" ", 4); - return parts.length == 4 && parts[1].equals("NOTICE"); - } - - public void execute(String rawLine) { - if (CtcpResponse.isCtcpResponse(rawLine)) { - CtcpResponse ctcpResponse = new CtcpResponse(rawLine, connection); - for (CtcpResponseListener listener : connection.getDelegates(CtcpResponseListener.class)) { - listener.onCtcpResponse(ctcpResponse); - } - } else { - Notice n = new Notice(rawLine, connection); - for (NoticeListener listener : connection.getDelegates(NoticeListener.class)) { - listener.onNotice(n); - - } - - } - } -} diff --git a/src/main/java/org/freecode/irc/event/internal/RawPrivateMessageProcessor.java b/src/main/java/org/freecode/irc/event/internal/RawPrivateMessageProcessor.java deleted file mode 100644 index 429d86e..0000000 --- a/src/main/java/org/freecode/irc/event/internal/RawPrivateMessageProcessor.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.freecode.irc.event.internal; - -import org.freecode.irc.CtcpRequest; -import org.freecode.irc.IrcConnection; -import org.freecode.irc.Privmsg; -import org.freecode.irc.event.CtcpRequestListener; -import org.freecode.irc.event.PrivateMessageListener; - -/** - * User: Shivam - * Date: 16/06/13 - * Time: 23:57 - */ -public class RawPrivateMessageProcessor extends RawLineProcessor { - - - public RawPrivateMessageProcessor(IrcConnection connection) { - super(connection); - } - - public boolean qualifies(String rawLine) { - final String[] parts = rawLine.split(" ", 4); - return parts.length == 4 && parts[1].equals("PRIVMSG"); //&& !CtcpRequest.isCtcpRequest(rawLine); //&& parts[3].startsWith(":"); - } - - public void execute(String rawLine) { - if (!CtcpRequest.isCtcpRequest(rawLine)) { - final Privmsg privmsg = new Privmsg(rawLine, connection); - for (PrivateMessageListener listener : connection.getDelegates(PrivateMessageListener.class)) { - listener.onPrivmsg(privmsg); - } - } else { - final CtcpRequest request = new CtcpRequest(rawLine, connection); - for (CtcpRequestListener listener : connection.getDelegates(CtcpRequestListener.class)) { - listener.onCtcpRequest(request); - } - } - } -} diff --git a/src/main/java/org/freecode/irc/votebot/FreeVoteBot.java b/src/main/java/org/freecode/irc/votebot/FreeVoteBot.java index f8bccab..95612ec 100644 --- a/src/main/java/org/freecode/irc/votebot/FreeVoteBot.java +++ b/src/main/java/org/freecode/irc/votebot/FreeVoteBot.java @@ -1,13 +1,14 @@ package org.freecode.irc.votebot; -import org.freecode.irc.CtcpRequest; -import org.freecode.irc.CtcpResponse; -import org.freecode.irc.IrcConnection; -import org.freecode.irc.Privmsg; -import org.freecode.irc.event.CtcpRequestListener; -import org.freecode.irc.event.JoinListener; -import org.freecode.irc.event.NumericListener; -import org.freecode.irc.event.PrivateMessageListener; +import com.speed.irc.connection.Server; +import com.speed.irc.event.channel.ChannelUserEvent; +import com.speed.irc.event.channel.ChannelUserListener; +import com.speed.irc.event.channel.ModeChangedEvent; +import com.speed.irc.event.message.PrivateMessageEvent; +import com.speed.irc.event.message.PrivateMessageListener; +import com.speed.irc.event.message.RawMessageEvent; +import com.speed.irc.event.message.RawMessageListener; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.api.AdminModule; import org.freecode.irc.votebot.api.FVBModule; import org.freecode.irc.votebot.dao.PollDAO; @@ -31,14 +32,14 @@ * Date: 17/06/13 * Time: 00:05 */ -public class FreeVoteBot implements PrivateMessageListener, JoinListener { +public class FreeVoteBot implements PrivateMessageListener, ChannelUserListener { public static final String CHANNEL_SOURCE = "#freecode"; private String[] channels; private String nick, realName, serverHost, user; private int port; private ScriptModuleLoader sml; - private IrcConnection connection; + private Server connection; private String version; private ExpiryQueue expiryQueue = new ExpiryQueue<>(1500L); @@ -47,6 +48,7 @@ public class FreeVoteBot implements PrivateMessageListener, JoinListener { private VoteDAO voteDAO; public ScheduledExecutorService pollExecutor; public HashMap pollFutures; + public static final int ERR_NICKNAMEINUSE = 433; private KVStore kvStore; @@ -89,49 +91,31 @@ public void init() { } private void registerUser() { - try { - connection.register(nick, user, realName); - } catch (IOException e) { - e.printStackTrace(); - } - connection.addListener(this); + connection.register(nick, user, realName); + connection.getEventManager().addListener(this); } private void addNickInUseListener() { - NumericListener nickInUse = new NumericListener(connection) { - public int getNumeric() { - return IrcConnection.ERR_NICKNAMEINUSE; - } + RawMessageListener nickInUse = new RawMessageListener() { - public void execute(String rawLine) { - FreeVoteBot.this.nick = FreeVoteBot.this.nick + "_"; - try { - connection.sendRaw("NICK " + FreeVoteBot.this.nick); - } catch (IOException e) { - e.printStackTrace(); - } - } - }; - connection.addListener(nickInUse); + public void rawMessageReceived(RawMessageEvent e) { + if(e.getMessage().getCommand().equalsIgnoreCase(String.valueOf(ERR_NICKNAMEINUSE))) { + FreeVoteBot.this.nick = FreeVoteBot.this.nick + "_"; + connection.sendRaw("NICK " + FreeVoteBot.this.nick); + + } + } + }; + connection.getEventManager().addListener(nickInUse); } private void addCTCPRequestListener() { - connection.addListener(new CtcpRequestListener() { - public void onCtcpRequest(CtcpRequest request) { - if (request.getCommand().equals("VERSION")) { - request.getIrcConnection().send(new CtcpResponse(request.getIrcConnection(), - request.getNick(), "VERSION", "FreeVoteBot " + version + " by " + CHANNEL_SOURCE + " on irc.rizon.net")); - } else if (request.getCommand().equals("PING")) { - request.getIrcConnection().send(new CtcpResponse(request.getIrcConnection(), - request.getNick(), "PING", request.getArguments())); - } - } - }); + connection.setCtcpReply("VERSION", "FreeVoteBot " + version); } private void connectToIRCServer() { try { - connection = new IrcConnection(serverHost, port); + connection = new Server(serverHost, port, true); } catch (IOException e) { e.printStackTrace(); } @@ -144,7 +128,7 @@ private void identifyToNickServ() { BufferedReader read = new BufferedReader(new FileReader(pass)); String s = read.readLine(); if (s != null) { - connection.send(new Privmsg("NickServ", "identify " + s, connection)); + connection.sendMessage(new Privmsg("identify " + s, null, connection.getUser("NickServ"))); } read.close(); } catch (IOException e) { @@ -160,25 +144,7 @@ private void joinChannels() { } public void onPrivmsg(final Privmsg privmsg) { - if (privmsg.getNick().equalsIgnoreCase(nick)) { - return; - } - String sender = privmsg.getNick().toLowerCase(); - if (expiryQueue.contains(sender) || !expiryQueue.insert(sender)) { - return; - } - - for (FVBModule module : moduleList) { - try { - if (module.isEnabled() && module.canRun(privmsg)) { - module.process(privmsg); - return; - } - } catch (Exception e) { - privmsg.send(e.getMessage()); - } - } } @@ -252,7 +218,7 @@ public ScriptModuleLoader getScriptModuleLoader() { public void sendMsg(String s) { for (String channel : channels) { - connection.sendMessage(channel, s); + connection.sendMessage(new Privmsg(s,null, connection.getChannel(channel))); } } @@ -278,7 +244,88 @@ private DateFormat getDateFormatter() { return dateFormat; } - static class PollVotes implements Comparable { + @Override + public void messageReceived(PrivateMessageEvent e) { + Privmsg privmsg = e.getMessage(); + if (privmsg.getSender().equalsIgnoreCase(nick)) { + return; + } + + String sender = privmsg.getSender().toLowerCase(); + if (expiryQueue.contains(sender) || !expiryQueue.insert(sender)) { + return; + } + + for (FVBModule module : moduleList) { + try { + if (module.isEnabled() && module.canRun(privmsg)) { + module.process(privmsg); + return; + } + } catch (Exception e1) { + privmsg.getConversable().sendMessage(e1.getMessage()); + } + } + } + + public void channelUserJoined(ChannelUserEvent e) { + String nick = e.getUser().getNick(); + String channel = e.getChannel().getName(); + try { + Poll[] openPolls = pollDAO.getOpenPolls(); + Poll[] pollsNotVotedIn = voteDAO.getPollsNotVotedIn(openPolls, nick); + PollVotes[] pollVotes = new PollVotes[pollsNotVotedIn.length]; + for (int i = 0; i < pollsNotVotedIn.length; i++) { + Poll poll = pollsNotVotedIn[i]; + String question = poll.getQuestion(); + int id = poll.getId(); + long expiry = poll.getExpiry(); + Date date = new Date(expiry); + Vote[] votes = voteDAO.getVotesOnPoll(id); + String msg = String.format("Open poll #%d: \"%s\", ends: %s, votes: %d", id, question, getDateFormatter().format(date), votes.length); + pollVotes[i] = new PollVotes(votes.length, msg); + } + if (pollVotes.length == 0) { + e.getUser().sendNotice("No new polls to vote in!"); + } else { + Arrays.sort(pollVotes); + e.getUser().sendNotice("Trending polls list:"); + if (pollVotes.length >= 3) { + e.getUser().sendNotice(pollVotes[0].question); + e.getUser().sendNotice(pollVotes[1].question); + e.getUser().sendNotice(pollVotes[2].question); + } else { + for (PollVotes p : pollVotes) { + e.getUser().sendNotice(p.question); + } + } + } + } catch (SQLException e1) { + e1.printStackTrace(); + } + } + + public void channelUserParted(ChannelUserEvent e) { + + } + + public void channelUserModeChanged(ModeChangedEvent e) { + + } + + public void channelUserKicked(ChannelUserEvent e) { + + } + + public void channelUserNickChanged(ChannelUserEvent e) { + + } + + public void channelUserQuit(ChannelUserEvent e) { + + } + + static class PollVotes implements Comparable { int votes; String question; @@ -292,40 +339,7 @@ public int compareTo(PollVotes o) { } } - @Override public void onJoin(String channel, String nick, String mask) { - System.out.println(nick + " joins " + channel); - try { - Poll[] openPolls = pollDAO.getOpenPolls(); - Poll[] pollsNotVotedIn = voteDAO.getPollsNotVotedIn(openPolls, nick); - PollVotes[] pollVotes = new PollVotes[pollsNotVotedIn.length]; - for (int i = 0; i < pollsNotVotedIn.length; i++) { - Poll poll = pollsNotVotedIn[i]; - String question = poll.getQuestion(); - int id = poll.getId(); - long expiry = poll.getExpiry(); - Date date = new Date(expiry); - Vote[] votes = voteDAO.getVotesOnPoll(id); - String msg = String.format("Open poll #%d: \"%s\", ends: %s, votes: %d", id, question, getDateFormatter().format(date), votes.length); - pollVotes[i] = new PollVotes(votes.length, msg); - } - if (pollVotes.length == 0) { - connection.sendNotice(nick, "No new polls to vote in!"); - } else { - Arrays.sort(pollVotes); - connection.sendNotice(nick, "Trending polls list:"); - if (pollVotes.length >= 3) { - connection.sendNotice(nick, pollVotes[0].question); - connection.sendNotice(nick, pollVotes[1].question); - connection.sendNotice(nick, pollVotes[2].question); - } else { - for (PollVotes p : pollVotes) { - connection.sendNotice(nick, p.question); - } - } - } - } catch (SQLException e) { - e.printStackTrace(); - } + } } diff --git a/src/main/java/org/freecode/irc/votebot/NoticeFilter.java b/src/main/java/org/freecode/irc/votebot/NoticeFilter.java index 31f27a3..e7a4d1c 100644 --- a/src/main/java/org/freecode/irc/votebot/NoticeFilter.java +++ b/src/main/java/org/freecode/irc/votebot/NoticeFilter.java @@ -1,8 +1,9 @@ package org.freecode.irc.votebot; -import org.freecode.irc.IrcConnection; -import org.freecode.irc.Notice; -import org.freecode.irc.event.NoticeListener; +import com.speed.irc.connection.Server; +import com.speed.irc.event.message.NoticeEvent; +import com.speed.irc.event.message.NoticeListener; +import com.speed.irc.types.Notice; /** * User: Shivam @@ -14,15 +15,15 @@ public abstract class NoticeFilter implements NoticeListener { static class NoticeFilterQueue extends ExpiryQueue { - private final IrcConnection connection; + private final Server connection; - public NoticeFilterQueue(long defaultExpiry, IrcConnection connection) { + public NoticeFilterQueue(long defaultExpiry, Server connection) { super(defaultExpiry); this.connection = connection; } public void onRemoval(NoticeFilter notice) { - connection.removeListener(notice); + connection.getEventManager().removeListener(notice); } } @@ -39,7 +40,7 @@ public NoticeFilter() { this(true); } - public static void setFilterQueue(IrcConnection connection, long delay) { + public static void setFilterQueue(Server connection, long delay) { queue = new NoticeFilterQueue(delay, connection); } @@ -47,9 +48,10 @@ public static void setFilterQueue(IrcConnection connection, long delay) { public abstract void run(Notice notice); - public void onNotice(Notice n) { - if (accept(n)) { - run(n); + @Override + public void noticeReceived(NoticeEvent n) { + if (accept(n.getNotice())) { + run(n.getNotice()); } } } diff --git a/src/main/java/org/freecode/irc/votebot/api/AdminModule.java b/src/main/java/org/freecode/irc/votebot/api/AdminModule.java index 5d53ecb..e05cd28 100644 --- a/src/main/java/org/freecode/irc/votebot/api/AdminModule.java +++ b/src/main/java/org/freecode/irc/votebot/api/AdminModule.java @@ -1,8 +1,7 @@ package org.freecode.irc.votebot.api; -import org.freecode.irc.Notice; -import org.freecode.irc.Privmsg; -import org.freecode.irc.Transmittable; +import com.speed.irc.types.Notice; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.FreeVoteBot; import org.freecode.irc.votebot.NoticeFilter; @@ -30,9 +29,8 @@ public String getCapitalisedName() { protected abstract Right[] getRights(); @Override - public final void process(Transmittable trns) { - final Privmsg privmsg = (Privmsg) trns; - privmsg.getIrcConnection().addListener(new NoticeFilter() { + public final void process(final Privmsg privmsg) { + privmsg.getConversable().getServer().getEventManager().addListener(new NoticeFilter() { public boolean accept(Notice notice) { Pattern pattern = Pattern.compile("\u0002(.+?)\u0002"); Matcher matcher = pattern.matcher(notice.getMessage()); @@ -40,18 +38,18 @@ public boolean accept(Notice notice) { String access = matcher.group(1); for (Right right : getRights()) { if (right.getCapitalisedName().equals(access)) { - return notice.getNick().equals("ChanServ") && notice.getMessage().contains("Main nick:") && notice.getMessage().contains("\u0002" + privmsg.getNick() + "\u0002"); + return notice.getSenderNick().equals("ChanServ") && notice.getMessage().contains("Main nick:") && notice.getMessage().contains("\u0002" + privmsg.getSender() + "\u0002"); } } } if (notice.getMessage().equals("Permission denied.")) - notice.getIrcConnection().removeListener(this); + privmsg.getConversable().getServer().getEventManager().removeListener(this); return false; } public void run(Notice notice) { processMessage(privmsg); - privmsg.getIrcConnection().removeListener(this); + privmsg.getConversable().getServer().getEventManager().removeListener(this); } }); diff --git a/src/main/java/org/freecode/irc/votebot/api/CommandModule.java b/src/main/java/org/freecode/irc/votebot/api/CommandModule.java index 8adc088..82c7ba1 100644 --- a/src/main/java/org/freecode/irc/votebot/api/CommandModule.java +++ b/src/main/java/org/freecode/irc/votebot/api/CommandModule.java @@ -1,56 +1,56 @@ package org.freecode.irc.votebot.api; -import org.freecode.irc.Privmsg; -import org.freecode.irc.Transmittable; +import com.speed.irc.connection.Server; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.FreeVoteBot; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class CommandModule extends FVBModule { - private final Pattern COMMAND_PATTERN; - private final Pattern NAME_PATTERN, PARAMETER_PATTERN; - - public CommandModule() { - char c = getCommandCharacter(); - this.COMMAND_PATTERN = Pattern.compile(String.format("(%s([^ ]+))|(%s(.+?) (.+))", c, c)); - this.PARAMETER_PATTERN = Pattern.compile(getParameterRegex()); - this.NAME_PATTERN = Pattern.compile(getName()); - } - - @Override - public boolean canRun(Transmittable trns) { - if (!trns.isPrivmsg()) - return false; - String msg = trns.asPrivmsg().getMessage(); - Matcher matcher = COMMAND_PATTERN.matcher(msg); - if (matcher.matches()) { - if (matcher.group(4) == null || matcher.group(4).isEmpty()) { - return NAME_PATTERN.matcher(matcher.group(2)).matches(); - } else { - return NAME_PATTERN.matcher(matcher.group(4)).matches() && - PARAMETER_PATTERN.matcher(matcher.group(5)).matches(); - } - } - return false; - } - - @Override - public void process(Transmittable trns) { - processMessage((Privmsg) trns); - } - - protected void askChanServForUserCreds(Privmsg privmsg) { - privmsg.getIrcConnection().send(new Privmsg("ChanServ", "WHY " + FreeVoteBot.CHANNEL_SOURCE + " " + privmsg.getNick(), privmsg.getIrcConnection())); - } - - public abstract void processMessage(Privmsg privmsg); - - protected String getParameterRegex() { - return ".*"; - } - - protected char getCommandCharacter() { - return '!'; - } + private final Pattern COMMAND_PATTERN; + private final Pattern NAME_PATTERN, PARAMETER_PATTERN; + + public CommandModule() { + char c = getCommandCharacter(); + this.COMMAND_PATTERN = Pattern.compile(String.format("(%s([^ ]+))|(%s(.+?) (.+))", c, c)); + this.PARAMETER_PATTERN = Pattern.compile(getParameterRegex()); + this.NAME_PATTERN = Pattern.compile(getName()); + } + + @Override + public boolean canRun(Privmsg trns) { + String msg = trns.getMessage(); + Matcher matcher = COMMAND_PATTERN.matcher(msg); + if (matcher.matches()) { + if (matcher.group(4) == null || matcher.group(4).isEmpty()) { + return NAME_PATTERN.matcher(matcher.group(2)).matches(); + } else { + return NAME_PATTERN.matcher(matcher.group(4)).matches() && + PARAMETER_PATTERN.matcher(matcher.group(5)).matches(); + } + } + return false; + } + + @Override + public void process(Privmsg trns) { + processMessage(trns); + } + + protected void askChanServForUserCreds(Privmsg privmsg) { + Server server = privmsg.getConversable().getServer(); + server.sendMessage(new Privmsg("WHY " + FreeVoteBot.CHANNEL_SOURCE + " " + + privmsg.getSender(), null, server.getUser("ChanServ"))); + } + + public abstract void processMessage(Privmsg privmsg); + + protected String getParameterRegex() { + return ".*"; + } + + protected char getCommandCharacter() { + return '!'; + } } diff --git a/src/main/java/org/freecode/irc/votebot/api/FVBModule.java b/src/main/java/org/freecode/irc/votebot/api/FVBModule.java index 79953ed..ac3e7cd 100644 --- a/src/main/java/org/freecode/irc/votebot/api/FVBModule.java +++ b/src/main/java/org/freecode/irc/votebot/api/FVBModule.java @@ -1,14 +1,14 @@ package org.freecode.irc.votebot.api; -import org.freecode.irc.Transmittable; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.KVStore; public abstract class FVBModule implements Runnable { private volatile boolean enabled = true; - public abstract boolean canRun(final Transmittable trns); + public abstract boolean canRun(final Privmsg trns); - public abstract void process(final Transmittable trns); + public abstract void process(final Privmsg trns); public abstract String getName(); diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/CreatePollModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/CreatePollModule.java index c65278d..045662c 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/CreatePollModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/CreatePollModule.java @@ -1,11 +1,10 @@ package org.freecode.irc.votebot.modules.admin; -import org.freecode.irc.Privmsg; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.PollExpiryAnnouncer; import org.freecode.irc.votebot.api.AdminModule; import org.freecode.irc.votebot.dao.PollDAO; -import java.sql.SQLException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -29,7 +28,7 @@ public void processMessage(final Privmsg privmsg) { lifeSpan = parseExpiry(parts[1]); question = parts[2]; } catch (IllegalArgumentException e) { - privmsg.getIrcConnection().send(new Privmsg(privmsg.getTarget(), e.getMessage(), privmsg.getIrcConnection())); + privmsg.getConversable().sendMessage(e.getMessage()); throw e; } } else { @@ -38,14 +37,14 @@ public void processMessage(final Privmsg privmsg) { } if (question.isEmpty() || question.length() < 5) { - privmsg.getIrcConnection().send(new Privmsg(privmsg.getTarget(), "Question is too short.", privmsg.getIrcConnection())); + privmsg.getConversable().sendMessage("Question is too short."); return; } try { final long expiration = System.currentTimeMillis() + lifeSpan; - int id = pollDAO.addNewPoll(question.trim(), expiration, privmsg.getNick()); - privmsg.getIrcConnection().send(new Privmsg(privmsg.getTarget(), "Created poll, type !vote " + id + " yes/no/abstain to vote.", privmsg.getIrcConnection())); + int id = pollDAO.addNewPoll(question.trim(), expiration, privmsg.getSender()); + privmsg.getConversable().sendMessage("Created poll, type !vote " + id + " yes/no/abstain to vote."); PollExpiryAnnouncer exp = new PollExpiryAnnouncer(expiration, id, getFvb()); ScheduledFuture future = getFvb().pollExecutor.scheduleAtFixedRate(exp, 5000L, 500L, TimeUnit.MILLISECONDS); exp.setFuture(future); diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/JoinChannelModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/JoinChannelModule.java index ee71a10..00c8311 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/JoinChannelModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/JoinChannelModule.java @@ -1,6 +1,6 @@ package org.freecode.irc.votebot.modules.admin; -import org.freecode.irc.Privmsg; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.api.AdminModule; /** @@ -13,7 +13,7 @@ public class JoinChannelModule extends AdminModule { @Override public void processMessage(Privmsg privmsg) { String msg = privmsg.getMessage().substring(2).trim(); - privmsg.getIrcConnection().joinChannel(msg); + privmsg.getConversable().getServer().joinChannel(msg); } @Override diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/LoadModules.java b/src/main/java/org/freecode/irc/votebot/modules/admin/LoadModules.java index 4f82552..308e7a2 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/LoadModules.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/LoadModules.java @@ -1,12 +1,12 @@ package org.freecode.irc.votebot.modules.admin; +import com.speed.irc.types.Privmsg; import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.PullResult; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; -import org.freecode.irc.Privmsg; import org.freecode.irc.votebot.ScriptModuleLoader; import org.freecode.irc.votebot.api.AdminModule; import org.freecode.irc.votebot.api.ExternalModule; @@ -59,7 +59,7 @@ protected Right[] getRights() { public void processMessage(Privmsg privmsg) { String command = privmsg.getMessage().substring(getName().length() + 1).trim(); if (git == null || repository == null) { - privmsg.send("Failed to load git repositories"); + privmsg.getConversable().sendMessage("Failed to load git repositories"); if (!command.equalsIgnoreCase("clean")) { return; } @@ -67,32 +67,32 @@ public void processMessage(Privmsg privmsg) { if (command.equalsIgnoreCase("pull")) { try { PullResult result = git.pull().call(); - privmsg.send(result.isSuccessful() ? "Successfully pulled." : "Failed to pull."); + privmsg.getConversable().sendMessage(result.isSuccessful() ? "Successfully pulled." : "Failed to pull."); } catch (GitAPIException e) { - privmsg.send(e.getMessage()); + privmsg.getConversable().sendMessage(e.getMessage()); } } else if (command.equalsIgnoreCase("clean")) { try { git = cloneRepo(); repository = git.getRepository(); - privmsg.send("Successfully cleaned"); + privmsg.getConversable().sendMessage("Successfully cleaned"); } catch (Exception e) { - privmsg.send(e.getMessage()); + privmsg.getConversable().sendMessage(e.getMessage()); } } else if (command.equalsIgnoreCase("reload")) { try { getFvb().removeModules(loadedModules); loadedModules.addAll(Arrays.asList(loadModules())); getFvb().addModules(loadedModules); - privmsg.send("Successfully reloaded"); + privmsg.getConversable().sendMessage("Successfully reloaded"); } catch (Exception e) { - privmsg.send("Error reloading: " + e.getMessage()); + privmsg.getConversable().sendMessage("Error reloading: " + e.getMessage()); } } else if (command.startsWith("load ")) { String name = command.substring(5).trim(); if (name.matches(".*[^\\w].*")) { //contains a symbol that isn't a word - privmsg.send("Invalid name!"); + privmsg.getConversable().sendMessage("Invalid name!"); } else { File file = new File(MODULES_DIR, name.concat(".py")); if (file.exists()) { @@ -101,21 +101,21 @@ public void processMessage(Privmsg privmsg) { .loadFromFile(file); loadedModules.add(module); if (getFvb().addModule(module)) - privmsg.send("Successfully added module"); + privmsg.getConversable().sendMessage("Successfully added module"); else - privmsg.send("Failed to add module"); + privmsg.getConversable().sendMessage("Failed to add module"); } catch (IOException | ScriptException e) { - privmsg.send("Error loading module: " + e.getMessage()); + privmsg.getConversable().sendMessage("Error loading module: " + e.getMessage()); } } else { - privmsg.send("File does not exist!"); + privmsg.getConversable().sendMessage("File does not exist!"); } } } else if (command.startsWith("remove ")) { String name = command.substring(6).trim(); if (name.matches(".*[^\\w].*")) { //contains a symbol that isn't a word - privmsg.send("Invalid name!"); + privmsg.getConversable().sendMessage("Invalid name!"); } else { ExternalModule module = null; for (ExternalModule ext : loadedModules) { @@ -127,9 +127,9 @@ public void processMessage(Privmsg privmsg) { if (module != null) { loadedModules.remove(module); if (getFvb().removeModule(module)) { - privmsg.send("Successfully removed"); + privmsg.getConversable().sendMessage("Successfully removed"); } else { - privmsg.send("Failed to remove"); + privmsg.getConversable().sendMessage("Failed to remove"); } } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/OpenClosePollModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/OpenClosePollModule.java index b7df115..b538869 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/OpenClosePollModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/OpenClosePollModule.java @@ -1,6 +1,6 @@ package org.freecode.irc.votebot.modules.admin; -import org.freecode.irc.Privmsg; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.PollExpiryAnnouncer; import org.freecode.irc.votebot.api.AdminModule; import org.freecode.irc.votebot.dao.PollDAO; @@ -31,7 +31,7 @@ public void processMessage(Privmsg privmsg) { } try { if (pollDAO.setStatusOfPoll(id, state) > 0) { - privmsg.send("Poll #" + id + " " + action + "."); + privmsg.getConversable().sendMessage("Poll #" + id + " " + action + "."); if (action.equalsIgnoreCase("closed")) { Future future = getFvb().pollFutures.get(id); if (future != null) { diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/RebuildModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/RebuildModule.java index 85003db..bb81d4a 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/RebuildModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/RebuildModule.java @@ -1,6 +1,6 @@ package org.freecode.irc.votebot.modules.admin; -import org.freecode.irc.Privmsg; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.api.AdminModule; import java.io.BufferedReader; @@ -16,74 +16,68 @@ */ public class RebuildModule extends AdminModule { - private String idAbbrev; - private String idDescribe; - - public static final String LAST_ID = "pre-rebuild.commit.id.abbrev"; - - public void init() { - String last = readString(LAST_ID); - if (idAbbrev.equalsIgnoreCase(last)) return; - - int commits = countCommitsSince(last); - getFvb().sendMsg("Running " + idDescribe + ", " + commits + " new commits since last run (" + last + ")"); - - store(LAST_ID, idAbbrev); - } - - @Override - public void processMessage(Privmsg privmsg) { - try (BufferedWriter writer = privmsg.getIrcConnection().getWriter()) { - writer.write("QUIT :Rebuilding!\r\n"); - writer.flush(); - } catch (IOException e) { - e.printStackTrace(); - } - - try (BufferedReader reader = executeRebuild()) { - String line; - while ((line = reader.readLine()) != null) { - System.out.println(line); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static int countCommitsSince(String idAbbrev) { - try { - Process p = Runtime.getRuntime().exec(new String[]{ - "/bin/sh", "-c", "git rev-list " + idAbbrev + "..HEAD | wc -l" - }); - String line = new BufferedReader(new InputStreamReader(p.getInputStream())).readLine(); - return Integer.parseInt(line); - } catch (IOException | NumberFormatException e) { - e.printStackTrace(); - } - - return -1; - } - - private static BufferedReader executeRebuild() throws IOException { - Process p = Runtime.getRuntime().exec("./run.sh &"); - return new BufferedReader(new InputStreamReader(p.getInputStream())); - } - - @Override - public String getName() { - return "rebuild"; - } - - protected Right[] getRights() { - return new Right[]{Right.FOUNDER}; - } - - public void setIdAbbrev(String idAbbrev) { - this.idAbbrev = idAbbrev; - } - - public void setIdDescribe(String idDescribe) { - this.idDescribe = idDescribe; - } + private String idAbbrev; + private String idDescribe; + + public static final String LAST_ID = "pre-rebuild.commit.id.abbrev"; + + public void init() { + String last = readString(LAST_ID); + if (idAbbrev.equalsIgnoreCase(last)) return; + + int commits = countCommitsSince(last); + getFvb().sendMsg("Running " + idDescribe + ", " + commits + " new commits since last run (" + last + ")"); + + store(LAST_ID, idAbbrev); + } + + @Override + public void processMessage(Privmsg privmsg) { + privmsg.getConversable().getServer().quit("REBUILDING"); + try (BufferedReader reader = executeRebuild()) { + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static int countCommitsSince(String idAbbrev) { + try { + Process p = Runtime.getRuntime().exec(new String[]{ + "/bin/sh", "-c", "git rev-list " + idAbbrev + "..HEAD | wc -l" + }); + String line = new BufferedReader(new InputStreamReader(p.getInputStream())).readLine(); + return Integer.parseInt(line); + } catch (IOException | NumberFormatException e) { + e.printStackTrace(); + } + + return -1; + } + + private static BufferedReader executeRebuild() throws IOException { + Process p = Runtime.getRuntime().exec("./run.sh &"); + return new BufferedReader(new InputStreamReader(p.getInputStream())); + } + + @Override + public String getName() { + return "rebuild"; + } + + protected Right[] getRights() { + return new Right[]{Right.FOUNDER}; + } + + public void setIdAbbrev(String idAbbrev) { + this.idAbbrev = idAbbrev; + } + + public void setIdDescribe(String idDescribe) { + this.idDescribe = idDescribe; + } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/SendMessageModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/SendMessageModule.java index 601f512..8baa8a5 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/SendMessageModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/SendMessageModule.java @@ -1,6 +1,6 @@ package org.freecode.irc.votebot.modules.admin; -import org.freecode.irc.Privmsg; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.api.AdminModule; /** @@ -19,7 +19,8 @@ public void processMessage(Privmsg privmsg) { if(msg.trim().isEmpty()) { return; } - privmsg.getIrcConnection().send(new Privmsg(target, msg, privmsg.getIrcConnection())); + privmsg.getConversable().getServer(). + sendMessage(new Privmsg(msg, null, privmsg.getConversable().getServer().getUser(target))); } @Override diff --git a/src/main/java/org/freecode/irc/votebot/modules/admin/WorkingDirectoryModule.java b/src/main/java/org/freecode/irc/votebot/modules/admin/WorkingDirectoryModule.java index 5525756..48e587e 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/admin/WorkingDirectoryModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/admin/WorkingDirectoryModule.java @@ -1,6 +1,6 @@ package org.freecode.irc.votebot.modules.admin; -import org.freecode.irc.Privmsg; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.api.AdminModule; import java.io.BufferedReader; @@ -11,7 +11,9 @@ public class WorkingDirectoryModule extends AdminModule { @Override public void processMessage(Privmsg privmsg) { try (BufferedReader reader = executePwd()) { - privmsg.getIrcConnection().send(new Privmsg(privmsg.getNick(), "PWD: " + reader.readLine(), privmsg.getIrcConnection())); + privmsg.getConversable().getServer().sendMessage( + new Privmsg("PWD: " + reader.readLine(), null, + privmsg.getConversable().getServer().getUser(privmsg.getSender()))); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/main/java/org/freecode/irc/votebot/modules/common/PollsModule.java b/src/main/java/org/freecode/irc/votebot/modules/common/PollsModule.java index 0e11fa0..c2a9034 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/common/PollsModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/common/PollsModule.java @@ -1,7 +1,8 @@ package org.freecode.irc.votebot.modules.common; -import org.freecode.irc.Notice; -import org.freecode.irc.Privmsg; +import com.speed.irc.connection.Server; +import com.speed.irc.types.Notice; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.api.CommandModule; import org.freecode.irc.votebot.dao.PollDAO; import org.freecode.irc.votebot.dao.VoteDAO; @@ -24,19 +25,20 @@ public void processMessage(Privmsg privmsg) { try { Poll[] polls = pollDAO.getOpenPolls(); String[] params = privmsg.getMessage().split(" "); + Server server = privmsg.getConversable().getServer(); - if (params.length != 1) { - polls = voteDAO.getPollsNotVotedIn(polls, privmsg.getNick()); + if (params.length != 1) { + polls = voteDAO.getPollsNotVotedIn(polls, privmsg.getSender()); } if (polls.length == 0) { String message = params.length == 1 ? "No active polls to view!" : "No polls to vote in!"; - privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), message, privmsg.getIrcConnection())); + server.sendNotice(new Notice(message, null, privmsg.getSender(), server)); return; } String message = params.length == 1 ? "List of polls:" : "List of polls not voted in:"; - privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), message, privmsg.getIrcConnection())); + server.sendNotice(new Notice(message, null, privmsg.getSender(), server)); for (Poll poll : polls) { Vote[] votes = voteDAO.getVotesOnPoll(poll.getId()); @@ -56,11 +58,11 @@ public void processMessage(Privmsg privmsg) { String msg = "Poll #" + poll.getId() + ": " + poll.getQuestion() + " Ends: " + getDateFormatter().format(new Date(poll.getExpiry())) + " Created by: " + poll.getCreator() + " Yes: " + yes + " No: " + no + " Abstain: " + abstain; - privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), msg, privmsg.getIrcConnection())); + server.sendNotice(new Notice(msg, null, privmsg.getSender(), server)); } - privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "End list of polls.", privmsg.getIrcConnection())); + server.sendNotice(new Notice("End list of polls", null, privmsg.getSender(), server)); } catch (SQLException e) { - privmsg.send(e.getMessage()); + privmsg.getConversable().sendMessage(e.getMessage()); } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/common/StoreTestModule.java b/src/main/java/org/freecode/irc/votebot/modules/common/StoreTestModule.java index 001283a..362975e 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/common/StoreTestModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/common/StoreTestModule.java @@ -1,6 +1,6 @@ package org.freecode.irc.votebot.modules.common; -import org.freecode.irc.Privmsg; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.api.CommandModule; public class StoreTestModule extends CommandModule { @@ -11,11 +11,11 @@ public void processMessage(Privmsg privmsg) { if (command.equalsIgnoreCase("test")) { String lastSender; if ((lastSender = readString("sender.last")) == null) { - privmsg.send("Successful test!"); + privmsg.getConversable().sendMessage("Successful test!"); } else { - privmsg.send("Successful test! Last tester was: " + lastSender); + privmsg.getConversable().sendMessage("Successful test! Last tester was: " + lastSender); } - store("sender.last", privmsg.getNick()); + store("sender.last", privmsg.getSender()); } else if (command.startsWith("set ")) { try { String[] args = command.substring(4).trim().split(" "); @@ -23,7 +23,7 @@ public void processMessage(Privmsg privmsg) { String value = args[1]; store(key, value); - privmsg.send(key + ": " + readJson(key)); + privmsg.getConversable().sendMessage(key + ": " + readJson(key)); } catch (Exception e) { e.printStackTrace(); } @@ -31,7 +31,7 @@ public void processMessage(Privmsg privmsg) { try { String key = command.substring(4).trim(); - privmsg.send(key + ": " + readJson(key)); + privmsg.getConversable().sendMessage(key + ": " + readJson(key)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/org/freecode/irc/votebot/modules/common/TestModule.java b/src/main/java/org/freecode/irc/votebot/modules/common/TestModule.java index 9610f27..fc37518 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/common/TestModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/common/TestModule.java @@ -1,6 +1,6 @@ package org.freecode.irc.votebot.modules.common; -import org.freecode.irc.Privmsg; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.api.CommandModule; public class TestModule extends CommandModule { @@ -8,12 +8,12 @@ public class TestModule extends CommandModule { public void processMessage(Privmsg privmsg) { String lastSender; if ((lastSender = readString("sender.last")) == null) { - privmsg.send("Successful test!"); + privmsg.getConversable().sendMessage("Successful test!"); } else { //lastSender = new Gson().fromJson(lastSender, String.class); - privmsg.send("Successful test! Last tester was: " + lastSender); + privmsg.getConversable().sendMessage("Successful test! Last tester was: " + lastSender); } - store("sender.last", privmsg.getNick()); + store("sender.last", privmsg.getSender()); } public String getName() { diff --git a/src/main/java/org/freecode/irc/votebot/modules/common/VersionModule.java b/src/main/java/org/freecode/irc/votebot/modules/common/VersionModule.java index 0393924..aed92ef 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/common/VersionModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/common/VersionModule.java @@ -1,6 +1,6 @@ package org.freecode.irc.votebot.modules.common; -import org.freecode.irc.Privmsg; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.api.CommandModule; public class VersionModule extends CommandModule { @@ -13,9 +13,9 @@ public class VersionModule extends CommandModule { public void processMessage(Privmsg privmsg) { String[] params = privmsg.getMessage().split(" "); if (params.length == 1) { - privmsg.send("Version: " + version); + privmsg.getConversable().sendMessage("Version: " + version); } else { - privmsg.send("Version: " + version + ", last commit \"" + + privmsg.getConversable().sendMessage("Version: " + version + ", last commit \"" + commitMessage + "\" by " + commitAuthor + ", " + commitTime); } } diff --git a/src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java b/src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java index 8f9d863..c6272c1 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java @@ -1,7 +1,8 @@ package org.freecode.irc.votebot.modules.common; -import org.freecode.irc.Notice; -import org.freecode.irc.Privmsg; +import com.speed.irc.connection.Server; +import com.speed.irc.types.Notice; +import com.speed.irc.types.Privmsg; import org.freecode.irc.votebot.NoticeFilter; import org.freecode.irc.votebot.api.CommandModule; import org.freecode.irc.votebot.dao.PollDAO; @@ -23,172 +24,175 @@ */ public class VoteModule extends CommandModule { - private PollDAO pollDAO; - private VoteDAO voteDAO; - - public void processMessage(Privmsg privmsg) { - String message = privmsg.getMessage(); - if (message.startsWith("!v ") || message.startsWith("!vote ")) { - final String msg = privmsg.getMessage().substring(privmsg.getMessage().indexOf(' ')).trim(); - System.out.println(msg); - final String[] split = msg.split(" ", 2); - if (split.length == 2) { - String ids = split[0]; - String vote = split[1].toLowerCase(); - final int nId; - switch (vote) { - case "yes": - nId = 0; - break; - case "no": - nId = 1; - break; - case "abstain": - nId = 2; - break; - default: - return; - } - if (!ids.matches("\\d+")) { - return; - } - final int id = Integer.parseInt(ids); - vote(nId, id, privmsg); - } else if (split.length == 1) { - String id = split[0]; - if (!id.matches("\\d+")) { - return; - } - try { - - int pollId = Integer.parseInt(id); - Poll poll = pollDAO.getPoll(pollId); - - if (poll != null) { - String expiry = getDateFormatter().format(new Date(poll.getExpiry())); - String closed = poll.isClosed() ? "Closed" : "Open"; - if (System.currentTimeMillis() >= poll.getExpiry()) { - closed = "Expired"; - } - - Vote[] votes = voteDAO.getVotesOnPoll(pollId); - int yes = 0, no = 0, abstain = 0; - for (Vote vote : votes) { - int answerIndex = vote.getAnswerIndex(); - if (answerIndex == 0) { - yes++; - } else if (answerIndex == 1) { - no++; - } else if (answerIndex == 2) { - abstain++; - } - } - - boolean open = closed.equals("Open"); - privmsg.send("Poll #" + poll.getId() + ": " + poll.getQuestion() + - " Created by: " + poll.getCreator() + - " Yes: " + yes + " No: " + no + " Abstain: " + abstain + - " Status: \u00030" + (open ? "3" : "4") + closed + "\u0003" + - (open ? " Ends: " : " Ended: ") + expiry); - - } - } catch (SQLException e) { - privmsg.send(e.getMessage()); - } - } - - } else if (message.startsWith("!y ")) { - String id = message.replace("!y", "").trim(); - if (id.matches("\\d+")) { - voteYes(Integer.parseInt(id), privmsg); - } - } else if (message.startsWith("!n ")) { - String id = message.replace("!n", "").trim(); - if (id.matches("\\d+")) { - voteNo(Integer.parseInt(id), privmsg); - } - } else if (message.startsWith("!a ")) { - String id = message.replace("!a", "").trim(); - if (id.matches("\\d+")) { - voteAbstain(Integer.parseInt(id), privmsg); - } - } - } - - private void voteYes(final int pollId, final Privmsg privmsg) { - vote(0, pollId, privmsg); - } - - private void voteNo(final int pollId, final Privmsg privmsg) { - vote(1, pollId, privmsg); - } - - private void voteAbstain(final int pollId, final Privmsg privmsg) { - vote(2, pollId, privmsg); - } - - private void vote(final int answerIndex, final int pollId, final Privmsg privmsg) { - - privmsg.getIrcConnection().addListener(new NoticeFilter() { - public boolean accept(Notice notice) { - if (notice.getNick().equals("ChanServ") && notice.getMessage().equals("Permission denied.")) { - notice.getIrcConnection().removeListener(this); - return false; - } - return notice.getNick().equals("ChanServ") && notice.getMessage().contains("Main nick:") && notice.getMessage().contains(privmsg.getNick()); - } - - public void run(Notice notice) { - try { - String mainNick = notice.getMessage().substring(notice.getMessage().indexOf("Main nick:") + 10).trim(); - System.out.println(mainNick); - - Poll poll = pollDAO.getPoll(pollId); - if (poll != null) { - long time = poll.getExpiry(); - if (System.currentTimeMillis() < time && !poll.isClosed()) { - Vote vote = voteDAO.getUsersVoteOnPoll(mainNick, pollId); - if (vote != null) { - if (vote.getAnswerIndex() == answerIndex) { - privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "You've already voted with this option!", privmsg.getIrcConnection())); - } else { - vote.setAnswerIndex(answerIndex); - voteDAO.updateUsersVote(vote); - privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "Vote updated.", privmsg.getIrcConnection())); - } - } else { - voteDAO.addUsersVote(mainNick, pollId, answerIndex); - privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "Vote cast.", privmsg.getIrcConnection())); - } - } else { - privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "Voting is closed for this poll.", privmsg.getIrcConnection())); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - privmsg.getIrcConnection().removeListener(this); - } - }); - - askChanServForUserCreds(privmsg); - } - - private DateFormat getDateFormatter() { - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.UK); - dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London")); - return dateFormat; - } - - public String getName() { - return "(vote|v|y|n|a)"; - } - - public void setPollDAO(PollDAO pollDAO) { - this.pollDAO = pollDAO; - } - - public void setVoteDAO(VoteDAO voteDAO) { - this.voteDAO = voteDAO; - } + private PollDAO pollDAO; + private VoteDAO voteDAO; + + public void processMessage(Privmsg privmsg) { + String message = privmsg.getMessage(); + if (message.startsWith("!v ") || message.startsWith("!vote ")) { + final String msg = privmsg.getMessage().substring(privmsg.getMessage().indexOf(' ')).trim(); + System.out.println(msg); + final String[] split = msg.split(" ", 2); + if (split.length == 2) { + String ids = split[0]; + String vote = split[1].toLowerCase(); + final int nId; + switch (vote) { + case "yes": + nId = 0; + break; + case "no": + nId = 1; + break; + case "abstain": + nId = 2; + break; + default: + return; + } + if (!ids.matches("\\d+")) { + return; + } + final int id = Integer.parseInt(ids); + vote(nId, id, privmsg); + } else if (split.length == 1) { + String id = split[0]; + if (!id.matches("\\d+")) { + return; + } + try { + + int pollId = Integer.parseInt(id); + Poll poll = pollDAO.getPoll(pollId); + + if (poll != null) { + String expiry = getDateFormatter().format(new Date(poll.getExpiry())); + String closed = poll.isClosed() ? "Closed" : "Open"; + if (System.currentTimeMillis() >= poll.getExpiry()) { + closed = "Expired"; + } + + Vote[] votes = voteDAO.getVotesOnPoll(pollId); + int yes = 0, no = 0, abstain = 0; + for (Vote vote : votes) { + int answerIndex = vote.getAnswerIndex(); + if (answerIndex == 0) { + yes++; + } else if (answerIndex == 1) { + no++; + } else if (answerIndex == 2) { + abstain++; + } + } + + boolean open = closed.equals("Open"); + privmsg.getConversable().sendMessage("Poll #" + poll.getId() + ": " + poll.getQuestion() + + " Created by: " + poll.getCreator() + + " Yes: " + yes + " No: " + no + " Abstain: " + abstain + + " Status: \u00030" + (open ? "3" : "4") + closed + "\u0003" + + (open ? " Ends: " : " Ended: ") + expiry); + + } + } catch (SQLException e) { + privmsg.getConversable().sendMessage(e.getMessage()); + } + } + + } else if (message.startsWith("!y ")) { + String id = message.replace("!y", "").trim(); + if (id.matches("\\d+")) { + voteYes(Integer.parseInt(id), privmsg); + } + } else if (message.startsWith("!n ")) { + String id = message.replace("!n", "").trim(); + if (id.matches("\\d+")) { + voteNo(Integer.parseInt(id), privmsg); + } + } else if (message.startsWith("!a ")) { + String id = message.replace("!a", "").trim(); + if (id.matches("\\d+")) { + voteAbstain(Integer.parseInt(id), privmsg); + } + } + } + + private void voteYes(final int pollId, final Privmsg privmsg) { + vote(0, pollId, privmsg); + } + + private void voteNo(final int pollId, final Privmsg privmsg) { + vote(1, pollId, privmsg); + } + + private void voteAbstain(final int pollId, final Privmsg privmsg) { + vote(2, pollId, privmsg); + } + + private void vote(final int answerIndex, final int pollId, final Privmsg privmsg) { + + privmsg.getConversable().getServer().getEventManager().addListener(new NoticeFilter() { + public boolean accept(Notice notice) { + if (notice.getSenderNick().equals("ChanServ") && notice.getMessage().equals("Permission denied.")) { + notice.getServer().getEventManager().removeListener(this); + return false; + } + return notice.getSenderNick().equals("ChanServ") && notice.getMessage().contains("Main nick:") && notice.getMessage().contains(privmsg.getSender()); + } + + public void run(Notice notice) { + try { + String mainNick = notice.getMessage().substring(notice.getMessage().indexOf("Main nick:") + 10).trim(); + System.out.println(mainNick); + Server server = privmsg.getConversable().getServer(); + Poll poll = pollDAO.getPoll(pollId); + if (poll != null) { + long time = poll.getExpiry(); + if (System.currentTimeMillis() < time && !poll.isClosed()) { + Vote vote = voteDAO.getUsersVoteOnPoll(mainNick, pollId); + if (vote != null) { + if (vote.getAnswerIndex() == answerIndex) { + server.sendNotice(new Notice("You've already voted with this option!", null, privmsg.getSender(), server)); + } else { + vote.setAnswerIndex(answerIndex); + voteDAO.updateUsersVote(vote); + server.sendNotice(new Notice("Vote updated!", null, privmsg.getSender(), server)); + + } + } else { + voteDAO.addUsersVote(mainNick, pollId, answerIndex); + server.sendNotice(new Notice("Vote cast!s", null, privmsg.getSender(), server)); + + } + } else { + server.sendNotice(new Notice("Voting is closed for this poll.", null, privmsg.getSender(), server)); + + } + } + } catch (Exception e) { + e.printStackTrace(); + } + privmsg.getConversable().getServer().getEventManager().removeListener(this); + } + }); + + askChanServForUserCreds(privmsg); + } + + private DateFormat getDateFormatter() { + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.UK); + dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London")); + return dateFormat; + } + + public String getName() { + return "(vote|v|y|n|a)"; + } + + public void setPollDAO(PollDAO pollDAO) { + this.pollDAO = pollDAO; + } + + public void setVoteDAO(VoteDAO voteDAO) { + this.voteDAO = voteDAO; + } } diff --git a/src/main/resources/properties/freevotebot.properties b/src/main/resources/properties/freevotebot.properties index 1ded562..c2163b6 100644 --- a/src/main/resources/properties/freevotebot.properties +++ b/src/main/resources/properties/freevotebot.properties @@ -5,7 +5,7 @@ user.realName=FreeVoteBot # IRC Server Properties ircServer.host=irc.rizon.net -ircServer.port=6667 +ircServer.port=6697 ircServer.channels=#freecode # Database Properties From e8a70f42ab6daeec7250dc3b9106db3808c797f6 Mon Sep 17 00:00:00 2001 From: ShivamMistry Date: Sat, 17 May 2014 23:52:41 +0100 Subject: [PATCH 3/4] move api --- pom.xml | 2 +- {api => src/api}/com/speed/irc/connection/Server.java | 0 .../api}/com/speed/irc/connection/ServerMessageParser.java | 0 .../api}/com/speed/irc/connection/ServerMessageReader.java | 0 .../api}/com/speed/irc/connection/ServerSupportParser.java | 0 .../api}/com/speed/irc/connection/ssl/IRCTrustManager.java | 0 {api => src/api}/com/speed/irc/event/EventGenerator.java | 0 {api => src/api}/com/speed/irc/event/EventManager.java | 0 {api => src/api}/com/speed/irc/event/IRCEvent.java | 0 {api => src/api}/com/speed/irc/event/IRCEventListener.java | 0 {api => src/api}/com/speed/irc/event/ListenerProperties.java | 0 {api => src/api}/com/speed/irc/event/api/ApiEvent.java | 0 {api => src/api}/com/speed/irc/event/api/ApiListener.java | 0 {api => src/api}/com/speed/irc/event/api/ExceptionEvent.java | 0 {api => src/api}/com/speed/irc/event/api/WhoisEvent.java | 0 {api => src/api}/com/speed/irc/event/api/WhoisListener.java | 0 {api => src/api}/com/speed/irc/event/channel/ChannelEvent.java | 0 .../api}/com/speed/irc/event/channel/ChannelEventListener.java | 0 .../api}/com/speed/irc/event/channel/ChannelUserEvent.java | 0 .../api}/com/speed/irc/event/channel/ChannelUserListener.java | 0 .../api}/com/speed/irc/event/channel/ModeChangedEvent.java | 0 .../api}/com/speed/irc/event/channel/TopicChangedEvent.java | 0 .../api}/com/speed/irc/event/generators/JoinGenerator.java | 0 .../api}/com/speed/irc/event/generators/KickGenerator.java | 0 .../api}/com/speed/irc/event/generators/ModeGenerator.java | 0 .../api}/com/speed/irc/event/generators/NoticeGenerator.java | 0 .../api}/com/speed/irc/event/generators/PartGenerator.java | 0 .../api}/com/speed/irc/event/generators/PrivmsgGenerator.java | 0 .../api}/com/speed/irc/event/generators/WhoisGenerator.java | 0 {api => src/api}/com/speed/irc/event/message/NoticeEvent.java | 0 .../api}/com/speed/irc/event/message/NoticeListener.java | 0 .../api}/com/speed/irc/event/message/PrivateMessageEvent.java | 0 .../com/speed/irc/event/message/PrivateMessageListener.java | 0 .../api}/com/speed/irc/event/message/RawMessageEvent.java | 0 .../api}/com/speed/irc/event/message/RawMessageListener.java | 0 {api => src/api}/com/speed/irc/framework/Bot.java | 0 .../api}/com/speed/irc/framework/test/GraphicalUserList.java | 0 {api => src/api}/com/speed/irc/framework/test/HelloBot.java | 0 {api => src/api}/com/speed/irc/types/Bot.java | 0 {api => src/api}/com/speed/irc/types/CTCPReply.java | 0 {api => src/api}/com/speed/irc/types/Channel.java | 0 {api => src/api}/com/speed/irc/types/ChannelUser.java | 0 {api => src/api}/com/speed/irc/types/Conversable.java | 0 {api => src/api}/com/speed/irc/types/Mask.java | 0 {api => src/api}/com/speed/irc/types/Mode.java | 0 {api => src/api}/com/speed/irc/types/ModeList.java | 0 {api => src/api}/com/speed/irc/types/Notice.java | 2 +- {api => src/api}/com/speed/irc/types/ParsingException.java | 0 {api => src/api}/com/speed/irc/types/Privmsg.java | 0 {api => src/api}/com/speed/irc/types/RawMessage.java | 0 {api => src/api}/com/speed/irc/types/ServerUser.java | 0 {api => src/api}/com/speed/irc/types/Whois.java | 0 {api => src/api}/com/speed/irc/util/ControlCodeFormatter.java | 0 {api => src/api}/com/speed/irc/util/Numerics.java | 0 54 files changed, 2 insertions(+), 2 deletions(-) rename {api => src/api}/com/speed/irc/connection/Server.java (100%) rename {api => src/api}/com/speed/irc/connection/ServerMessageParser.java (100%) rename {api => src/api}/com/speed/irc/connection/ServerMessageReader.java (100%) rename {api => src/api}/com/speed/irc/connection/ServerSupportParser.java (100%) rename {api => src/api}/com/speed/irc/connection/ssl/IRCTrustManager.java (100%) rename {api => src/api}/com/speed/irc/event/EventGenerator.java (100%) rename {api => src/api}/com/speed/irc/event/EventManager.java (100%) rename {api => src/api}/com/speed/irc/event/IRCEvent.java (100%) rename {api => src/api}/com/speed/irc/event/IRCEventListener.java (100%) rename {api => src/api}/com/speed/irc/event/ListenerProperties.java (100%) rename {api => src/api}/com/speed/irc/event/api/ApiEvent.java (100%) rename {api => src/api}/com/speed/irc/event/api/ApiListener.java (100%) rename {api => src/api}/com/speed/irc/event/api/ExceptionEvent.java (100%) rename {api => src/api}/com/speed/irc/event/api/WhoisEvent.java (100%) rename {api => src/api}/com/speed/irc/event/api/WhoisListener.java (100%) rename {api => src/api}/com/speed/irc/event/channel/ChannelEvent.java (100%) rename {api => src/api}/com/speed/irc/event/channel/ChannelEventListener.java (100%) rename {api => src/api}/com/speed/irc/event/channel/ChannelUserEvent.java (100%) rename {api => src/api}/com/speed/irc/event/channel/ChannelUserListener.java (100%) rename {api => src/api}/com/speed/irc/event/channel/ModeChangedEvent.java (100%) rename {api => src/api}/com/speed/irc/event/channel/TopicChangedEvent.java (100%) rename {api => src/api}/com/speed/irc/event/generators/JoinGenerator.java (100%) rename {api => src/api}/com/speed/irc/event/generators/KickGenerator.java (100%) rename {api => src/api}/com/speed/irc/event/generators/ModeGenerator.java (100%) rename {api => src/api}/com/speed/irc/event/generators/NoticeGenerator.java (100%) rename {api => src/api}/com/speed/irc/event/generators/PartGenerator.java (100%) rename {api => src/api}/com/speed/irc/event/generators/PrivmsgGenerator.java (100%) rename {api => src/api}/com/speed/irc/event/generators/WhoisGenerator.java (100%) rename {api => src/api}/com/speed/irc/event/message/NoticeEvent.java (100%) rename {api => src/api}/com/speed/irc/event/message/NoticeListener.java (100%) rename {api => src/api}/com/speed/irc/event/message/PrivateMessageEvent.java (100%) rename {api => src/api}/com/speed/irc/event/message/PrivateMessageListener.java (100%) rename {api => src/api}/com/speed/irc/event/message/RawMessageEvent.java (100%) rename {api => src/api}/com/speed/irc/event/message/RawMessageListener.java (100%) rename {api => src/api}/com/speed/irc/framework/Bot.java (100%) rename {api => src/api}/com/speed/irc/framework/test/GraphicalUserList.java (100%) rename {api => src/api}/com/speed/irc/framework/test/HelloBot.java (100%) rename {api => src/api}/com/speed/irc/types/Bot.java (100%) rename {api => src/api}/com/speed/irc/types/CTCPReply.java (100%) rename {api => src/api}/com/speed/irc/types/Channel.java (100%) rename {api => src/api}/com/speed/irc/types/ChannelUser.java (100%) rename {api => src/api}/com/speed/irc/types/Conversable.java (100%) rename {api => src/api}/com/speed/irc/types/Mask.java (100%) rename {api => src/api}/com/speed/irc/types/Mode.java (100%) rename {api => src/api}/com/speed/irc/types/ModeList.java (100%) rename {api => src/api}/com/speed/irc/types/Notice.java (96%) rename {api => src/api}/com/speed/irc/types/ParsingException.java (100%) rename {api => src/api}/com/speed/irc/types/Privmsg.java (100%) rename {api => src/api}/com/speed/irc/types/RawMessage.java (100%) rename {api => src/api}/com/speed/irc/types/ServerUser.java (100%) rename {api => src/api}/com/speed/irc/types/Whois.java (100%) rename {api => src/api}/com/speed/irc/util/ControlCodeFormatter.java (100%) rename {api => src/api}/com/speed/irc/util/Numerics.java (100%) diff --git a/pom.xml b/pom.xml index 22629ca..45a8285 100644 --- a/pom.xml +++ b/pom.xml @@ -97,7 +97,7 @@ - api + src/api diff --git a/api/com/speed/irc/connection/Server.java b/src/api/com/speed/irc/connection/Server.java similarity index 100% rename from api/com/speed/irc/connection/Server.java rename to src/api/com/speed/irc/connection/Server.java diff --git a/api/com/speed/irc/connection/ServerMessageParser.java b/src/api/com/speed/irc/connection/ServerMessageParser.java similarity index 100% rename from api/com/speed/irc/connection/ServerMessageParser.java rename to src/api/com/speed/irc/connection/ServerMessageParser.java diff --git a/api/com/speed/irc/connection/ServerMessageReader.java b/src/api/com/speed/irc/connection/ServerMessageReader.java similarity index 100% rename from api/com/speed/irc/connection/ServerMessageReader.java rename to src/api/com/speed/irc/connection/ServerMessageReader.java diff --git a/api/com/speed/irc/connection/ServerSupportParser.java b/src/api/com/speed/irc/connection/ServerSupportParser.java similarity index 100% rename from api/com/speed/irc/connection/ServerSupportParser.java rename to src/api/com/speed/irc/connection/ServerSupportParser.java diff --git a/api/com/speed/irc/connection/ssl/IRCTrustManager.java b/src/api/com/speed/irc/connection/ssl/IRCTrustManager.java similarity index 100% rename from api/com/speed/irc/connection/ssl/IRCTrustManager.java rename to src/api/com/speed/irc/connection/ssl/IRCTrustManager.java diff --git a/api/com/speed/irc/event/EventGenerator.java b/src/api/com/speed/irc/event/EventGenerator.java similarity index 100% rename from api/com/speed/irc/event/EventGenerator.java rename to src/api/com/speed/irc/event/EventGenerator.java diff --git a/api/com/speed/irc/event/EventManager.java b/src/api/com/speed/irc/event/EventManager.java similarity index 100% rename from api/com/speed/irc/event/EventManager.java rename to src/api/com/speed/irc/event/EventManager.java diff --git a/api/com/speed/irc/event/IRCEvent.java b/src/api/com/speed/irc/event/IRCEvent.java similarity index 100% rename from api/com/speed/irc/event/IRCEvent.java rename to src/api/com/speed/irc/event/IRCEvent.java diff --git a/api/com/speed/irc/event/IRCEventListener.java b/src/api/com/speed/irc/event/IRCEventListener.java similarity index 100% rename from api/com/speed/irc/event/IRCEventListener.java rename to src/api/com/speed/irc/event/IRCEventListener.java diff --git a/api/com/speed/irc/event/ListenerProperties.java b/src/api/com/speed/irc/event/ListenerProperties.java similarity index 100% rename from api/com/speed/irc/event/ListenerProperties.java rename to src/api/com/speed/irc/event/ListenerProperties.java diff --git a/api/com/speed/irc/event/api/ApiEvent.java b/src/api/com/speed/irc/event/api/ApiEvent.java similarity index 100% rename from api/com/speed/irc/event/api/ApiEvent.java rename to src/api/com/speed/irc/event/api/ApiEvent.java diff --git a/api/com/speed/irc/event/api/ApiListener.java b/src/api/com/speed/irc/event/api/ApiListener.java similarity index 100% rename from api/com/speed/irc/event/api/ApiListener.java rename to src/api/com/speed/irc/event/api/ApiListener.java diff --git a/api/com/speed/irc/event/api/ExceptionEvent.java b/src/api/com/speed/irc/event/api/ExceptionEvent.java similarity index 100% rename from api/com/speed/irc/event/api/ExceptionEvent.java rename to src/api/com/speed/irc/event/api/ExceptionEvent.java diff --git a/api/com/speed/irc/event/api/WhoisEvent.java b/src/api/com/speed/irc/event/api/WhoisEvent.java similarity index 100% rename from api/com/speed/irc/event/api/WhoisEvent.java rename to src/api/com/speed/irc/event/api/WhoisEvent.java diff --git a/api/com/speed/irc/event/api/WhoisListener.java b/src/api/com/speed/irc/event/api/WhoisListener.java similarity index 100% rename from api/com/speed/irc/event/api/WhoisListener.java rename to src/api/com/speed/irc/event/api/WhoisListener.java diff --git a/api/com/speed/irc/event/channel/ChannelEvent.java b/src/api/com/speed/irc/event/channel/ChannelEvent.java similarity index 100% rename from api/com/speed/irc/event/channel/ChannelEvent.java rename to src/api/com/speed/irc/event/channel/ChannelEvent.java diff --git a/api/com/speed/irc/event/channel/ChannelEventListener.java b/src/api/com/speed/irc/event/channel/ChannelEventListener.java similarity index 100% rename from api/com/speed/irc/event/channel/ChannelEventListener.java rename to src/api/com/speed/irc/event/channel/ChannelEventListener.java diff --git a/api/com/speed/irc/event/channel/ChannelUserEvent.java b/src/api/com/speed/irc/event/channel/ChannelUserEvent.java similarity index 100% rename from api/com/speed/irc/event/channel/ChannelUserEvent.java rename to src/api/com/speed/irc/event/channel/ChannelUserEvent.java diff --git a/api/com/speed/irc/event/channel/ChannelUserListener.java b/src/api/com/speed/irc/event/channel/ChannelUserListener.java similarity index 100% rename from api/com/speed/irc/event/channel/ChannelUserListener.java rename to src/api/com/speed/irc/event/channel/ChannelUserListener.java diff --git a/api/com/speed/irc/event/channel/ModeChangedEvent.java b/src/api/com/speed/irc/event/channel/ModeChangedEvent.java similarity index 100% rename from api/com/speed/irc/event/channel/ModeChangedEvent.java rename to src/api/com/speed/irc/event/channel/ModeChangedEvent.java diff --git a/api/com/speed/irc/event/channel/TopicChangedEvent.java b/src/api/com/speed/irc/event/channel/TopicChangedEvent.java similarity index 100% rename from api/com/speed/irc/event/channel/TopicChangedEvent.java rename to src/api/com/speed/irc/event/channel/TopicChangedEvent.java diff --git a/api/com/speed/irc/event/generators/JoinGenerator.java b/src/api/com/speed/irc/event/generators/JoinGenerator.java similarity index 100% rename from api/com/speed/irc/event/generators/JoinGenerator.java rename to src/api/com/speed/irc/event/generators/JoinGenerator.java diff --git a/api/com/speed/irc/event/generators/KickGenerator.java b/src/api/com/speed/irc/event/generators/KickGenerator.java similarity index 100% rename from api/com/speed/irc/event/generators/KickGenerator.java rename to src/api/com/speed/irc/event/generators/KickGenerator.java diff --git a/api/com/speed/irc/event/generators/ModeGenerator.java b/src/api/com/speed/irc/event/generators/ModeGenerator.java similarity index 100% rename from api/com/speed/irc/event/generators/ModeGenerator.java rename to src/api/com/speed/irc/event/generators/ModeGenerator.java diff --git a/api/com/speed/irc/event/generators/NoticeGenerator.java b/src/api/com/speed/irc/event/generators/NoticeGenerator.java similarity index 100% rename from api/com/speed/irc/event/generators/NoticeGenerator.java rename to src/api/com/speed/irc/event/generators/NoticeGenerator.java diff --git a/api/com/speed/irc/event/generators/PartGenerator.java b/src/api/com/speed/irc/event/generators/PartGenerator.java similarity index 100% rename from api/com/speed/irc/event/generators/PartGenerator.java rename to src/api/com/speed/irc/event/generators/PartGenerator.java diff --git a/api/com/speed/irc/event/generators/PrivmsgGenerator.java b/src/api/com/speed/irc/event/generators/PrivmsgGenerator.java similarity index 100% rename from api/com/speed/irc/event/generators/PrivmsgGenerator.java rename to src/api/com/speed/irc/event/generators/PrivmsgGenerator.java diff --git a/api/com/speed/irc/event/generators/WhoisGenerator.java b/src/api/com/speed/irc/event/generators/WhoisGenerator.java similarity index 100% rename from api/com/speed/irc/event/generators/WhoisGenerator.java rename to src/api/com/speed/irc/event/generators/WhoisGenerator.java diff --git a/api/com/speed/irc/event/message/NoticeEvent.java b/src/api/com/speed/irc/event/message/NoticeEvent.java similarity index 100% rename from api/com/speed/irc/event/message/NoticeEvent.java rename to src/api/com/speed/irc/event/message/NoticeEvent.java diff --git a/api/com/speed/irc/event/message/NoticeListener.java b/src/api/com/speed/irc/event/message/NoticeListener.java similarity index 100% rename from api/com/speed/irc/event/message/NoticeListener.java rename to src/api/com/speed/irc/event/message/NoticeListener.java diff --git a/api/com/speed/irc/event/message/PrivateMessageEvent.java b/src/api/com/speed/irc/event/message/PrivateMessageEvent.java similarity index 100% rename from api/com/speed/irc/event/message/PrivateMessageEvent.java rename to src/api/com/speed/irc/event/message/PrivateMessageEvent.java diff --git a/api/com/speed/irc/event/message/PrivateMessageListener.java b/src/api/com/speed/irc/event/message/PrivateMessageListener.java similarity index 100% rename from api/com/speed/irc/event/message/PrivateMessageListener.java rename to src/api/com/speed/irc/event/message/PrivateMessageListener.java diff --git a/api/com/speed/irc/event/message/RawMessageEvent.java b/src/api/com/speed/irc/event/message/RawMessageEvent.java similarity index 100% rename from api/com/speed/irc/event/message/RawMessageEvent.java rename to src/api/com/speed/irc/event/message/RawMessageEvent.java diff --git a/api/com/speed/irc/event/message/RawMessageListener.java b/src/api/com/speed/irc/event/message/RawMessageListener.java similarity index 100% rename from api/com/speed/irc/event/message/RawMessageListener.java rename to src/api/com/speed/irc/event/message/RawMessageListener.java diff --git a/api/com/speed/irc/framework/Bot.java b/src/api/com/speed/irc/framework/Bot.java similarity index 100% rename from api/com/speed/irc/framework/Bot.java rename to src/api/com/speed/irc/framework/Bot.java diff --git a/api/com/speed/irc/framework/test/GraphicalUserList.java b/src/api/com/speed/irc/framework/test/GraphicalUserList.java similarity index 100% rename from api/com/speed/irc/framework/test/GraphicalUserList.java rename to src/api/com/speed/irc/framework/test/GraphicalUserList.java diff --git a/api/com/speed/irc/framework/test/HelloBot.java b/src/api/com/speed/irc/framework/test/HelloBot.java similarity index 100% rename from api/com/speed/irc/framework/test/HelloBot.java rename to src/api/com/speed/irc/framework/test/HelloBot.java diff --git a/api/com/speed/irc/types/Bot.java b/src/api/com/speed/irc/types/Bot.java similarity index 100% rename from api/com/speed/irc/types/Bot.java rename to src/api/com/speed/irc/types/Bot.java diff --git a/api/com/speed/irc/types/CTCPReply.java b/src/api/com/speed/irc/types/CTCPReply.java similarity index 100% rename from api/com/speed/irc/types/CTCPReply.java rename to src/api/com/speed/irc/types/CTCPReply.java diff --git a/api/com/speed/irc/types/Channel.java b/src/api/com/speed/irc/types/Channel.java similarity index 100% rename from api/com/speed/irc/types/Channel.java rename to src/api/com/speed/irc/types/Channel.java diff --git a/api/com/speed/irc/types/ChannelUser.java b/src/api/com/speed/irc/types/ChannelUser.java similarity index 100% rename from api/com/speed/irc/types/ChannelUser.java rename to src/api/com/speed/irc/types/ChannelUser.java diff --git a/api/com/speed/irc/types/Conversable.java b/src/api/com/speed/irc/types/Conversable.java similarity index 100% rename from api/com/speed/irc/types/Conversable.java rename to src/api/com/speed/irc/types/Conversable.java diff --git a/api/com/speed/irc/types/Mask.java b/src/api/com/speed/irc/types/Mask.java similarity index 100% rename from api/com/speed/irc/types/Mask.java rename to src/api/com/speed/irc/types/Mask.java diff --git a/api/com/speed/irc/types/Mode.java b/src/api/com/speed/irc/types/Mode.java similarity index 100% rename from api/com/speed/irc/types/Mode.java rename to src/api/com/speed/irc/types/Mode.java diff --git a/api/com/speed/irc/types/ModeList.java b/src/api/com/speed/irc/types/ModeList.java similarity index 100% rename from api/com/speed/irc/types/ModeList.java rename to src/api/com/speed/irc/types/ModeList.java diff --git a/api/com/speed/irc/types/Notice.java b/src/api/com/speed/irc/types/Notice.java similarity index 96% rename from api/com/speed/irc/types/Notice.java rename to src/api/com/speed/irc/types/Notice.java index b36d34d..60e81ef 100644 --- a/api/com/speed/irc/types/Notice.java +++ b/src/api/com/speed/irc/types/Notice.java @@ -20,7 +20,7 @@ * for more details. *

* You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see {@link http://www.gnu.org/licenses/}. + * along with Speed's IRC API. If not, see {@linkplain http://www.gnu.org/licenses/}. * * @author Shivam Mistry */ diff --git a/api/com/speed/irc/types/ParsingException.java b/src/api/com/speed/irc/types/ParsingException.java similarity index 100% rename from api/com/speed/irc/types/ParsingException.java rename to src/api/com/speed/irc/types/ParsingException.java diff --git a/api/com/speed/irc/types/Privmsg.java b/src/api/com/speed/irc/types/Privmsg.java similarity index 100% rename from api/com/speed/irc/types/Privmsg.java rename to src/api/com/speed/irc/types/Privmsg.java diff --git a/api/com/speed/irc/types/RawMessage.java b/src/api/com/speed/irc/types/RawMessage.java similarity index 100% rename from api/com/speed/irc/types/RawMessage.java rename to src/api/com/speed/irc/types/RawMessage.java diff --git a/api/com/speed/irc/types/ServerUser.java b/src/api/com/speed/irc/types/ServerUser.java similarity index 100% rename from api/com/speed/irc/types/ServerUser.java rename to src/api/com/speed/irc/types/ServerUser.java diff --git a/api/com/speed/irc/types/Whois.java b/src/api/com/speed/irc/types/Whois.java similarity index 100% rename from api/com/speed/irc/types/Whois.java rename to src/api/com/speed/irc/types/Whois.java diff --git a/api/com/speed/irc/util/ControlCodeFormatter.java b/src/api/com/speed/irc/util/ControlCodeFormatter.java similarity index 100% rename from api/com/speed/irc/util/ControlCodeFormatter.java rename to src/api/com/speed/irc/util/ControlCodeFormatter.java diff --git a/api/com/speed/irc/util/Numerics.java b/src/api/com/speed/irc/util/Numerics.java similarity index 100% rename from api/com/speed/irc/util/Numerics.java rename to src/api/com/speed/irc/util/Numerics.java From 7647f40803efd81824597f53c5cfe9f9d583e317 Mon Sep 17 00:00:00 2001 From: ShivamMistry Date: Sun, 18 May 2014 00:04:40 +0100 Subject: [PATCH 4/4] add git submodules --- .gitmodules | 3 + lib/api | 1 + pom.xml | 2 +- src/api/com/speed/irc/connection/Server.java | 657 ------------------ .../irc/connection/ServerMessageParser.java | 324 --------- .../irc/connection/ServerMessageReader.java | 118 ---- .../irc/connection/ServerSupportParser.java | 96 --- .../irc/connection/ssl/IRCTrustManager.java | 43 -- .../com/speed/irc/event/EventGenerator.java | 44 -- src/api/com/speed/irc/event/EventManager.java | 95 --- src/api/com/speed/irc/event/IRCEvent.java | 38 - .../com/speed/irc/event/IRCEventListener.java | 26 - .../speed/irc/event/ListenerProperties.java | 30 - src/api/com/speed/irc/event/api/ApiEvent.java | 73 -- .../com/speed/irc/event/api/ApiListener.java | 28 - .../speed/irc/event/api/ExceptionEvent.java | 38 - .../com/speed/irc/event/api/WhoisEvent.java | 57 -- .../speed/irc/event/api/WhoisListener.java | 31 - .../speed/irc/event/channel/ChannelEvent.java | 162 ----- .../event/channel/ChannelEventListener.java | 32 - .../irc/event/channel/ChannelUserEvent.java | 61 -- .../event/channel/ChannelUserListener.java | 40 -- .../irc/event/channel/ModeChangedEvent.java | 85 --- .../irc/event/channel/TopicChangedEvent.java | 37 - .../irc/event/generators/JoinGenerator.java | 60 -- .../irc/event/generators/KickGenerator.java | 54 -- .../irc/event/generators/ModeGenerator.java | 145 ---- .../irc/event/generators/NoticeGenerator.java | 58 -- .../irc/event/generators/PartGenerator.java | 53 -- .../event/generators/PrivmsgGenerator.java | 75 -- .../irc/event/generators/WhoisGenerator.java | 60 -- .../speed/irc/event/message/NoticeEvent.java | 52 -- .../irc/event/message/NoticeListener.java | 31 - .../event/message/PrivateMessageEvent.java | 57 -- .../event/message/PrivateMessageListener.java | 30 - .../irc/event/message/RawMessageEvent.java | 54 -- .../irc/event/message/RawMessageListener.java | 31 - src/api/com/speed/irc/framework/Bot.java | 166 ----- .../irc/framework/test/GraphicalUserList.java | 95 --- .../speed/irc/framework/test/HelloBot.java | 190 ----- src/api/com/speed/irc/types/Bot.java | 116 ---- src/api/com/speed/irc/types/CTCPReply.java | 53 -- src/api/com/speed/irc/types/Channel.java | 488 ------------- src/api/com/speed/irc/types/ChannelUser.java | 153 ---- src/api/com/speed/irc/types/Conversable.java | 76 -- src/api/com/speed/irc/types/Mask.java | 85 --- src/api/com/speed/irc/types/Mode.java | 51 -- src/api/com/speed/irc/types/ModeList.java | 94 --- src/api/com/speed/irc/types/Notice.java | 101 --- .../com/speed/irc/types/ParsingException.java | 58 -- src/api/com/speed/irc/types/Privmsg.java | 98 --- src/api/com/speed/irc/types/RawMessage.java | 92 --- src/api/com/speed/irc/types/ServerUser.java | 195 ------ src/api/com/speed/irc/types/Whois.java | 96 --- .../speed/irc/util/ControlCodeFormatter.java | 173 ----- src/api/com/speed/irc/util/Numerics.java | 42 -- 56 files changed, 5 insertions(+), 5298 deletions(-) create mode 100644 .gitmodules create mode 160000 lib/api delete mode 100755 src/api/com/speed/irc/connection/Server.java delete mode 100644 src/api/com/speed/irc/connection/ServerMessageParser.java delete mode 100644 src/api/com/speed/irc/connection/ServerMessageReader.java delete mode 100644 src/api/com/speed/irc/connection/ServerSupportParser.java delete mode 100644 src/api/com/speed/irc/connection/ssl/IRCTrustManager.java delete mode 100644 src/api/com/speed/irc/event/EventGenerator.java delete mode 100755 src/api/com/speed/irc/event/EventManager.java delete mode 100755 src/api/com/speed/irc/event/IRCEvent.java delete mode 100755 src/api/com/speed/irc/event/IRCEventListener.java delete mode 100644 src/api/com/speed/irc/event/ListenerProperties.java delete mode 100644 src/api/com/speed/irc/event/api/ApiEvent.java delete mode 100644 src/api/com/speed/irc/event/api/ApiListener.java delete mode 100644 src/api/com/speed/irc/event/api/ExceptionEvent.java delete mode 100644 src/api/com/speed/irc/event/api/WhoisEvent.java delete mode 100644 src/api/com/speed/irc/event/api/WhoisListener.java delete mode 100644 src/api/com/speed/irc/event/channel/ChannelEvent.java delete mode 100644 src/api/com/speed/irc/event/channel/ChannelEventListener.java delete mode 100644 src/api/com/speed/irc/event/channel/ChannelUserEvent.java delete mode 100644 src/api/com/speed/irc/event/channel/ChannelUserListener.java delete mode 100644 src/api/com/speed/irc/event/channel/ModeChangedEvent.java delete mode 100644 src/api/com/speed/irc/event/channel/TopicChangedEvent.java delete mode 100644 src/api/com/speed/irc/event/generators/JoinGenerator.java delete mode 100644 src/api/com/speed/irc/event/generators/KickGenerator.java delete mode 100644 src/api/com/speed/irc/event/generators/ModeGenerator.java delete mode 100644 src/api/com/speed/irc/event/generators/NoticeGenerator.java delete mode 100644 src/api/com/speed/irc/event/generators/PartGenerator.java delete mode 100644 src/api/com/speed/irc/event/generators/PrivmsgGenerator.java delete mode 100644 src/api/com/speed/irc/event/generators/WhoisGenerator.java delete mode 100755 src/api/com/speed/irc/event/message/NoticeEvent.java delete mode 100755 src/api/com/speed/irc/event/message/NoticeListener.java delete mode 100755 src/api/com/speed/irc/event/message/PrivateMessageEvent.java delete mode 100755 src/api/com/speed/irc/event/message/PrivateMessageListener.java delete mode 100755 src/api/com/speed/irc/event/message/RawMessageEvent.java delete mode 100755 src/api/com/speed/irc/event/message/RawMessageListener.java delete mode 100644 src/api/com/speed/irc/framework/Bot.java delete mode 100644 src/api/com/speed/irc/framework/test/GraphicalUserList.java delete mode 100644 src/api/com/speed/irc/framework/test/HelloBot.java delete mode 100644 src/api/com/speed/irc/types/Bot.java delete mode 100644 src/api/com/speed/irc/types/CTCPReply.java delete mode 100755 src/api/com/speed/irc/types/Channel.java delete mode 100755 src/api/com/speed/irc/types/ChannelUser.java delete mode 100644 src/api/com/speed/irc/types/Conversable.java delete mode 100644 src/api/com/speed/irc/types/Mask.java delete mode 100644 src/api/com/speed/irc/types/Mode.java delete mode 100644 src/api/com/speed/irc/types/ModeList.java delete mode 100644 src/api/com/speed/irc/types/Notice.java delete mode 100644 src/api/com/speed/irc/types/ParsingException.java delete mode 100644 src/api/com/speed/irc/types/Privmsg.java delete mode 100755 src/api/com/speed/irc/types/RawMessage.java delete mode 100644 src/api/com/speed/irc/types/ServerUser.java delete mode 100644 src/api/com/speed/irc/types/Whois.java delete mode 100644 src/api/com/speed/irc/util/ControlCodeFormatter.java delete mode 100755 src/api/com/speed/irc/util/Numerics.java diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..81fbf9c --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "lib/api"] + path = lib/api + url = git@github.com:ShivamMistry/speedsircapi diff --git a/lib/api b/lib/api new file mode 160000 index 0000000..674a60b --- /dev/null +++ b/lib/api @@ -0,0 +1 @@ +Subproject commit 674a60bc4589d945ac169f3c153933098eee2a56 diff --git a/pom.xml b/pom.xml index 45a8285..bf441b3 100644 --- a/pom.xml +++ b/pom.xml @@ -97,7 +97,7 @@ - src/api + lib/api/src diff --git a/src/api/com/speed/irc/connection/Server.java b/src/api/com/speed/irc/connection/Server.java deleted file mode 100755 index d7328a0..0000000 --- a/src/api/com/speed/irc/connection/Server.java +++ /dev/null @@ -1,657 +0,0 @@ -package com.speed.irc.connection; - -import com.speed.irc.connection.ssl.IRCTrustManager; -import com.speed.irc.event.EventManager; -import com.speed.irc.event.api.ApiEvent; -import com.speed.irc.types.*; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.TrustManager; -import java.io.*; -import java.net.Socket; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.security.GeneralSecurityException; -import java.security.SecureRandom; -import java.util.*; -import java.util.concurrent.*; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * A class representing a socket connection to an IRC server with the - * functionality of sending raw commands and messages. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class Server implements Runnable { - private volatile BufferedWriter write; - private volatile BufferedReader read; - protected volatile Socket socket; - protected EventManager eventManager = new EventManager(); - protected Map channels = new HashMap(); - private static SSLContext context; - private List users; - private char[] modeSymbols; - private char[] channelPrefix; - private char[] modeLetters; - private String serverName; - private String nick, realName, user; - private ServerMessageParser parser; - protected HashSet ctcpReplies = new HashSet(); - public Map> whoisWaiting = new HashMap>(); - protected boolean autoConnect; - private int port; - private ScheduledThreadPoolExecutor chanExec; - private ScheduledExecutorService serverExecutor, eventExecutor; - private ModeList userModes; - - /** - * Initialises a server object. Only blocking IO is supported. - * - * @param sock The socket used for communication to the IRC server. - * @throws IOException - */ - public Server(final Socket sock) throws IOException { - socket = sock; - port = sock.getPort(); - setServerName(socket.getRemoteSocketAddress().toString()); - write = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); - read = new BufferedReader(new InputStreamReader(sock.getInputStream())); - chanExec = new ScheduledThreadPoolExecutor(10); - serverExecutor = Executors.newSingleThreadScheduledExecutor(); - eventExecutor = Executors.newSingleThreadScheduledExecutor(); - serverExecutor.scheduleWithFixedDelay(this, 1000, 200, TimeUnit.MILLISECONDS); - eventExecutor.scheduleWithFixedDelay(eventManager, 1000, 100, TimeUnit.MILLISECONDS); - parser = new ServerMessageParser(this); - users = new CopyOnWriteArrayList(); - ctcpReplies.add(ServerMessageParser.CTCP_REPLY_VERSION); - ctcpReplies.add(ServerMessageParser.CTCP_REPLY_TIME); - ctcpReplies.add(ServerMessageParser.CTCP_REPLY_PING); - } - - public Server(final String host, final int port) throws IOException { - this(new Socket(host, port)); - - } - - public Server(final String host, final int port, final boolean ssl) throws IOException { - this(ssl ? context.getSocketFactory().createSocket(host, port) : new Socket(host, port)); - } - - static { - try { - context = SSLContext.getInstance("SSL"); - context.init(new KeyManager[0], new TrustManager[]{new IRCTrustManager()}, new SecureRandom()); - } catch (GeneralSecurityException e) { - e.printStackTrace(); - } - } - - public void parseUserModes(final String modes) { - userModes.parse(modes); - } - - public ModeList getUserModes() { - return userModes; - } - - public boolean isUsingSSL() { - return socket instanceof SSLSocket; - } - - public SSLSocket getSSLSocket() { - return isUsingSSL() ? (SSLSocket) socket : null; - } - - public String getRealName() { - return realName; - } - - public String getUser() { - return user; - } - - /** - * Gets the channel thread executor, used to send WHO requests for channels. - * - * @return the channel thread executor - */ - public ScheduledThreadPoolExecutor getChanExec() { - return chanExec; - } - - /** - * Sends a QUIT command (with no message) to the server and shuts down this - * server connection. - */ - public void quit() { - quit(null); - } - - public void setNick(final String newNick) { - sendRaw("NICK " + newNick); - } - - protected void putNick(final String nick) { - this.nick = nick; - } - - public void register(final String nick) { - register(nick, null, null, null); - } - - public void register(final String nick, final String user) { - register(nick, user, null, null); - } - - public void register(final String nick, final String user, final String realName) { - register(nick, user, realName, null); - } - - public void register(final String nick, String user, String realName, final String pass) { - if (nick == null || nick.isEmpty()) { - quit(); - throw new IllegalArgumentException("Nickname is null or empty"); - } - if (pass != null && !pass.isEmpty()) { - sendRaw("PASS " + pass); - } - if (user == null || user.isEmpty()) { - user = nick; - } - if (realName == null || realName.isEmpty()) { - realName = user; - } - setNick(nick); - sendRaw("USER " + user + " 0 * :" + realName); - this.nick = nick; - this.realName = realName; - this.user = user; - } - - /** - * Sends a QUIT command to the server and shuts down this server connection. - * - * @param message the quit message to send to the server, null or - * "" for no message - */ - public void quit(final String message) { - eventManager.dispatchEvent(new ApiEvent(ApiEvent.SERVER_QUIT, this, this)); - parser.reader.running = false; - try { - if (!socket.isClosed()) { - getWriter().write( - "QUIT" + (message == null || message.trim().isEmpty() ? "\n" : (" :" + message + "\n"))); - getWriter().flush(); - socket.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - try { - Thread.sleep(1000); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - for (Channel c : channels.values()) { - if (c.getFuture() != null && !c.getFuture().isDone()) - c.getFuture().cancel(true); - } - try { - socket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - eventExecutor.shutdownNow(); - parser.execServ.shutdownNow(); - chanExec.shutdownNow(); - serverExecutor.shutdownNow(); - } - - /** - * Sets the logger to log debug output to and turns debugging on. - * - * @param logger the logger to log output to. - */ - public final void setReadDebug(final Logger logger) { - parser.reader.logger = logger; - setReadDebug(true); - } - - /** - * Controls whether the API should log debug output. - * - * @param on true to enable debug output, false otherwise - */ - public final void setReadDebug(boolean on) { - parser.reader.logging = on; - } - - protected final void connect() { - try { - socket = new Socket(serverName, port); - write = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); - read = new BufferedReader(new InputStreamReader(socket.getInputStream())); - Logger logger = null; - boolean log = false; - if (parser.reader.logging) { - logger = parser.reader.logger; - log = parser.reader.logging; - } - parser = new ServerMessageParser(this); - if (logger != null && log) { - setReadDebug(logger); - } - } catch (UnknownHostException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public ServerMessageParser getParser() { - return parser; - } - - public CTCPReply getCtcp(String request) { - synchronized (ctcpReplies) { - for (CTCPReply reply : ctcpReplies) { - if (reply.getRequest().equals(request)) { - return reply; - } - } - } - return null; - } - - /** - * Sets whether the api should auto reconnect if the connection is broken. - * Default is off. - * - * @param on - */ - public void setAutoReconnect(final boolean on) { - this.autoConnect = on; - } - - /** - * Gets the current nick as captured by the message sending thread. - * - * @return the current nick for this server connection. - */ - public String getNick() { - return nick; - } - - /** - * Sets a reply to a CTCP request. - * - * @param request the request to send the reply for - * @param reply the reply to send for the request - */ - public void setCtcpReply(final String request, final String reply) { - synchronized (ctcpReplies) { - ctcpReplies.add(new CTCPReply() { - - public String getReply() { - return reply; - } - - public String getRequest() { - return request; - } - - }); - } - } - - public void removeCtcpReply(final CTCPReply reply) { - synchronized (ctcpReplies) { - ctcpReplies.remove(reply); - } - } - - /** - * Adds an automated CTCP reply to the reply list. - * - * @param reply the CTCPReply to be added to the list - */ - public void addCtcpReply(final CTCPReply reply) { - synchronized (ctcpReplies) { - ctcpReplies.add(reply); - } - } - - /** - * Gets the reply which corresponds to the request. - * - * @param request the request to retrieve the reply for - * @return the reply for the supplied request - */ - public String getCtcpReply(final String request) { - synchronized (ctcpReplies) { - for (CTCPReply reply : ctcpReplies) { - Matcher matcher = Pattern.compile(reply.getRequest(), Pattern.CASE_INSENSITIVE).matcher(request); - if (matcher.matches()) { - if (matcher.groupCount() == 0) - return reply.getReply(); - else { - String resp = reply.getReply(); - StringBuffer response = new StringBuffer(); - boolean flag = false; - for (int i = 0; i < resp.length(); i++) { - char c = resp.charAt(i); - if (c == '$' && (i == 0 || resp.charAt(i - 1) != '\\')) { - flag = true; - continue; - } else if (resp.charAt(i - 1) == '\\') { - response.deleteCharAt(i - 1); - } else if (Character.isDigit(c) && flag) { - int group = Character.getNumericValue(c); - flag = false; - try { - String str = matcher.group(group); - response.append(str); - } catch (IndexOutOfBoundsException e) { - e.printStackTrace(); - } - continue; - - } - response.append(c); - - } - return response.toString(); - } - } - } - } - return null; - } - - /** - * Sends a raw command to the server. - * - * @param raw The raw command to be added to the sending queue. - */ - public void sendRaw(String raw) { - if (raw.startsWith("NICK")) { - nick = raw.replace("NICK", "").replace(":", "").trim(); - } - if ((raw.contains("\n") || raw.contains("\r")) && !raw.endsWith("\r\n")) - raw = raw.replace("\n", "").replace("\r", ""); - if (!raw.endsWith("\r\n")) - raw += "\r\n"; - try { - // System.out.println(raw); - write.write(raw); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Gets the channel map. - * - * @return the channel map. - */ - protected Map getChannelMap() { - return channels; - } - - public Collection getChannels() { - return channels.values(); - } - - public void addChannel(final Channel channel) { - channels.put(channel.getName().toLowerCase(), channel); - } - - /** - * Gets the buffered writer. - * - * @return the buffered writer. - */ - public BufferedWriter getWriter() { - return write; - } - - /** - * Sets the buffered writer. - * - * @param write the new buffered writer. - */ - public void setWrite(final BufferedWriter write) { - this.write = write; - } - - /** - * Gets the buffered reader. - * - * @return the buffered reader. - */ - public BufferedReader getReader() { - return read; - } - - /** - * Sets the buffered reader. - * - * @param read the new buffered reader. - */ - public void setRead(final BufferedReader read) { - this.read = read; - } - - /** - * Checks whether the api is connected to the server. - * - * @return true if we are connected, false if - * unconnected. - */ - public boolean isConnected() { - return !socket.isClosed(); - } - - /** - * Gets the channel access mode symbols (e.g. @ for op) - * - * @return the channel access mode symbols. - */ - public char[] getModeSymbols() { - return modeSymbols; - } - - protected void setModeSymbols(final char[] modeSymbols) { - this.modeSymbols = modeSymbols; - } - - /** - * Gets the channel access mode letters (e.g. v for voice) - * - * @return the channel access mode letters - */ - public char[] getModeLetters() { - return modeLetters; - } - - protected void setModeLetters(final char[] modeLetters) { - this.modeLetters = modeLetters; - } - - /** - * Sends a notice to the specified nick. - * - * @param notice the notice to send, sender can be null. - */ - public void sendNotice(final Notice notice) { - sendRaw("NOTICE " + notice.getTarget() + " :" + notice.getMessage() + "\n"); - } - - /** - * Sends a private message to the server. - * - * @param msg the message to send, sender can be null. - */ - public void sendMessage(final Privmsg msg) { - sendRaw(String.format("PRIVMSG %s :%s", msg.getConversable().getName(), msg.getMessage())); - } - - /** - * Gets a server user object with a supplied nickname. - * - * @param nick the nickname to search for - * @return the ServerUser object, creates a new object if the user wasn't - * found. - */ - public ServerUser getUser(final String nick) { - for (ServerUser u : users) { - if (u.getNick().equalsIgnoreCase(nick)) - return u; - } - return new ServerUser(nick, null, null, this); - } - - /** - * Sends an action to a channel/nick. - * - * @param channel The specified channel/nick you would like to send the action - * to. - * @param action The action you would like to send. - */ - public void sendAction(final String channel, final String action) { - sendRaw("PRIVMSG " + channel + ": \u0001ACTION " + action + "\n"); - } - - /** - * Gets the event manager associated with this server object. - * - * @return the event manager for this server. - */ - public EventManager getEventManager() { - return eventManager; - } - - public void run() { - try { - if (write != null) { - write.flush(); - } - } catch (SocketException e) { - if (autoConnect) { - try { - Thread.sleep(5000); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - try { - socket.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - connect(); - eventManager.dispatchEvent(new ApiEvent(ApiEvent.SERVER_DISCONNECTED, this, this)); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - - /** - * Sets the server's host address. - * - * @param serverName the server's host address. - */ - public void setServerName(String serverName) { - this.serverName = serverName; - } - - /** - * Gets the server's host address. - * - * @return the server's host address. - */ - public String getServerName() { - return serverName; - } - - /** - * Joins a channel on this server if we are not already joined to it. - * - * @param channelName The name of the channel. - * @return The channel object. - */ - public Channel joinChannel(final String channelName) { - if (channels.containsKey(channelName.trim())) { - final Channel channel = channels.get(channelName.toLowerCase()); - if (!channel.isRunning()) { - channel.join(); - } - return channel; - } - final Channel channel = new Channel(channelName, this); - channel.join(); - return channel; - } - - /** - * Creates/finds a channel object for the specified channel. - * - * @param channelName the name of the channel. - * @return a channel object. - */ - public Channel getChannel(final String channelName) { - return channels.containsKey(channelName.toLowerCase().trim()) ? channels.get(channelName) : new Channel( - channelName, this); - } - - /** - * Adds a user to the Server's list. - * - * @param user the {@link com.speed.irc.types.ServerUser} object to add to - * this Server. - */ - public void addUser(final ServerUser user) { - users.add(user); - } - - protected void removeUser(final ServerUser user) { - users.remove(user); - } - - public boolean hasChannel(final String name) { - return channels.containsKey(name.toLowerCase()); - } - - public boolean hasChannel(final Channel channel) { - return channels.containsValue(channel); - } - - public void addWhoisWaiting(final ServerUser c) { - whoisWaiting.put(c, new LinkedList()); - } - - public char[] getChannelPrefix() { - return parser.getServerSupport().getChanTypes(); - } -} diff --git a/src/api/com/speed/irc/connection/ServerMessageParser.java b/src/api/com/speed/irc/connection/ServerMessageParser.java deleted file mode 100644 index 838f01b..0000000 --- a/src/api/com/speed/irc/connection/ServerMessageParser.java +++ /dev/null @@ -1,324 +0,0 @@ -package com.speed.irc.connection; - -import com.speed.irc.event.EventGenerator; -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.channel.ChannelUserEvent; -import com.speed.irc.event.channel.TopicChangedEvent; -import com.speed.irc.event.generators.*; -import com.speed.irc.event.message.RawMessageEvent; -import com.speed.irc.types.*; -import com.speed.irc.util.Numerics; - -import java.util.Date; -import java.util.List; -import java.util.concurrent.*; - -/** - * Processes messages sent from the server. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ServerMessageParser implements Runnable, EventGenerator { - private final Server server; - private List generators; - protected ServerMessageReader reader; - protected ScheduledExecutorService execServ; - protected Future future; - private ServerSupportParser serverSupport; - - public static final CTCPReply CTCP_REPLY_VERSION = new CTCPReply() { - - public String getReply() { - return "Speed's IRC API"; - } - - public String getRequest() { - return "VERSION"; - } - - }; - - public static final CTCPReply CTCP_REPLY_TIME = new CTCPReply() { - - public String getReply() { - return new Date().toString(); - } - - public String getRequest() { - return "TIME"; - } - - }; - - public static final CTCPReply CTCP_REPLY_PING = new CTCPReply() { - - public String getReply() { - return ""; - } - - public String getRequest() { - return "PING (.*)"; - } - - }; - - public ServerMessageParser(final Server server) { - this.server = server; - generators = new CopyOnWriteArrayList(); - generators.add(this); - generators.add(new JoinGenerator()); - generators.add(new KickGenerator()); - generators.add(new ModeGenerator()); - generators.add(new NoticeGenerator(server)); - generators.add(new PartGenerator()); - generators.add(new PrivmsgGenerator()); - generators.add(new WhoisGenerator(server)); - reader = new ServerMessageReader(server); - execServ = Executors.newSingleThreadScheduledExecutor(); - new Thread(reader, "Server message reader").start(); - future = execServ.scheduleWithFixedDelay(this, 0, 20, - TimeUnit.MILLISECONDS); - serverSupport = new ServerSupportParser(); - } - - private synchronized void parse(final String s) throws Exception { - final RawMessage message = new RawMessage(s, server); - for (EventGenerator generator : generators) { - if (generator.accept(message)) { - IRCEvent event = generator.generate(message); - if (event != null) - server.eventManager.dispatchEvent(event); - } - } - server.eventManager.dispatchEvent(new RawMessageEvent(message, this)); - - } - - /** - * Submits an event generator to this parser - * - * @param generator generator to add - */ - public void addGenerator(final EventGenerator generator) { - if (!generators.contains(generator)) - generators.add(generator); - } - - /** - * Removes a generator from this serverSupport - * - * @param generator the generator to remove - * @return true if it was removed, false if it failed to be removed - */ - public boolean removeGenerator(final EventGenerator generator) { - return generators.remove(generator); - } - - public void run() { - String s; - if (!reader.isEmpty()) { - s = reader.poll(); - if (s.matches("\\W.+")) - s = s.substring(1); - try { - parse(s); - } catch (Exception e) { - server.eventManager - .dispatchEvent(new com.speed.irc.event.api.ExceptionEvent(new ParsingException( - "Parsing error", e), this, server)); - } - } - - } - - public boolean accept(RawMessage message) { - return message != null; - } - - public IRCEvent generate(RawMessage message) { - String raw = message.getRaw(); - String code = message.getCommand().trim(); - if (raw.startsWith("PING")) { - server.sendRaw(raw.replaceFirst("PING", "PONG") + "\n"); - } else if (message.getCommand().equals(Numerics.SERVER_SUPPORT)) { - serverSupport.parse(message); - if (serverSupport.getSettings().containsKey("PREFIX")) { - String t = serverSupport.getSettings().getProperty("PREFIX"); - String letters = t.split("\\(", 2)[1].split("\\)")[0]; - String symbols = t.split("\\)", 2)[1]; - if (letters.length() == symbols.length()) { - server.setModeLetters(letters.toCharArray()); - server.setModeSymbols(symbols.toCharArray()); - } - } - } else if (code.equals(Numerics.CHANNEL_MODES)) { - String chan_name = message.getRaw().split(" ")[3]; - String modez = message.getRaw().split(" ")[4]; - if (!server.channels.containsKey(chan_name)) { - return null; - } - Channel channel = server.channels.get(chan_name); - channel.chanModeList.parse(modez); - } else if (code.equals(Numerics.CHANNEL_NAMES)) { - String[] parts = message.getRaw().split(" "); - // String secret = parts[3]; - String chan_name = parts[4]; - String users = message.getRaw().split(" :")[1]; - if (!server.channels.containsKey(chan_name)) { - return null; - } - Channel channel = server.channels.get(chan_name); - if (channel.isRunning()) { - for (String s : users.split(" ")) { - if (s.matches("[A-Za-z].*")) { - channel.userBuffer.add(new ChannelUser(s, "", "", "", - channel)); - } else { - char c = s.charAt(0); - channel.userBuffer.add(new ChannelUser(s.substring(1), - Character.toString(c), "", "", channel)); - } - } - } - } else if (code.equals(Numerics.CHANNEL_NAMES_END)) { - Channel channel = server.channels.get(raw.split(" ")[3]); - channel.getUsers().clear(); - channel.getUsers().addAll(channel.userBuffer); - channel.userBuffer.clear(); - } else if (code.equals(Numerics.WHO_RESPONSE)) { - Channel channel = server.channels.get(raw.split(" ")[3]); - String[] temp = raw.split(" "); - String user = temp[4]; - String host = temp[5]; - String nick = temp[7]; - String modes = temp[8]; - boolean away = modes.contains("G"); - boolean oper = modes.contains("*"); - boolean identified = modes.contains("r"); - modes = modes.replaceAll("[A-Za-z]", "").replace("*", ""); - ChannelUser u = new ChannelUser(nick, modes, user, host, channel); - u.setIdentified(identified); - u.setAway(away); - u.setOper(oper); - channel.userBuffer.add(u); - - } else if (code.equals(Numerics.WHO_END)) { - Channel channel = server.channels.get(raw.split(" ")[3]); - channel.users.clear(); - channel.users.addAll(channel.userBuffer); - channel.userBuffer.clear(); - } else if (code.toLowerCase().equals("topic")) { - Channel channel = server.getChannel(raw.split(" ")[2]); - if (!channel.isRunning()) { - channel.setup(); - } - String topicSetter = raw.split(" ")[0]; - long time = System.currentTimeMillis(); - String oldTopic = channel.getTopic(); - channel.setTopicSetter(topicSetter); - channel.setTopicSetTime(time); - String[] temp = raw.split(" :", 2); - channel.setTopic(temp[1]); - if (temp[0].substring(temp[0].indexOf("TOPIC")).contains( - channel.getName())) { - return new TopicChangedEvent(channel, topicSetter, this, new String[]{oldTopic, temp[1]}); - } - } else if (code.equals(Numerics.BANNED_FROM_CHANNEL) - && message.getTarget().equals(server.getNick())) { - Channel channel = server.channels.get(raw.split(" ")[3]); - if (channel != null && channel.isRunning()) - channel.isRunning = false; - } else if (code.equals("QUIT")) { - String nick = raw.split("!")[0]; - String quitMsg = ""; - String[] parts = raw.split(" :", 2); - if (parts.length > 1) { - quitMsg = parts[1]; - } - for (Channel c : server.getChannels()) { - if (c.isRunning && c.getUser(nick) != null) { - server.eventManager.dispatchEvent(new ChannelUserEvent( - this, c, c.getUser(nick), - ChannelUserEvent.USER_QUIT, quitMsg)); - } - } - } else if (code.trim().equalsIgnoreCase("nick")) { - try { - final ServerUser u = server.getUser(message.getSender().split( - "!")[0]); - final String oldNick = u.getNick(); - final String newNick = raw.split(" :")[1].trim(); - if (oldNick.equals(server.getNick())) { - server.putNick(newNick); - } - - if (u instanceof ChannelUser) { - return new ChannelUserEvent(this, - u.getChannel(), (ChannelUser) u, - ChannelUserEvent.USER_NICK_CHANGED, oldNick, newNick); - } else { - // this user is not in a channel, so we need to recreate the - // object - ServerUser n_u = new ServerUser(newNick, u.getHost(), - u.getUser(), server); - server.removeUser(u); - server.addUser(n_u); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - parseNumerics(message); - return null; - } - - private void parseNumerics(RawMessage message) { - String code = message.getCommand(); - if (code.equals(Numerics.CHANNEL_TOPIC)) { - String chanName = message.getRaw().split(" ")[3]; - String topic = message.getRaw().split(" :", 2)[1].trim(); - Channel c = server.getChannel(chanName); - if (!c.isRunning()) { - c.setup(); - } - c.setTopic(topic); - - } else if (code.equals(Numerics.CHANNEL_TOPIC_SET)) { - String[] parts = message.getRaw().split(" "); - String chanName = parts[3]; - String setter = parts[4]; - /* - * if(setter.contains("!")) { setter = setter.split("!")[0]; } - */ - // would use the above code but we want the api to capture as much - // info as possible - // some servers send the mask, some just send the nick - String timestamp = parts[5]; - Channel c = server.getChannel(chanName); - if (!c.isRunning()) { - c.setup(); - } - c.setTopicSetter(setter); - c.setTopicSetTime(Long.parseLong(timestamp) * 1000L); - } - } - - public ServerSupportParser getServerSupport() { - return serverSupport; - } -} \ No newline at end of file diff --git a/src/api/com/speed/irc/connection/ServerMessageReader.java b/src/api/com/speed/irc/connection/ServerMessageReader.java deleted file mode 100644 index cadedbf..0000000 --- a/src/api/com/speed/irc/connection/ServerMessageReader.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.speed.irc.connection; - -import com.speed.irc.event.api.ApiEvent; - -import java.io.IOException; -import java.util.LinkedList; -import java.util.Queue; -import java.util.logging.Logger; - -/** - * Reads messages from the server and adds them to a queue. Encapsulates the - * queue to prevent it being read and modified before the parser parses the - * messages. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ServerMessageReader implements Runnable { - private final Server server; - private Queue queue = new LinkedList(); - private volatile String current; - protected volatile boolean running = true; - protected Logger logger = Logger.getLogger(Logger.class.getName()); - protected boolean logging; - - /** - * No public access to queue to prevent reading before the parser. Gets the - * next message to be read. - * - * @return the next message - */ - protected String poll() { - return queue.poll(); - } - - /** - * Gets the next item on the queue without removing it from the queue. - * - * @return the next item on queue - */ - public String peek() { - return queue.peek(); - } - - /** - * Checks to see if the queue is empty. - * - * @return true if they queue is empty, else false. - */ - public boolean isEmpty() { - return queue.isEmpty(); - } - - /** - * No public access to queue to prevent reading before the parser. Gets the - * queue - * - * @return the queue - */ - protected Queue getQueue() { - return queue; - } - - public ServerMessageReader(final Server server) { - this.server = server; - } - - public void run() { - try { - while (server.isConnected() && running - && (current = server.getReader().readLine()) != null) { - try { - queue.add(current); - } catch (IllegalStateException e) { - - queue.clear(); - queue.add(current); - } - if (logging) { - logger.info(current); - } - if (current.startsWith("ERROR :Closing Link:")) { - if (server.autoConnect && running) { - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - server.connect(); - server.eventManager.dispatchEvent(new ApiEvent( - ApiEvent.SERVER_DISCONNECTED, server, this)); - break; - } - } - } - } catch (IOException e) { - - server.quit(); - - } - - } - -} diff --git a/src/api/com/speed/irc/connection/ServerSupportParser.java b/src/api/com/speed/irc/connection/ServerSupportParser.java deleted file mode 100644 index 1ebeb4b..0000000 --- a/src/api/com/speed/irc/connection/ServerSupportParser.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.speed.irc.connection; - -import com.speed.irc.types.RawMessage; -import com.speed.irc.util.Numerics; - -import java.util.Properties; - -/** - * Parses the server support message (numeric 005) - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ServerSupportParser { - - private RawMessage[] messages; - private int index; - private Properties settings = new Properties(); - - private static final String CHANTYPES = "CHANTYPES"; - - public ServerSupportParser() { - this.messages = new RawMessage[0]; - index = 0; - } - - private void addMessage(RawMessage message) { - if (!message.getCommand().equals(Numerics.SERVER_SUPPORT)) - throw new IllegalArgumentException("Wrong numeric: " - + message.getCommand()); - RawMessage[] msgs = new RawMessage[index + 1]; - msgs[index] = message; - for (int i = 0; i < index; i++) { - msgs[i] = messages[i]; - } - index++; - messages = msgs; - } - - public void parse(RawMessage msg) { - addMessage(msg); - String message = msg.getRaw(); - if (msg.getRaw().contains(" :are supported by this server")) { - message = msg.getRaw() - .replace(" :are supported by this server", "").trim(); - - } - String[] parts = message.split(" "); - for (String s : parts) { - String key = null; - String value = null; - if (s.contains("=")) { - String[] t = s.split("=", 2); - key = t[0]; - value = t[1]; - } else { - key = s; - value = s; - } - settings.put(key, value); - } - } - - public Properties getSettings() { - return settings; - } - - public char[] getChanTypes() { - if (!getSettings().containsKey(CHANTYPES)) { - return new char[]{'@'}; - } else { - return settings.getProperty(CHANTYPES).toCharArray(); - } - } - - public char[][] getChanModes() { - String s = getSettings().getProperty("CHANMODES"); - String[] modes = s.split(",", 4); - return new char[][]{modes[0].toCharArray(), modes[1].toCharArray(), - modes[2].toCharArray(), modes[3].toCharArray()}; - } -} diff --git a/src/api/com/speed/irc/connection/ssl/IRCTrustManager.java b/src/api/com/speed/irc/connection/ssl/IRCTrustManager.java deleted file mode 100644 index 5d47b01..0000000 --- a/src/api/com/speed/irc/connection/ssl/IRCTrustManager.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.speed.irc.connection.ssl; - -import javax.net.ssl.X509TrustManager; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -/** - * This trust manager does not check certificates. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class IRCTrustManager implements X509TrustManager { - - public void checkClientTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException { - - } - - public void checkServerTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException { - - } - - public X509Certificate[] getAcceptedIssuers() { - return null; - } - -} diff --git a/src/api/com/speed/irc/event/EventGenerator.java b/src/api/com/speed/irc/event/EventGenerator.java deleted file mode 100644 index 06fa730..0000000 --- a/src/api/com/speed/irc/event/EventGenerator.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.speed.irc.event; - -import com.speed.irc.types.RawMessage; - -/** - * Represents an EventGenerator submitted to the parser. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public interface EventGenerator { - /** - * Checks whether this generator will generate events for the specified message - * - * @param raw the message to test for compatibility with this generator, - * should not be null - * @return true if the message is compatible, false otherwise - */ - public boolean accept(final RawMessage raw); - - /** - * Generates an event object for the specified raw message - * - * @param raw The raw message to generate events for. Undefined behaviour if - * message is not compatible, and should not be null. - * @return The event generated by this method. - */ - public IRCEvent generate(final RawMessage raw); - -} diff --git a/src/api/com/speed/irc/event/EventManager.java b/src/api/com/speed/irc/event/EventManager.java deleted file mode 100755 index 8877496..0000000 --- a/src/api/com/speed/irc/event/EventManager.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.speed.irc.event; - -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * Manages events in a queue, and sends them to the appropriate listener. - * Also manages a list of listeners. - *

- *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class EventManager implements Runnable { - - private List listeners = new CopyOnWriteArrayList(); - private BlockingQueue eventQueue = new LinkedBlockingQueue(); - - /** - * Adds an event to the event queue. - * - * @param event the event to be processed by the event queue. - */ - public void dispatchEvent(final IRCEvent event) { - eventQueue.offer(event); - } - - /** - * Adds an event listener to this event manager. - * - * @param listener the listener to be added to this event manager. - */ - public void addListener(final IRCEventListener listener) { - listeners.add(listener); - } - - /** - * Removes an event listener from this event manager. - * - * @param listener the listener to be removed - * @return true if the listener was successfully removed, - * false if it wasn't - */ - public boolean removeListener(final IRCEventListener listener) { - return listeners.remove(listener); - } - - public void run() { - IRCEvent e = eventQueue.poll(); - if (e != null) { - for (IRCEventListener listener : listeners) { - for (Class clz : listener.getClass().getInterfaces()) { - if (clz.getAnnotation(ListenerProperties.class) != null) { - try { - ListenerProperties properties = clz.getAnnotation(ListenerProperties.class); - for (Class clazz : properties.events()) { - if (e.getClass().isAssignableFrom(clazz)) { - e.callListener(listener); - } - } - } catch (Exception e1) { - this.dispatchEvent(new com.speed.irc.event.api.ExceptionEvent(e1, this, null)); - e1.printStackTrace(); - } - } - } - } - } - } - - /** - * Clears the queue of events to be processed. - */ - public void clearQueue() { - eventQueue.clear(); - - } - -} diff --git a/src/api/com/speed/irc/event/IRCEvent.java b/src/api/com/speed/irc/event/IRCEvent.java deleted file mode 100755 index 9de403e..0000000 --- a/src/api/com/speed/irc/event/IRCEvent.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.speed.irc.event; - -/** - * Allows identification as an event. All events must implement this class to be - * dispatched by the event manager. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public interface IRCEvent { - /** - * Gets the object that dispatched this event - * - * @return the object that dispatched the event - */ - public Object getSource(); - - /** - * Invokes the correct method(s) from the listener for this event. - * - * @param listener a listener object that accepts this event - */ - public void callListener(IRCEventListener listener); -} diff --git a/src/api/com/speed/irc/event/IRCEventListener.java b/src/api/com/speed/irc/event/IRCEventListener.java deleted file mode 100755 index 675d9ea..0000000 --- a/src/api/com/speed/irc/event/IRCEventListener.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.speed.irc.event; - -/** - * Event listeners must extend this interface to allow them to be registered as - * an event listener. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public interface IRCEventListener { - -} diff --git a/src/api/com/speed/irc/event/ListenerProperties.java b/src/api/com/speed/irc/event/ListenerProperties.java deleted file mode 100644 index afed965..0000000 --- a/src/api/com/speed/irc/event/ListenerProperties.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.speed.irc.event; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Event listeners must use this annotation to allow them to receive the correct - * events. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -@Retention(value = RetentionPolicy.RUNTIME) -public @interface ListenerProperties { - Class[] events(); -} diff --git a/src/api/com/speed/irc/event/api/ApiEvent.java b/src/api/com/speed/irc/event/api/ApiEvent.java deleted file mode 100644 index a0d7a82..0000000 --- a/src/api/com/speed/irc/event/api/ApiEvent.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.speed.irc.event.api; - -import com.speed.irc.connection.Server; -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.IRCEventListener; - -/** - * Provides events for many API features. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ApiEvent implements IRCEvent { - public static final int SERVER_DISCONNECTED = 1, EXCEPTION_RECEIVED = 2; - - public static final int SERVER_QUIT = 3; - - private int opcode; - private Server server; - private Object source; - - public ApiEvent(final int opcode, final Server server, final Object src) { - source = src; - this.opcode = opcode; - this.server = server; - } - - /** - * Gets the opcode of the event. - * - * @return the opcode of this event - * @see {@link ApiEvent#SERVER_DISCONNECTED}, - * {@link ApiEvent#EXCEPTION_RECEIVED}, {@link ApiEvent#SERVER_QUIT} - */ - public int getOpcode() { - return opcode; - } - - /** - * Gets the server from which the event was thrown. - * - * @return the server from which the event was thrown - */ - public Server getServer() { - return server; - } - - public Object getSource() { - return source; - } - - public void callListener(final IRCEventListener listener) { - if (listener instanceof ApiListener) {// these checks SHOULDN'T be - // necessary - ((ApiListener) listener).apiEventReceived(this); - } - } - -} diff --git a/src/api/com/speed/irc/event/api/ApiListener.java b/src/api/com/speed/irc/event/api/ApiListener.java deleted file mode 100644 index ce9e814..0000000 --- a/src/api/com/speed/irc/event/api/ApiListener.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.speed.irc.event.api; - -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.event.ListenerProperties; - -/** - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -@ListenerProperties(events = ApiEvent.class) -public interface ApiListener extends IRCEventListener { - public void apiEventReceived(ApiEvent e); -} diff --git a/src/api/com/speed/irc/event/api/ExceptionEvent.java b/src/api/com/speed/irc/event/api/ExceptionEvent.java deleted file mode 100644 index 5d3899c..0000000 --- a/src/api/com/speed/irc/event/api/ExceptionEvent.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.speed.irc.event.api; - -import com.speed.irc.connection.Server; - -/** - * Wraps an exception into an event - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ExceptionEvent extends ApiEvent { - private final Exception exception; - - public ExceptionEvent(final Exception e, final Object source, - final Server server) { - super(ApiEvent.EXCEPTION_RECEIVED, server, source); - exception = e; - } - - public Exception getException() { - return exception; - } - -} diff --git a/src/api/com/speed/irc/event/api/WhoisEvent.java b/src/api/com/speed/irc/event/api/WhoisEvent.java deleted file mode 100644 index 21aa2ba..0000000 --- a/src/api/com/speed/irc/event/api/WhoisEvent.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.speed.irc.event.api; - -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.types.Whois; - -/** - * Represents a WHOIS event. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class WhoisEvent implements IRCEvent { - - private final Whois whois; - private final Object source; - - public WhoisEvent(final Whois whois, final Object source) { - this.whois = whois; - this.source = source; - } - - /** - * Gets the WHOIS object that this event represents, not guaranteed to be non-null. - * - * @return the event represented by this object, may be null - */ - public Whois getWhois() { - return whois; - } - - public Object getSource() { - return source; - } - - @Override - public void callListener(IRCEventListener listener) { - if (listener instanceof WhoisListener) { - ((WhoisListener) listener).whoisReceived(this); - } - } - -} diff --git a/src/api/com/speed/irc/event/api/WhoisListener.java b/src/api/com/speed/irc/event/api/WhoisListener.java deleted file mode 100644 index eb753d4..0000000 --- a/src/api/com/speed/irc/event/api/WhoisListener.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.speed.irc.event.api; - -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.event.ListenerProperties; - -/** - * Marks the implementing class as a WHOIS event listener. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -@ListenerProperties(events = WhoisEvent.class) -public interface WhoisListener extends IRCEventListener { - - public void whoisReceived(WhoisEvent e); - -} diff --git a/src/api/com/speed/irc/event/channel/ChannelEvent.java b/src/api/com/speed/irc/event/channel/ChannelEvent.java deleted file mode 100644 index ff4c849..0000000 --- a/src/api/com/speed/irc/event/channel/ChannelEvent.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.speed.irc.event.channel; - -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.types.Channel; -import com.speed.irc.types.ServerUser; - -/** - * Represents a channel event. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public abstract class ChannelEvent implements IRCEvent { - - /** - * Constants for the ChannelEvent#getCode() method, - * #TOPIC_CHANGED means the event was dispatched because the topic changed - * #MODE_CHANGED means the event was dispatched because a channel mode was changed - */ - public static final int TOPIC_CHANGED = 10, - MODE_CHANGED = 11; - private final int code; - private final Channel channel; - private String[] args; - private final Object source; - private ServerUser sender; - - public ChannelEvent(final Channel channel, final int code, - String senderNick, final Object source, final String... args) { - this.code = code; - this.channel = channel; - this.source = source; - this.sender = channel.getUser(senderNick); - if (this.sender == null) - // e.g. ChanServ etc - this.sender = channel.getServer().getUser(senderNick); - this.args = args; - } - - public ChannelEvent(Channel channel2, int code2, Object source2, - final String... args) { - this.code = code2; - this.channel = channel2; - this.source = source2; - this.args = args; - } - - /** - * Gets the code of this event - * See #TOPIC_CHANGED and #MODE_CHANGED - * - * @return the numeric code for this event - * @see #TOPIC_CHANGED and #MODE_CHANGED - */ - public int getCode() { - return code; - } - - /** - * Gets the channel that this event was dispatched for - * - * @return The channel object that represents the channel this event was - * dispatched for. - */ - public Channel getChannel() { - return channel; - } - - /** - * Gets the user that caused this event - * - * @return The {@link ServerUser} (usually {@link com.speed.irc.types.ChannelUser}) - * that caused this event to be dispatched. - */ - public ServerUser getSender() { - return sender; - } - - public Object getSource() { - return source; - } - - public void callListener(IRCEventListener listener) { - if (listener instanceof ChannelUserListener - && this instanceof ChannelUserEvent) { - final ChannelUserListener l = (ChannelUserListener) listener; - final ChannelUserEvent event = (ChannelUserEvent) this; - switch (event.getCode()) { - case ChannelUserEvent.USER_JOINED: - l.channelUserJoined(event); - break; - case ChannelUserEvent.USER_KICKED: - l.channelUserKicked(event); - break; - case ChannelUserEvent.USER_PARTED: - l.channelUserParted(event); - break; - case ChannelUserEvent.USER_NICK_CHANGED: - l.channelUserNickChanged(event); - break; - case ChannelUserEvent.USER_QUIT: - l.channelUserQuit(event); - break; - } - } else if (listener instanceof ChannelUserListener && this instanceof ModeChangedEvent) { - final ChannelEvent event = this; - final ChannelUserListener l = (ChannelUserListener) listener; - final ModeChangedEvent mce = (ModeChangedEvent) this; - if (event.getCode() == ChannelEvent.MODE_CHANGED && mce.getAffectedUser() != null) { - l.channelUserModeChanged(mce); - } - } else if (listener instanceof ChannelEventListener) { - final ChannelEventListener l = (ChannelEventListener) listener; - final ChannelEvent event = this; - switch (event.getCode()) { - case ChannelEvent.MODE_CHANGED: - l.channelModeChanged((ModeChangedEvent) event); - break; - case ChannelEvent.TOPIC_CHANGED: - l.channelTopicChanged((TopicChangedEvent) event); - break; - } - } - } - - /** - * Get the arguments of this event, usually used internally to parse meaningful - * data. - *

- * For {@link ModeChangedEvent} this should be the contents of this array: - *

- * [0]: the mode including whether its + or -. - *

- * [1]: the mask that was affected by this mode, if there was one at all - *

- * For {@link TopicChangedEvent} this should be the contents of this array: - *

- * [0]: the old topic - *

- * [1]: the new topic - * - * @return the arguments of the event - */ - public String[] getArgs() { - return args; - } -} diff --git a/src/api/com/speed/irc/event/channel/ChannelEventListener.java b/src/api/com/speed/irc/event/channel/ChannelEventListener.java deleted file mode 100644 index cecb721..0000000 --- a/src/api/com/speed/irc/event/channel/ChannelEventListener.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.speed.irc.event.channel; - -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.event.ListenerProperties; - -/** - * Implement this interface and register to the event manager to receive channel - * events. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -@ListenerProperties(events = {ChannelEvent.class, TopicChangedEvent.class, ModeChangedEvent.class}) -public interface ChannelEventListener extends IRCEventListener { - public void channelTopicChanged(TopicChangedEvent e); - - public void channelModeChanged(ModeChangedEvent e); -} diff --git a/src/api/com/speed/irc/event/channel/ChannelUserEvent.java b/src/api/com/speed/irc/event/channel/ChannelUserEvent.java deleted file mode 100644 index 3898aa8..0000000 --- a/src/api/com/speed/irc/event/channel/ChannelUserEvent.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.speed.irc.event.channel; - -import com.speed.irc.types.Channel; -import com.speed.irc.types.ChannelUser; - -/** - * Represents a channel user event. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ChannelUserEvent extends ChannelEvent { - - private ChannelUser user; - public static final int USER_JOINED = 0, USER_PARTED = 1, USER_MODE_CHANGED = 2, USER_KICKED = 3, - USER_NICK_CHANGED = 4, USER_QUIT = 5; - - public ChannelUserEvent(Object source, final Channel channel, final ChannelUser user, final int code) { - super(channel, code, source); - this.user = user; - } - - public ChannelUserEvent(Object source, final Channel channel, final ChannelUser user, final String sender, - final int code, final String... args) { - super(channel, code, sender, source, args); - this.user = user; - } - - public ChannelUserEvent(Object source, final Channel channel, final ChannelUser user, final int code, - final String... args) { - super(channel, code, source, args); - this.user = user; - } - - public ChannelUser getUser() { - return user; - } - - /** - * @return - * @deprecated see {@link #getArgs()} instead - */ - public String[] getArguments() { - return getArgs(); - } - -} diff --git a/src/api/com/speed/irc/event/channel/ChannelUserListener.java b/src/api/com/speed/irc/event/channel/ChannelUserListener.java deleted file mode 100644 index 13e8aa2..0000000 --- a/src/api/com/speed/irc/event/channel/ChannelUserListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.speed.irc.event.channel; - -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.event.ListenerProperties; - -/** - * Implement this interface and register to the event manager to receive channel - * user events. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -@ListenerProperties(events = {ChannelUserEvent.class, ModeChangedEvent.class}) -public interface ChannelUserListener extends IRCEventListener { - public void channelUserJoined(ChannelUserEvent e); - - public void channelUserParted(ChannelUserEvent e); - - public void channelUserModeChanged(ModeChangedEvent e); - - public void channelUserKicked(ChannelUserEvent e); - - public void channelUserNickChanged(ChannelUserEvent e); - - public void channelUserQuit(ChannelUserEvent e); -} diff --git a/src/api/com/speed/irc/event/channel/ModeChangedEvent.java b/src/api/com/speed/irc/event/channel/ModeChangedEvent.java deleted file mode 100644 index 88aaca5..0000000 --- a/src/api/com/speed/irc/event/channel/ModeChangedEvent.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.speed.irc.event.channel; - -import com.speed.irc.types.Channel; -import com.speed.irc.types.ChannelUser; -import com.speed.irc.types.ModeList; - -/** - * A class representing the change of modes in a Channel. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ModeChangedEvent extends ChannelEvent { - private final ChannelUser affectedUser; - private final ModeList modes; - private final String affectedMask; - private final String rawModes; - - public ModeChangedEvent(Channel channel, String senderNick, Object source, String... args) { - super(channel, ChannelEvent.MODE_CHANGED, senderNick, source, args); - modes = new ModeList(channel.getServer(), args[0]); - affectedMask = args.length == 1 ? channel.getName() : args[1]; - affectedUser = null; - rawModes = args[0]; - } - - public ModeChangedEvent(Channel channel, ChannelUser affectedUser, String senderNick, Object source, String... args) { - super(channel, ChannelEvent.MODE_CHANGED, senderNick, source, args); - this.affectedUser = affectedUser; - this.modes = new ModeList(channel.getServer(), args[0]); - affectedMask = null; - rawModes = args[0]; - } - - /** - * Gets the modes added to the channel - * - * @return the modes added to the channel - */ - public ModeList getNewModes() { - return modes; - } - - /** - * Gets the user affected by this mode change. - * - * @return the user affected by this change if appropriate, else null. - */ - public ChannelUser getAffectedUser() { - return affectedUser; - } - - /** - * Gets the mask affected by this mode change. - * - * @return the mask affected by this change if appropriate, else null. - */ - public String getAffectedMask() { - return affectedMask; - } - - /** - * Gets the raw mode affected by this mode change - * - * @return the mode affected by this change - */ - public String getRowMode() { - return rawModes; - } - -} diff --git a/src/api/com/speed/irc/event/channel/TopicChangedEvent.java b/src/api/com/speed/irc/event/channel/TopicChangedEvent.java deleted file mode 100644 index aba4c3b..0000000 --- a/src/api/com/speed/irc/event/channel/TopicChangedEvent.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.speed.irc.event.channel; - -import com.speed.irc.types.Channel; - -/** - * Represents a topic changed event. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class TopicChangedEvent extends ChannelEvent { - public TopicChangedEvent(Channel channel, String changerNick, Object source, String... args) { - super(channel, ChannelEvent.TOPIC_CHANGED, changerNick, source, args); - } - - public String getOldTopic() { - return getArgs()[0]; - } - - public String getNewTopic() { - return getArgs()[1]; - } -} diff --git a/src/api/com/speed/irc/event/generators/JoinGenerator.java b/src/api/com/speed/irc/event/generators/JoinGenerator.java deleted file mode 100644 index 071c3a5..0000000 --- a/src/api/com/speed/irc/event/generators/JoinGenerator.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.speed.irc.event.generators; - -import com.speed.irc.event.EventGenerator; -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.channel.ChannelUserEvent; -import com.speed.irc.types.Channel; -import com.speed.irc.types.ChannelUser; -import com.speed.irc.types.RawMessage; - -/** - * Processes JOIN messages sent from the server. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class JoinGenerator implements EventGenerator { - - public boolean accept(RawMessage raw) { - return raw.getCommand().equals("JOIN"); - } - - public IRCEvent generate(RawMessage raw) { - final String[] parts = raw.getRaw().split("!"); - final String nick = parts[0]; - final String user = parts[1].split("@")[0]; - final String host = parts[1].split("@")[1].split(" ")[0]; - String chan = raw.getRaw().split(" ")[2]; - if (raw.getRaw().split(" ")[2].startsWith(":")) { - chan = chan.substring(1); - } - Channel channel = raw.getServer().getChannel(chan); - if (channel == null) { - channel = new Channel(chan, raw.getServer()); - channel.setup(); - } else if (!channel.isRunning()) { - channel.setup(); - } - if (channel.getUser(nick) != null) { - channel.removeChannelUser(channel.getUser(nick)); - } - final ChannelUser u = new ChannelUser(nick, "", user, host, channel); - return new ChannelUserEvent(this, channel, u, - ChannelUserEvent.USER_JOINED); - } - -} diff --git a/src/api/com/speed/irc/event/generators/KickGenerator.java b/src/api/com/speed/irc/event/generators/KickGenerator.java deleted file mode 100644 index 6af6fe4..0000000 --- a/src/api/com/speed/irc/event/generators/KickGenerator.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.speed.irc.event.generators; - -import com.speed.irc.event.EventGenerator; -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.channel.ChannelUserEvent; -import com.speed.irc.types.Channel; -import com.speed.irc.types.ChannelUser; -import com.speed.irc.types.RawMessage; - -/** - * Processes KICK messages sent from the server. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class KickGenerator implements EventGenerator { - - public boolean accept(RawMessage raw) { - return raw.getCommand().equals("KICK"); - } - - public IRCEvent generate(RawMessage raw) { - final Channel channel = raw.getServer().getChannel( - raw.getRaw().split(" ")[2]); - if (channel == null) { - return null; - } - final ChannelUser user = channel.getUser(raw.getRaw().split(" ")[3]); - if (user == null) { - return null; - } - String kickMsg = ""; - String[] parts = raw.getRaw().split(" :", 2); - if (parts.length > 1) { - kickMsg = parts[1]; - } - return new ChannelUserEvent(this, channel, user, raw.getSender().split( - "!")[0].trim(), ChannelUserEvent.USER_KICKED, kickMsg); - } -} diff --git a/src/api/com/speed/irc/event/generators/ModeGenerator.java b/src/api/com/speed/irc/event/generators/ModeGenerator.java deleted file mode 100644 index 87d1810..0000000 --- a/src/api/com/speed/irc/event/generators/ModeGenerator.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.speed.irc.event.generators; - -import com.speed.irc.connection.Server; -import com.speed.irc.event.EventGenerator; -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.channel.ModeChangedEvent; -import com.speed.irc.types.Channel; -import com.speed.irc.types.ChannelUser; -import com.speed.irc.types.Mask; -import com.speed.irc.types.RawMessage; - -import java.util.Arrays; - -/** - * Processes MODE messages sent from the server. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ModeGenerator implements EventGenerator { - - public boolean accept(RawMessage raw) { - return raw.getCommand().equals("MODE"); - } - - public IRCEvent generate(RawMessage message) { - String raw = message.getRaw(); - Server server = message.getServer(); - String sender = message.getSender(); - String name = message.getTarget(); - Channel channel = null; - if (Arrays.binarySearch(server.getChannelPrefix(), name.charAt(0)) >= 0) { - channel = server.getChannel(name); - if (!channel.isRunning()) { - channel.setup(); - } - } - if (name.equals(server.getNick())) { - String modes = raw.split(" :", 2)[1].trim(); - server.parseUserModes(modes); - return null; - } - String senderNick = sender.split("!")[0].trim(); - raw = raw.split(name, 2)[1].trim(); - String[] strings = raw.split(" "); - String modes = strings[0]; - if (strings.length == 1 && channel != null) { - channel.chanModeList.parse(modes); - return new ModeChangedEvent(channel, senderNick, this, modes); - } else { - String[] u = new String[strings.length - 1]; - System.arraycopy(strings, 1, u, 0, u.length); - boolean plus = false; - int index = 0; - for (int i = 0; i < modes.toCharArray().length; i++) { - char c = modes.toCharArray()[i]; - if (c == '+') { - plus = true; - continue; - } else if (c == '-') { - plus = false; - continue; - } - if (c == 'b') { - if (plus) { - channel.bans.add(new Mask(u[index])); - } else { - channel.bans.remove(new Mask(u[index])); - } - server.getEventManager().dispatchEvent( - new ModeChangedEvent(channel, senderNick, this, (plus ? "+" : "-") - + "b", u[index])); - index++; - - continue; - } else if (c == 'e') { - if (plus) { - channel.exempts.add(new Mask(u[index])); - } else { - channel.exempts.remove(new Mask(u[index])); - } - server.getEventManager().dispatchEvent( - new ModeChangedEvent(channel, senderNick, this, (plus ? "+" : "-") - + "e", u[index])); - index++; - - continue; - } else if (c == 'I') { - if (plus) { - channel.invites.add(new Mask(u[index])); - } else { - channel.invites.remove(new Mask(u[index])); - } - server.getEventManager().dispatchEvent( - new ModeChangedEvent(channel, senderNick, this, (plus ? "+" : "-") - + "I", u[index])); - index++; - - continue; - } - if (Arrays.binarySearch(server.getModeLetters(), c) >= 0) { - //this is a known rank, with a nick argument - ChannelUser user = channel.getUser(u[index]); - if (user == null) { - user = new ChannelUser(u[index], "", null, null, channel); - channel.addChannelUser(user); - } - if (user != null) { - if (plus) { - user.addMode(c); - } else { - user.removeMode(c); - } - server.getEventManager().dispatchEvent( - new ModeChangedEvent(channel, user, senderNick, this, - (plus ? "+" : "-") + c)); - - } - } else { - //channel modes - channel.getModeList().parse((plus ? "+" : "-") + c); - } - index++; - - } - - } - return null; - } - -} diff --git a/src/api/com/speed/irc/event/generators/NoticeGenerator.java b/src/api/com/speed/irc/event/generators/NoticeGenerator.java deleted file mode 100644 index b53c06f..0000000 --- a/src/api/com/speed/irc/event/generators/NoticeGenerator.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.speed.irc.event.generators; - -import com.speed.irc.connection.Server; -import com.speed.irc.event.EventGenerator; -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.message.NoticeEvent; -import com.speed.irc.types.Notice; -import com.speed.irc.types.RawMessage; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Processes NOTICE messages sent from the server. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class NoticeGenerator implements EventGenerator { - private static final Pattern PATTERN_NOTICE = Pattern - .compile("(.+?)!(.+?)@(.+?) NOTICE (.+?) :(.*)"); - private final Server server; - - public NoticeGenerator(Server server) { - this.server = server; - } - - public boolean accept(RawMessage raw) { - return PATTERN_NOTICE.matcher(raw.getRaw()).matches(); - } - - public IRCEvent generate(RawMessage raw) { - final Matcher notice_matcher = PATTERN_NOTICE.matcher(raw.getRaw()); - if (notice_matcher.matches()) { - final String msg = notice_matcher.group(5); - final String sender = notice_matcher.group(1) + '!' - + notice_matcher.group(2) + '@' + notice_matcher.group(3); - final String name = notice_matcher.group(4); - return new NoticeEvent(new Notice(msg, sender, name, server), this); - } - return null; - } - -} diff --git a/src/api/com/speed/irc/event/generators/PartGenerator.java b/src/api/com/speed/irc/event/generators/PartGenerator.java deleted file mode 100644 index f22dd46..0000000 --- a/src/api/com/speed/irc/event/generators/PartGenerator.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.speed.irc.event.generators; - -import com.speed.irc.event.EventGenerator; -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.channel.ChannelUserEvent; -import com.speed.irc.types.Channel; -import com.speed.irc.types.ChannelUser; -import com.speed.irc.types.RawMessage; - -/** - * Processes PART messages sent from the server. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class PartGenerator implements EventGenerator { - - public boolean accept(RawMessage raw) { - return raw.getCommand().equals("PART"); - } - - public IRCEvent generate(RawMessage raw) { - final String nick = raw.getSender().split("!")[0]; - Channel channel = raw.getServer() - .getChannel(raw.getRaw().split(" ")[2]); - if (!channel.isRunning()) { - channel.setup(); - } - final ChannelUser user = channel.getUser(nick); - String[] parts = raw.getRaw().split(" :", 2); - String partMsg = ""; - if (parts.length > 1) { - partMsg = parts[1]; - } - return new ChannelUserEvent(this, channel, user, - ChannelUserEvent.USER_PARTED, partMsg); - } - -} diff --git a/src/api/com/speed/irc/event/generators/PrivmsgGenerator.java b/src/api/com/speed/irc/event/generators/PrivmsgGenerator.java deleted file mode 100644 index 1df4685..0000000 --- a/src/api/com/speed/irc/event/generators/PrivmsgGenerator.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.speed.irc.event.generators; - -import com.speed.irc.connection.Server; -import com.speed.irc.event.EventGenerator; -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.message.PrivateMessageEvent; -import com.speed.irc.types.*; - -import java.util.Arrays; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Processes PRIVMSG messages sent from the server. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class PrivmsgGenerator implements EventGenerator { - private static final Pattern PATTERN_PRIVMSG = Pattern - .compile("(.+?)!(.+?)@(.+?) PRIVMSG (.+?) :(.*)"); - - public boolean accept(RawMessage raw) { - return PATTERN_PRIVMSG.matcher(raw.getRaw()).matches(); - } - - public IRCEvent generate(RawMessage raw) { - final Matcher priv_matcher = PATTERN_PRIVMSG.matcher(raw.getRaw()); - final Server server = raw.getServer(); - if (priv_matcher.matches()) { - final String msg = priv_matcher.group(5); - final String sender = priv_matcher.group(1); - final String user = priv_matcher.group(2); - final String host = priv_matcher.group(3); - final String name = priv_matcher.group(4); - if (msg.startsWith("\u0001")) {// ctcp messages - String request = msg.replace("\u0001", ""); - String reply = server.getCtcpReply(request); - if (reply != null) { - server.sendRaw(String.format( - "NOTICE %s :\u0001%s %s\u0001\n", sender, request, - reply)); - } - } - Conversable conversable = null; - if (Arrays.binarySearch(server.getChannelPrefix(), name.charAt(0)) >= 0) { - conversable = server.getChannel(name); - Channel c = (Channel) conversable; - if (!c.isRunning()) { - c.setup(); - } - } else { - conversable = new ServerUser(sender, host, user, server); - } - return new PrivateMessageEvent( - new Privmsg(msg, sender, conversable), this); - } - return null; - } - -} diff --git a/src/api/com/speed/irc/event/generators/WhoisGenerator.java b/src/api/com/speed/irc/event/generators/WhoisGenerator.java deleted file mode 100644 index 8c00220..0000000 --- a/src/api/com/speed/irc/event/generators/WhoisGenerator.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.speed.irc.event.generators; - -import com.speed.irc.connection.Server; -import com.speed.irc.event.EventGenerator; -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.api.WhoisEvent; -import com.speed.irc.types.RawMessage; -import com.speed.irc.types.Whois; -import com.speed.irc.util.Numerics; - -import java.util.Collection; - -/** - * Generates WHOIS events. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class WhoisGenerator implements EventGenerator { - private final Server server; - - public WhoisGenerator(final Server server) { - this.server = server; - } - - public boolean accept(RawMessage raw) { - for (String s : Numerics.WHOIS) { - if (s.equals(raw.getCommand())) - return true; - } - return false; - } - - public IRCEvent generate(RawMessage raw) { - String user = raw.getRaw().split(" ")[3]; - Collection messages = server.whoisWaiting.get(server - .getUser(user)); - if (raw.getCommand().equals(Numerics.WHOIS_END)) { - return new WhoisEvent(new Whois(messages, server), this); - } else { - messages.add(raw); - return null; - } - } - -} diff --git a/src/api/com/speed/irc/event/message/NoticeEvent.java b/src/api/com/speed/irc/event/message/NoticeEvent.java deleted file mode 100755 index 1ac9b55..0000000 --- a/src/api/com/speed/irc/event/message/NoticeEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.speed.irc.event.message; - -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.types.Notice; - -/** - * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class NoticeEvent implements IRCEvent { - protected final Notice notice; - protected final Object source; - - public NoticeEvent(final Notice notice, final Object source) { - this.notice = notice; - this.source = source; - } - - /** - * Gets the notice object represented by this event - * - * @return the notice object represented by this event - */ - public Notice getNotice() { - return notice; - } - - public Object getSource() { - return source; - } - - public void callListener(IRCEventListener listener) { - if (listener instanceof NoticeListener) { - ((NoticeListener) listener).noticeReceived(this); - } - } -} diff --git a/src/api/com/speed/irc/event/message/NoticeListener.java b/src/api/com/speed/irc/event/message/NoticeListener.java deleted file mode 100755 index 7089a92..0000000 --- a/src/api/com/speed/irc/event/message/NoticeListener.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.speed.irc.event.message; - -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.event.ListenerProperties; - -/** - * Implement this interface and register to the event manager to receive notice - * events. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -@ListenerProperties(events = NoticeEvent.class) -public interface NoticeListener extends IRCEventListener { - public void noticeReceived(NoticeEvent e); - -} diff --git a/src/api/com/speed/irc/event/message/PrivateMessageEvent.java b/src/api/com/speed/irc/event/message/PrivateMessageEvent.java deleted file mode 100755 index f426968..0000000 --- a/src/api/com/speed/irc/event/message/PrivateMessageEvent.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.speed.irc.event.message; - -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.types.Privmsg; - -/** - * The wrapper class for an PRIVMSG event. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class PrivateMessageEvent implements IRCEvent { - - protected final Object source; - protected final Privmsg message; - - public PrivateMessageEvent(final Privmsg message, final Object source) { - this.source = source; - this.message = message; - } - - public Object getSource() { - return source; - } - - /** - * Gets the message associated with this event. - * - * @return the message associated with this event. - */ - public Privmsg getMessage() { - return message; - } - - public void callListener(IRCEventListener listener) { - if (listener instanceof PrivateMessageListener) { - ((PrivateMessageListener) listener) - .messageReceived(this); - } - } - -} diff --git a/src/api/com/speed/irc/event/message/PrivateMessageListener.java b/src/api/com/speed/irc/event/message/PrivateMessageListener.java deleted file mode 100755 index bbf2bda..0000000 --- a/src/api/com/speed/irc/event/message/PrivateMessageListener.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.speed.irc.event.message; - -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.event.ListenerProperties; - -/** - * Implement this interface and register to event manager to receive private - * message events. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -@ListenerProperties(events = PrivateMessageEvent.class) -public interface PrivateMessageListener extends IRCEventListener { - public void messageReceived(PrivateMessageEvent e); -} diff --git a/src/api/com/speed/irc/event/message/RawMessageEvent.java b/src/api/com/speed/irc/event/message/RawMessageEvent.java deleted file mode 100755 index e373ad5..0000000 --- a/src/api/com/speed/irc/event/message/RawMessageEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.speed.irc.event.message; - -import com.speed.irc.event.IRCEvent; -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.types.RawMessage; - -/** - * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class RawMessageEvent implements IRCEvent { - - private RawMessage message; - protected Object source; - - public RawMessageEvent(final RawMessage message, final Object source) { - this.message = message; - this.source = source; - } - - /** - * Gets the raw message associated with this event - * - * @return the raw message associated with this event. - */ - public RawMessage getMessage() { - return message; - } - - public Object getSource() { - return source; - } - - public void callListener(IRCEventListener listener) { - if (listener instanceof RawMessageListener) { - ((RawMessageListener) listener).rawMessageReceived(this); - } - } - -} diff --git a/src/api/com/speed/irc/event/message/RawMessageListener.java b/src/api/com/speed/irc/event/message/RawMessageListener.java deleted file mode 100755 index f167a08..0000000 --- a/src/api/com/speed/irc/event/message/RawMessageListener.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.speed.irc.event.message; - -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.event.ListenerProperties; - -/** - * Implement this interface and register to the event manager to receive raw - * message events. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -@ListenerProperties(events = RawMessageEvent.class) -public interface RawMessageListener extends IRCEventListener { - public void rawMessageReceived(RawMessageEvent e); - -} diff --git a/src/api/com/speed/irc/framework/Bot.java b/src/api/com/speed/irc/framework/Bot.java deleted file mode 100644 index 2d250b5..0000000 --- a/src/api/com/speed/irc/framework/Bot.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.speed.irc.framework; - -import com.speed.irc.connection.Server; -import com.speed.irc.event.api.ApiEvent; -import com.speed.irc.event.api.ApiListener; -import com.speed.irc.event.api.ExceptionEvent; -import com.speed.irc.types.Channel; - -import java.io.IOException; -import java.net.UnknownHostException; -import java.util.logging.Logger; - -/** - * The abstract class for making robots. To create a robot, you can extend this - * class. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public abstract class Bot implements ApiListener { - - private Server server; - protected final int port; - protected Logger logger = Logger.getLogger(Bot.class.getName()); - protected int modes; - - /** - * Gets the port the bot is connected to - * - * @return the port the bot is connected to - */ - public int getPort() { - return port; - } - - /** - * Logs an info message - * - * @param message the message to log - */ - public final void info(final String message) { - logger.info(message); - } - - /** - * Gets the server the bot is connected to - * - * @return the server the bot is connected to - */ - public final Server getServer() { - return server; - } - - /** - * Executed just after connecting to the server and before joining channels - */ - public abstract void onStart(); - - /** - * Initialises a bot. - * - * @param server the server host name to connect to - * @param port the port number - * @param ssl whether to use ssl or not - */ - public Bot(final String server, final int port, boolean ssl) { - this.port = port; - try { - this.server = new Server(server, port, ssl); - this.server.register(getNick(), getUser(), getRealName()); - this.server.getEventManager().addListener(this); - onStart(); - for (Channel s : getChannels()) { - s.join(); - } - } catch (UnknownHostException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public Bot(final String server, final int port) { - this(server, port, false); - } - - /** - * Gets the channels to auto connect to - * - * @return the channels to auto connect to - */ - public abstract Channel[] getChannels(); - - /** - * Gets the nickname the bot should try to connect with - * - * @return the nickname of the bot - */ - public abstract String getNick(); - - /** - * Gets the alternative nickname of the bot - * - * @return the alternative nickname of the bot - */ - public String getAltNick() { - return getNick() + "_"; - } - - /** - * Gets the real name of the bot - * - * @return the real name of bot - */ - public String getRealName() { - return "SpeedsIrcApi"; - } - - /** - * Gets the username of the bot - * - * @return the username of bot - */ - public String getUser() { - return "SpeedsIrcApi"; - } - - private void connect() { - server.register(getNick(), getUser(), getRealName()); - for (Channel s : getChannels()) { - s.join(); - } - } - - /** - * Used to identify to NickServ. - * - * @param password The password assigned to your nick - */ - public void identify(final String password) { - server.sendRaw("PRIVMSG NickServ :identify " + password + "\n"); - } - - public void apiEventReceived(ApiEvent e) { - if (e.getOpcode() == ApiEvent.SERVER_DISCONNECTED) { - connect(); - } else if (e.getOpcode() == ApiEvent.EXCEPTION_RECEIVED) { - ((ExceptionEvent) e).getException().printStackTrace(); - } - } -} diff --git a/src/api/com/speed/irc/framework/test/GraphicalUserList.java b/src/api/com/speed/irc/framework/test/GraphicalUserList.java deleted file mode 100644 index e8c58b0..0000000 --- a/src/api/com/speed/irc/framework/test/GraphicalUserList.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.speed.irc.framework.test; - -import com.speed.irc.framework.Bot; -import com.speed.irc.types.Channel; -import com.speed.irc.types.ChannelUser; - -import javax.swing.*; - -/** - * Displays a visual list of all the users in the channel, and associated - * properties. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class GraphicalUserList extends JFrame implements Runnable { - - private Channel mainChannel; - private JList list; - private ListModel model; - - public static void main(String[] args) { - new GraphicalUserList(); - } - - public GraphicalUserList() { - Bot bot = new Bot("irc.rizon.net", 6697, true) { - - public void onStart() { - mainChannel = new Channel("#freecode", getServer()); - getServer().setReadDebug(true); - } - - public Channel[] getChannels() { - return new Channel[]{mainChannel}; - } - - public String getNick() { - return "UserLister"; - } - - }; - setSize(200, 300); - setDefaultCloseOperation(EXIT_ON_CLOSE); - setTitle("User List"); - model = new AbstractListModel() { - - @Override - public int getSize() { - return mainChannel.getUsers().size(); - } - - @Override - public ChannelUser getElementAt(int index) { - return mainChannel.getSortedUsers()[index]; - } - }; - list = new JList(model); - list.setFixedCellHeight(15); - JScrollPane pane = new JScrollPane(list, - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - add(pane); - setVisible(true); - new Thread(this).start(); - } - - public void run() { - while (isVisible() && mainChannel.isJoined()) { - //okay we should REALLY be using API listeners for this but w.e - setTitle("User Lister " + mainChannel.getName() + " " + mainChannel.getModeList().parse()); - repaint(); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - -} diff --git a/src/api/com/speed/irc/framework/test/HelloBot.java b/src/api/com/speed/irc/framework/test/HelloBot.java deleted file mode 100644 index 321d4f0..0000000 --- a/src/api/com/speed/irc/framework/test/HelloBot.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.speed.irc.framework.test; - -import com.speed.irc.event.api.ApiEvent; -import com.speed.irc.event.api.WhoisEvent; -import com.speed.irc.event.api.WhoisListener; -import com.speed.irc.event.channel.ChannelUserEvent; -import com.speed.irc.event.channel.ChannelUserListener; -import com.speed.irc.event.channel.ModeChangedEvent; -import com.speed.irc.event.message.PrivateMessageEvent; -import com.speed.irc.event.message.PrivateMessageListener; -import com.speed.irc.framework.Bot; -import com.speed.irc.types.*; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.Random; - -/** - * Greets people as they join the channel or speak a greeting. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class HelloBot extends Bot implements ChannelUserListener, - PrivateMessageListener, WhoisListener { - - private static final String[] HELLO_PHRASES = new String[]{"Hello", "Hi", - "Hey", "Yo", "Wassup", "helo", "herro", "hiya", "hai", "heya", - "sup"}; - private static final Random RANDOM_GENERATOR = new Random(); - private volatile Channel[] channels; - private final static String OWNER = "Speed"; - - public HelloBot(final String server, final int port, final boolean ssl) { - super(server, port, ssl); - - } - - @Override - public String getRealName() { - return "Hello Bot"; - } - - public static void main(String[] args) { - new HelloBot("irc.rizon.net", 6697, true); - } - - public Channel[] getChannels() { - return channels; - } - - public String getNick() { - return "HelloBot"; - } - - public void onStart() { - channels = new Channel[]{new Channel("#freecode", getServer())}; - channels[0].setAutoRejoin(true); - // identify("password"); - getServer().setAutoReconnect(true); - getServer().setReadDebug(true); - } - - @Override - public void apiEventReceived(final ApiEvent e) { - super.apiEventReceived(e); - if (e.getOpcode() == ApiEvent.SERVER_QUIT) { - logger.info("WE HAVE QUIT FROM THE SERVER."); - } - } - - public void messageReceived(PrivateMessageEvent e) { - final String message = e.getMessage().getMessage(); - final String sender = e.getMessage().getSender(); - if (message.contains("!raw") && sender.equals(OWNER)) { - getServer().sendRaw(message.replaceFirst("!raw", "").trim()); - } else if (message.equals("!quit") && sender.equals(OWNER)) { - getServer().quit("bai"); - } else if (message.equals("!list") && sender.equals(OWNER)) { - Channel main = channels[0]; - if (main.isRunning()) { - Collection users = main.getUsers(); - for (ChannelUser u : users) { - info(u.getMask().toString() + " - " - + Integer.toBinaryString(u.getRights())); - } - } else { - info("Not in channel"); - } - } else if (message.equals("!rejoin") && sender.equals(OWNER)) { - channels[0].setAutoRejoin(!channels[0].isAutoRejoinOn()); - info(Boolean.toString(channels[0].isAutoRejoinOn())); - } else if (message.startsWith("!verify") && sender.equals(OWNER)) { - e.getMessage() - .getConversable() - .sendMessage( - Boolean.toString(Mask.verify(message.replaceFirst( - "!verify", "").trim()))); - - } else if (message.equals("!print")) { - e.getMessage().getConversable().sendMessage(getServer().getNick()); - } else if (message.equals("!topic")) { - if (e.getMessage().getConversable().isChannel()) { - Channel c = e.getMessage().getConversable().getChannel(); - c.sendMessage("Topic: " + c.getTopic()); - c.sendMessage("Topic set by: " + c.getTopicSetter()); - c.sendMessage("Topic set at: " - + new Date(c.getTopicSetTime()).toString()); - } - } else if (message.startsWith("!whois") && sender.equals(OWNER)) { - String name = message.replace("!whois", "").trim(); - ServerUser user = getServer().getUser(name); - user.requestWhois(); - } - if (e.getMessage().getConversable() == null - || !(e.getMessage().getConversable() instanceof Channel)) { - return; - } - final Channel channel = (Channel) e.getMessage().getConversable(); - final ChannelUser user = channel.getUser(sender); - for (String s : HELLO_PHRASES) { - if (message.toLowerCase().equals(s.toLowerCase()) - || (message.toLowerCase().contains( - getServer().getNick().toLowerCase()) && message - .toLowerCase().contains(s.toLowerCase()))) { - channel.sendMessage(HELLO_PHRASES[RANDOM_GENERATOR - .nextInt(HELLO_PHRASES.length - 1)] - + " " - + sender - + " with rights: " + user.getRights()); - } - - } - } - - public void channelUserJoined(ChannelUserEvent e) { - e.getChannel().sendMessage( - HELLO_PHRASES[RANDOM_GENERATOR - .nextInt(HELLO_PHRASES.length - 1)] - + " " - + e.getUser().getNick()); - } - - public void channelUserParted(ChannelUserEvent e) { - } - - public void channelUserModeChanged(ModeChangedEvent e) { - } - - - public void channelUserKicked(ChannelUserEvent e) { - } - - public void channelUserNickChanged(ChannelUserEvent e) { - final String newNick = e.getArgs()[1]; - final String oldNick = e.getArgs()[0]; - info(oldNick + " changed to " + newNick); - e.getChannel().sendMessage( - HELLO_PHRASES[RANDOM_GENERATOR - .nextInt(HELLO_PHRASES.length - 1)] + " " + newNick); - } - - public void whoisReceived(WhoisEvent e) { - Whois is = e.getWhois(); - channels[0].sendMessage("Whois: " + is.getUser().toString()); - channels[0].sendMessage("Whois: " + Arrays.toString(is.getChannels())); - } - - @Override - public void channelUserQuit(ChannelUserEvent e) { - // TODO Auto-generated method stub - - } - -} diff --git a/src/api/com/speed/irc/types/Bot.java b/src/api/com/speed/irc/types/Bot.java deleted file mode 100644 index 3051fee..0000000 --- a/src/api/com/speed/irc/types/Bot.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.connection.Server; -import com.speed.irc.event.IRCEventListener; -import com.speed.irc.event.api.ApiEvent; -import com.speed.irc.event.api.ApiListener; -import com.speed.irc.event.api.ExceptionEvent; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; -import java.util.logging.Logger; - -/** - * The abstract class for making robots. To create a robot, you can extend this - * class. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - * @deprecated use {@link com.speed.irc.framework.Bot} instead - */ -public abstract class Bot implements ApiListener { - - protected Server server; - protected final int port; - protected Logger logger = Logger.getLogger(Bot.class.getName()); - protected int modes; - - public int getPort() { - return port; - } - - public final void info(final String message) { - logger.info(message); - } - - public final Server getServer() { - return server; - } - - public abstract void onStart(); - - public Bot(final String server, final int port) { - this.port = port; - try { - this.server = new Server(new Socket(server, port)); - this.server.sendRaw("NICK " + getNick() + "\n"); - this.server.sendRaw("USER " + getUser() + " 0 * :" + getRealName()); - if (this instanceof IRCEventListener) { - this.server.getEventManager().addListener( - (IRCEventListener) this); - } - onStart(); - for (Channel s : getChannels()) { - s.join(); - } - } catch (UnknownHostException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public abstract Channel[] getChannels(); - - public abstract String getNick(); - - public String getRealName() { - return "SpeedsIrcApi"; - } - - public String getUser() { - return "Speed"; - } - - private void connect() { - this.server.sendRaw("NICK " + getNick() + "\n"); - this.server.sendRaw("USER " + getUser() + " " + modes + " * :" - + getRealName() + "\n"); - for (Channel s : getChannels()) { - s.join(); - } - } - - /** - * Used to identify to NickServ. - * - * @param password The password assigned to your nick - */ - public void identify(final String password) { - server.sendRaw("PRIVMSG NickServ :identify " + password + "\n"); - } - - public void apiEventReceived(ApiEvent e) { - if (e.getOpcode() == ApiEvent.SERVER_DISCONNECTED) { - connect(); - } else if (e.getOpcode() == ApiEvent.EXCEPTION_RECEIVED) { - ((ExceptionEvent) e).getException().printStackTrace(); - } - } -} diff --git a/src/api/com/speed/irc/types/CTCPReply.java b/src/api/com/speed/irc/types/CTCPReply.java deleted file mode 100644 index e71ebcd..0000000 --- a/src/api/com/speed/irc/types/CTCPReply.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.speed.irc.types; - -/** - * Abstract class used to represent CTCP requests and replies, allows CTCP - * replies to be dynamic. - *

- *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public abstract class CTCPReply { - /** - * Gets the reply message - * - * @return the reply message - */ - public abstract String getReply(); - - /** - * Gets the request message - * - * @return the request message - */ - public abstract String getRequest(); - - @Override - public boolean equals(Object o) { - if (o instanceof CTCPReply) { - return getReply().equals(((CTCPReply) o).getReply()) - && getRequest().equals(((CTCPReply) o).getRequest()); - } - return false; - } - - @Override - public int hashCode() { - return (getReply().hashCode() | getRequest().hashCode()) & 0xffffff; - } -} diff --git a/src/api/com/speed/irc/types/Channel.java b/src/api/com/speed/irc/types/Channel.java deleted file mode 100755 index 26f439b..0000000 --- a/src/api/com/speed/irc/types/Channel.java +++ /dev/null @@ -1,488 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.connection.Server; -import com.speed.irc.event.channel.ChannelUserEvent; -import com.speed.irc.event.channel.ChannelUserListener; -import com.speed.irc.event.channel.ModeChangedEvent; - -import java.util.*; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -/** - * Represents a channel - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class Channel extends Conversable implements ChannelUserListener, - Runnable { - protected String name; - protected Server server; - public volatile List users = new LinkedList(); - public volatile List userBuffer = new LinkedList(); - public volatile boolean isRunning = false; - public long whoDelay = 120000L; - private long topicSetTime; - private String topicSetter; - public int autoRejoinDelay = 50; - protected boolean autoRejoin; - public ModeList chanModeList; - public List bans = new LinkedList(); - public List exempts = new LinkedList(); - public List invites = new LinkedList(); - protected String topic; - protected ScheduledFuture future; - - public Future getFuture() { - return future; - } - - /** - * Constructs a channel. - * - * @param name the name of the channel. - * @param server the server object this channel is associated with. - */ - public Channel(final String name, final Server server) { - this.name = name; - this.server = server; - this.server.getEventManager().addListener(this); - this.server.addChannel(this); - chanModeList = new ModeList(server, ""); - } - - /** - * Gets the name of the channel. - * - * @return the name of the channel - */ - public String getName() { - return name; - } - - public ModeList getModeList() { - return chanModeList; - } - - /** - * Gets the list of users in the channel. - * - * @return The list of users in the channel. - */ - public Collection getUsers() { - return users; - } - - /** - * Gets a user from the channel. - * - * @param nick The nick of the ChannelUser to get. - * @return The ChannelUser object associated with the nick or - * null. - */ - public ChannelUser getUser(final String nick) { - for (ChannelUser user : users) { - if (user.getNick().equalsIgnoreCase(nick)) { - return user; - } - } - return null; - } - - /** - * Adds a channel user to this channel. - * - * @param user the user to add - * @return true if it is added, false otherwise. - */ - public boolean addChannelUser(final ChannelUser user) { - return users.add(user); - } - - /** - * Removes a user from the channel. - * - * @param user the user to remove. - * @return true if they were removed, false otherwise. - */ - public boolean removeChannelUser(final ChannelUser user) { - return users.remove(user); - } - - /** - * Checks whether the channel will be auto-rejoined when kicked. - * - * @return true if auto-rejoin is on, false otherwise. - */ - public boolean isAutoRejoinOn() { - return autoRejoin; - } - - /** - * Sets whether rejoining is enabled when kicked - * - * @param on turn auto-rejoin on or not - */ - public void setAutoRejoin(final boolean on) { - autoRejoin = on; - } - - /** - * Leaves the channel. - * - * @param message The part message, can be null for no message. - */ - public void part(final String message) { - isRunning = false; - if (message != null && !message.isEmpty()) - server.sendRaw(String.format("PART %s :%s\n", name, message)); - else - server.sendRaw(String.format("PART %s\n", name)); - } - - public boolean isRunning() { - return isRunning; - } - - public void run() { - if (isRunning) { - server.sendRaw("WHO " + name); - future = server.getChanExec().schedule(this, whoDelay, - TimeUnit.MILLISECONDS); - } - - } - - /** - * Gets the server the channel is on. - * - * @return the server the channel is on - */ - public Server getServer() { - return server; - } - - /** - * Joins the channel. - */ - public void join() { - server.sendRaw("JOIN :" + name); - } - - public void setup() { - server.sendRaw("MODE " + name); - isRunning = true; - if (!server.hasChannel(this)) - server.addChannel(this); - future = server.getChanExec().schedule(this, 5000L, - TimeUnit.MILLISECONDS); - } - - public boolean isJoined() { - return isRunning(); - } - - /** - * Joins the channel using the provided password. - * - * @param password the password to join the channel with - */ - public void join(final String password) { - server.sendRaw("JOIN :" + name + " " + password); - setup(); - } - - /** - * Returns a sorted array of ChannelUser objects. This array is sorted by - * first descending channel rank and then by descending alphabetical order - * (by nick). - * - * @return the sorted array of users - */ - public ChannelUser[] getSortedUsers() { - final Collection users = getUsers(); - ChannelUser[] u = users.toArray(new ChannelUser[users.size()]); - Arrays.sort(u, new Comparator() { - - public int compare(ChannelUser o1, ChannelUser o2) { - int c = o2.getRights() - o1.getRights(); - if (c == 0) { - return o1.getNick().toLowerCase() - .compareTo(o2.getNick().toLowerCase()); - } - return c; - } - }); - return u; - } - - /** - * Bans then kicks the channel user with the reason specified. - * - * @param user the ChannelUser to kick. - * @param reason The reason for kicking the channel user, can be - * null. - */ - public void kickBan(final ChannelUser user, final String reason) { - ban(user); - kick(user, reason); - } - - /** - * Attempts to ban the specified ChannelUser. - * - * @param user the user that should be banned. - */ - public void ban(final ChannelUser user) { - final String banMask = "*!*@" + user.getHost(); - ban(banMask); - } - - /** - * Attempts to ban the specified mask. - * - * @param banMask The ban-mask that should be banned. - */ - public void ban(final String banMask) { - server.sendRaw(String.format("MODE %s +b %s\n", name, banMask)); - } - - /** - * Attempts to kick a channel user. - * - * @param user The ChannelUser that is to be kicked. - * @param reason The reason for kicking the channel user, can be - * null. - */ - public void kick(final ChannelUser user, String reason) { - if (reason == null) { - reason = user.getNick(); - } - server.sendRaw(String.format("KICK %s %s :%s\n", name, user.getNick(), - reason)); - } - - /** - * Attempts to kick a channel user. - * - * @param nick The nick of the user that is to be kicked. - * @param reason The reason for kicking the channel user, can be - * null. - */ - public void kick(final String nick, String reason) { - final ChannelUser user = getUser(nick); - if (user == null) { - return; - } - if (reason == null) { - reason = user.getNick(); - } - server.sendRaw(String.format("KICK %s %s :%s\n", name, user.getNick(), - reason)); - - } - - /** - * Sets the channel's topic. Attempts to send any changes to the server. - * - * @param topic The new channel topic. - */ - public void sendTopic(final String topic) { - server.sendRaw(String.format("TOPIC %s :%s\n", name, topic)); - } - - /** - * Sets the topic in the memory. - * - * @param newTopic the new channel topic - */ - public void setTopic(final String newTopic) { - this.topic = newTopic; - } - - /** - * Gets the topic. - * - * @return the channel's topic - */ - public String getTopic() { - return topic; - } - - @Override - public String toString() { - return name; - } - - @Override - public boolean equals(final Object o) { - return o instanceof Channel - && ((Channel) o).getName().equalsIgnoreCase(getName()); - } - - public Collection getChannelUsers(final Mask mask) { - final List users = new LinkedList(); - for (ChannelUser user : users) { - if (mask.matches(user)) { - users.add(user); - } - } - return users; - } - - public void channelUserJoined(ChannelUserEvent e) { - if (e.getChannel().equals(this)) { - if (getUser(e.getUser().getNick()) == null) { - addChannelUser(e.getUser()); - } else { - ChannelUser user = e.getChannel().getUser(e.getUser().getNick()); - user.user = e.getUser().getUser(); - user.host = e.getUser().getHost(); - } - if (e.getUser().getNick().equals(server.getNick()) && !isRunning()) { - setup(); - } - } - } - - public void channelUserParted(ChannelUserEvent e) { - if (e.getChannel().equals(this)) { - ChannelUser user = e.getUser(); - if (user != null) { - removeChannelUser(user); - if (user.getNick().equals(server.getNick())) { - isRunning = false; - future.cancel(true); - } - } - - } - } - - public void channelUserModeChanged(ModeChangedEvent e) { - } - - public void channelUserKicked(ChannelUserEvent e) { - if (e.getChannel().equals(this)) { - ChannelUser user = e.getUser(); - removeChannelUser(user); - if (user.getNick().equals(server.getNick()) && isAutoRejoinOn()) { - try { - Thread.sleep(autoRejoinDelay); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - isRunning = false; - server.getChannels().remove(this); - join(); - } else if (user.getNick().equals(server.getNick())) { - isRunning = false; - server.getChannels().remove(this); - } - } - } - - /** - * Sets a/many mode(s) on this channel. For example, to give a user voice - * via modes:
- * MODE #channel +vv-o nick1 nick2 nick2
- * One would need to use:
- * setMode("+vv-o", "nick1", "nick2", "nick2") - * - * @param mode the mode(s) to set. - * @param args the arguments of the mode, for example nicknames. - */ - public void setMode(String mode, String... args) { - StringBuilder arg = new StringBuilder(); - for (String s : args) { - arg.append(s).append(' '); - } - server.sendRaw(String.format("MODE %s %s %s", name, mode, - arg.toString())); - } - - /** - * Removes kick exempt from a mask. - * - * @param mask the mask to remove the kick exempt from. - */ - public void removeExempt(String mask) { - setMode("-e", mask); - } - - /** - * Removes kick exempt from a mask. - * - * @param mask the mask to remove the kick exempt from. - */ - public void removeExempt(Mask mask) { - removeExempt(mask.toString()); - } - - public void channelUserNickChanged(ChannelUserEvent e) { - final String newNick = e.getArgs()[1]; - if (e.getUser() != null) { - final ChannelUser user = e.getUser(); - final ChannelUser replace = new ChannelUser(newNick, - user.getModes(), user.getUser(), user.getHost(), - e.getChannel()); - e.getChannel().removeChannelUser(user); - e.getChannel().addChannelUser(replace); - } - } - - /** - * @return the topic set time - */ - public long getTopicSetTime() { - return topicSetTime; - } - - /** - * sets the topic set time, should only really be used internally - * - * @param topicSetTime the topic set time - */ - public void setTopicSetTime(long topicSetTime) { - this.topicSetTime = topicSetTime; - } - - /** - * @return the topic setter - */ - public String getTopicSetter() { - return topicSetter; - } - - /** - * sets the topic setter, should only really be used internally - * - * @param topicSetter the topic setter - */ - public void setTopicSetter(String topicSetter) { - this.topicSetter = topicSetter; - } - - public void channelUserQuit(ChannelUserEvent e) { - if (e.getChannel().equals(this)) { - ChannelUser user = e.getUser(); - removeChannelUser(user); - } - } -} \ No newline at end of file diff --git a/src/api/com/speed/irc/types/ChannelUser.java b/src/api/com/speed/irc/types/ChannelUser.java deleted file mode 100755 index 3a2b11b..0000000 --- a/src/api/com/speed/irc/types/ChannelUser.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.speed.irc.types; - -/** - * Represents a user in a channel. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ChannelUser extends ServerUser { - private String modes; - private ModeList channelModes; - private final Channel channel; - public static final int VOICE_FLAG = 0x1, HALF_OP_FLAG = 0x2, - OP_FLAG = 0x4, ADMIN_FLAG = 0x8, OWNER_FLAG = 0x10; - private int rights; - - public Channel getChannel() { - return channel; - } - - public ChannelUser(final String nick, final String modes, - final String user, final String host, final Channel channel) { - super(nick, host, user, channel.getServer()); - this.channel = channel; - this.channelModes = new ModeList(this.channel.server, ""); - this.modes = (modes); - if (!modes.isEmpty()) - sync(modes); - } - - public void sync(String modes) { - channelModes.clear(); - StringBuilder builder = new StringBuilder("+"); - for (char c : modes.toCharArray()) { - builder.append(channelModes.channelModeSymbolToLetter(c)); - } - channelModes.parse(builder.toString()); - char[] modeSymbols = channel.getServer().getModeSymbols(); - if (modeSymbols.length == 5) { - if (modes.indexOf(modeSymbols[0]) != -1) - rights = rights | OWNER_FLAG; - if (modes.indexOf(modeSymbols[1]) != -1) - rights = rights | ADMIN_FLAG; - if (modes.indexOf(modeSymbols[2]) != -1) - rights = rights | OP_FLAG; - if (modes.indexOf(modeSymbols[3]) != -1) - rights = rights | HALF_OP_FLAG; - if (modes.indexOf(modeSymbols[4]) != -1) - rights = rights | VOICE_FLAG; - } else if (modeSymbols.length == 2) { - if (modes.indexOf(modeSymbols[0]) != -1) - rights = rights | OP_FLAG; - if (modes.indexOf(modeSymbols[1]) != -1) - rights = rights | VOICE_FLAG; - } else if (modeSymbols.length == 3) { - if (modes.indexOf(modeSymbols[0]) != -1) - rights = rights | OP_FLAG; - if (modes.indexOf(modeSymbols[1]) != -1) - rights = rights | HALF_OP_FLAG; - if (modes.indexOf(modeSymbols[2]) != -1) - rights = rights | VOICE_FLAG; - } else if (modeSymbols.length == 4) { - if (modes.indexOf(modeSymbols[0]) != -1) - rights = rights | ADMIN_FLAG; - if (modes.indexOf(modeSymbols[1]) != -1) - rights = rights | OP_FLAG; - if (modes.indexOf(modeSymbols[2]) != -1) - rights = rights | HALF_OP_FLAG; - if (modes.indexOf(modeSymbols[3]) != -1) - rights = rights | VOICE_FLAG; - } - } - - public void addMode(char mode) { - mode = channelModes.channelModeLetterToSymbol(mode); - if (modes.indexOf(mode) < 0) { - modes = modes + mode; - sync(modes); - } - } - - public String getModes() { - return modes; - } - - public void removeExempts() { - for (final Mask mask : channel.exempts) { - if (mask.matches(this)) { - channel.removeExempt(mask); - } - } - } - - public void removeMode(char mode) { - mode = channelModes.channelModeLetterToSymbol(mode); - StringBuilder builder = new StringBuilder(); - for (char c : modes.toCharArray()) { - if (c != mode) { - builder.append(c); - } - } - modes = builder.toString(); - sync(modes); - } - - public boolean isOperator() { - return (getRights() & OP_FLAG) != 0; - } - - public boolean isHalfOperator() { - return (getRights() & HALF_OP_FLAG) != 0; - } - - public boolean isVoiced() { - return (getRights() & VOICE_FLAG) != 0; - } - - public boolean isOwner() { - return (getRights() & OWNER_FLAG) != 0; - } - - public boolean isProtected() { - return (getRights() & ADMIN_FLAG) != 0; - } - - /** - * Useful if you're only checking for a single flag. - * - * @returns the bitmask of the user's flags - */ - public int getRights() { - return rights; - } - - @Override - public String toString() { - return modes + getNick(); - } -} diff --git a/src/api/com/speed/irc/types/Conversable.java b/src/api/com/speed/irc/types/Conversable.java deleted file mode 100644 index c34462a..0000000 --- a/src/api/com/speed/irc/types/Conversable.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.connection.Server; - -/** - * An abstract representation of a communicable entity on a server. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public abstract class Conversable { - /** - * Sends a PRIVMSG message to the entity. - * - * @param message the message that is to be sent. - */ - public void sendMessage(final String message) { - getServer().sendMessage(new Privmsg(message, null, this)); - } - - /** - * Sends a NOTICE message to the entity. - * - * @param notice the notice that is to be sent. - */ - public void sendNotice(final String notice) { - getServer() - .sendNotice(new Notice(notice, null, getName(), getServer())); - } - - /** - * Gets the name of the entity. - * - * @return the name of the channel or user. - */ - public abstract String getName(); - - /** - * Gets the server this entity is on. - * - * @return the server. - */ - public abstract Server getServer(); - - public boolean isChannel() { - return this instanceof Channel; - } - - public boolean isUser() { - return this instanceof ServerUser; - } - - public Channel getChannel() { - return isChannel() ? (Channel) this : null; - } - - public ServerUser getServerUser() { - return isUser() ? (ServerUser) this : null; - } - - -} diff --git a/src/api/com/speed/irc/types/Mask.java b/src/api/com/speed/irc/types/Mask.java deleted file mode 100644 index f56be2e..0000000 --- a/src/api/com/speed/irc/types/Mask.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.util.ControlCodeFormatter; - -/** - * Class used to encapsulate user masks - *

- *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class Mask { - - private final String mask; - - /** - * Initialise the user mask - * - * @param mask the mask to use - */ - public Mask(final String mask) { - this.mask = mask.toLowerCase(); - if (!verify(mask)) - throw new IllegalArgumentException("Mask doesn't match *!*@*: " + mask); - } - - public Mask(final String nick, final String user, final String host) { - this.mask = (nick + '!' + user + '@' + host).toLowerCase(); - if (!verify(mask)) - throw new IllegalArgumentException("Arguments are not valid: " - + mask); - } - - /** - * Verifies if the mask is valid - * - * @param mask the mask to check - * @return true if the mask is valid, false if it isn't. - */ - public static boolean verify(final String mask) { - return mask - .matches("[a-zA-Z\\*][\\-\\\\\\[\\]\\^\\`\\*\\w\\|]*?!~?[\\-\\\\\\[\\]\\^\\`\\*\\w\\|]+?@[\\-\\\\\\[\\]\\^\\`\\*\\w\\.\\:" - + ControlCodeFormatter.UNICODE_COLOUR + "]+"); - } - - /** - * Checks if a user matches this mask. - * - * @param user the user to check - * @return true if they do match, false if they don't - */ - public boolean matches(ServerUser user) { - String nickMask = mask.substring(0, mask.indexOf('!')).replace("*", - ".*"); - String userMask = mask.substring(mask.indexOf('!') + 1, - mask.indexOf('@')).replace("*", ".*"); - String hostMask = mask.substring(mask.indexOf('@') + 1) - .replace("", "\\.").replace("*", ".*"); - return user.getNick().toLowerCase().matches(nickMask) - && user.getUser().toLowerCase().matches(userMask) - && user.getHost().toLowerCase().matches(hostMask); - } - - public boolean equals(Object o) { - return o instanceof Mask && ((Mask) o).mask.equals(mask); - } - - public String toString() { - return mask; - } -} diff --git a/src/api/com/speed/irc/types/Mode.java b/src/api/com/speed/irc/types/Mode.java deleted file mode 100644 index a7df9ed..0000000 --- a/src/api/com/speed/irc/types/Mode.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.connection.Server; - -/** - * A class representing a single user and channel mode. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class Mode { - - private final char mode; - private final boolean plus; - - public Mode(final String s) { - if (!s.matches("[\\+-][A-Za-z]")) { - throw new IllegalArgumentException("Incorrect mode format"); - } - this.mode = s.charAt(1); - this.plus = s.charAt(0) == '+'; - } - - public Mode(final boolean plus, final char mode) { - this.plus = plus; - this.mode = mode; - } - - public ModeList newModeList(final Server server) { - return new ModeList(server, toString()); - } - - - public String toString() { - return String.valueOf(plus ? '+' : '-') + mode; - } -} diff --git a/src/api/com/speed/irc/types/ModeList.java b/src/api/com/speed/irc/types/ModeList.java deleted file mode 100644 index 98278f8..0000000 --- a/src/api/com/speed/irc/types/ModeList.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.connection.Server; - -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -/** - * A class representing user and channel modes. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ModeList { - private Set modes = new CopyOnWriteArraySet(); - private final Server server; - - public ModeList(final Server server, final String modes) { - this.server = server; - if (!modes.isEmpty()) - parse(modes); - } - - - protected void clear() { - modes.clear(); - } - - public char channelModeLetterToSymbol(char letter) { - for (int i = 0; i < server.getModeLetters().length; i++) { - if (server.getModeLetters()[i] == letter) { - return server.getModeSymbols()[i]; - } - } - return '0'; - } - - public char channelModeSymbolToLetter(char symbol) { - for (int i = 0; i < server.getModeSymbols().length; i++) { - if (server.getModeSymbols()[i] == symbol) { - return server.getModeLetters()[i]; - } - } - return '0'; - } - - public String parse() { - if (modes.size() > 0) { - StringBuilder builder = new StringBuilder(modes.size()); - for (char c : modes) { - builder.append(c); - } - return '+' + builder.toString(); - } else { - return ""; - } - } - - public void parse(String modes) { - boolean plus = false; - for (int i = 0; i < modes.toCharArray().length; i++) { - char c = modes.toCharArray()[i]; - if (c == '+') { - plus = true; - continue; - } else if (c == '-') { - plus = false; - continue; - } - if (plus) { - - this.modes.add(c); - } else { - if (this.modes.contains(c)) - this.modes.remove(c); - - } - } - } -} diff --git a/src/api/com/speed/irc/types/Notice.java b/src/api/com/speed/irc/types/Notice.java deleted file mode 100644 index 60e81ef..0000000 --- a/src/api/com/speed/irc/types/Notice.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.connection.Server; - -import java.util.Arrays; - -/** - * A wrapper class for NOTICE messages. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see {@linkplain http://www.gnu.org/licenses/}. - * - * @author Shivam Mistry - */ -public class Notice { - private final String message, sender, target; - private final Server server; - - /** - * @param message The actual message. - * @param sender The nick of the person who the notice was sent to/from. - * @param target The channel the notice was sent to/from. - * @param server The server the notice should be sent on. - */ - public Notice(final String message, final String sender, - final String target, final Server server) { - this.message = message; - this.target = target; - this.sender = sender; - this.server = server; - } - - /** - * Gets the message parsed from the raw command. - * - * @return the message - */ - public String getMessage() { - return message; - } - - /** - * Get the sender of the notice. - * - * @return the nick of the notice sender - * @deprecated see {@link #getSenderNick()} instead - */ - public String getSender() { - return sender; - } - - /** - * Gets the nick of the sender - * - * @return the senders nick - */ - public String getSenderNick() { - return sender; - } - - /** - * Gets the target of the notice. - * - * @return the target of the notice. - */ - public Conversable getTarget() { - return Arrays.binarySearch(server.getChannelPrefix(), target.charAt(0)) >= 0 ? server.getChannel(target) : server - .getUser(target.toLowerCase()); - } - - /** - * Gets the channel the notice was sent to or from - * - * @return the channel the notice was sent to or from - * @deprecated see {@link #getTarget()} instead - */ - public String getChannel() { - return target; - } - - /** - * Gets the server this notice was sent on. - * - * @return the server this notice was sent on. - */ - public Server getServer() { - return server; - } -} diff --git a/src/api/com/speed/irc/types/ParsingException.java b/src/api/com/speed/irc/types/ParsingException.java deleted file mode 100644 index 1ddbd92..0000000 --- a/src/api/com/speed/irc/types/ParsingException.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.speed.irc.types; - -/** - * Represents an exception being thrown while parsing. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ParsingException extends Exception { - - private static final long serialVersionUID = 2238835287734082797L; - private final String msg; - private final Exception e; - - /** - * Initialises a ParsingException. - * - * @param msg the message - * @param e the exception - */ - public ParsingException(final String msg, final Exception e) { - this.msg = msg; - this.e = e; - - } - - public void printStackTrace() { - e.printStackTrace(); - } - - public String getMessage() { - return msg; - } - - /** - * Gets the exception - * - * @return the exception. - */ - public Exception getException() { - return e; - } - -} diff --git a/src/api/com/speed/irc/types/Privmsg.java b/src/api/com/speed/irc/types/Privmsg.java deleted file mode 100644 index f07945f..0000000 --- a/src/api/com/speed/irc/types/Privmsg.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.speed.irc.types; - -import java.util.Arrays; - -/** - * A wrapper class for PRIVMSGs. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class Privmsg { - - private final String message, sender; - private Conversable conversable; - - /** - * @param message The actual message. - * @param sender The nick of the person who the message was sent to/from. - * @param conversable The channel the message was sent to/from. - */ - public Privmsg(final String message, final String sender, - final Conversable conversable) { - this.message = message; - this.conversable = conversable; - this.sender = sender; - } - - - /* - * Gets the message sent - * - * @return the message - */ - public String getMessage() { - return message; - } - - /** - * Gets the sender - * - * @return the sender - */ - public String getSender() { - return sender; - } - - /** - * Gets the conversable object of the sender/channel - * - * @return the conversable object - */ - public Conversable getConversable() { - return conversable; - } - - /** - * Checks whether the message is a private message - * - * @return true if the message was sent privately, false otherwise - */ - public boolean isPrivateMessage() { - return !isChannelMessage(); - } - - /** - * Checks whether the message is a channel message - * - * @return true if the message was sent to a channel, - * false otherwise - */ - public boolean isChannelMessage() { - return Arrays.binarySearch(getConversable().getServer().getChannelPrefix(), getConversable().getName().charAt(0)) >= 0; - } - - /** - * Check if the message is a CTCP request/reply - * - * @return true if the message was a CTCP request/reply - */ - public boolean isCtcpMessage() { - return message.startsWith("\u0001"); - } - -} diff --git a/src/api/com/speed/irc/types/RawMessage.java b/src/api/com/speed/irc/types/RawMessage.java deleted file mode 100755 index 64dff17..0000000 --- a/src/api/com/speed/irc/types/RawMessage.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.connection.Server; - -/** - * Represents a raw message. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class RawMessage { - - private String raw, code, sender, target; - private Server server; - - /** - * Initialises a wrapper for raw messages. - * - * @param raw the raw message - * @param server the server the raw message was sent from - */ - public RawMessage(String raw, final Server server) { - this.raw = raw; - this.server = server; - String[] strings = raw.split(" "); - code = strings[1]; - sender = strings[0]; - if (strings.length > 2) - target = strings[2]; - - } - - /** - * Gets the raw message. - * - * @return the raw message. - */ - public String getRaw() { - return raw; - } - - /** - * Gets the command/code of this raw message. - * - * @return the command or code of this raw message. - */ - public String getCommand() { - return code; - } - - /** - * Gets the target of this raw message. - * - * @return the target of the message. - */ - public String getTarget() { - return target; - } - - /** - * Gets the sender of the message - * - * @return the sender of the message, in the form *!*@* - */ - public String getSender() { - return sender; - } - - /** - * Gets the server the raw message was sent on. - * - * @return the server the raw message was sent on. - */ - public Server getServer() { - return server; - } - -} diff --git a/src/api/com/speed/irc/types/ServerUser.java b/src/api/com/speed/irc/types/ServerUser.java deleted file mode 100644 index 5556c7a..0000000 --- a/src/api/com/speed/irc/types/ServerUser.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.connection.Server; - -/** - * A representation of a user an a server. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ServerUser extends Conversable { - protected String nick, host, user; - private Server server; - private boolean identified, away, oper; - private String realName; - - /** - * Initialises a server user. - * - * @param nick the nick of the user - * @param host the host of the user - * @param user the username of the user - * @param server the server the user is on - */ - public ServerUser(final String nick, final String host, final String user, - final Server server) { - this.nick = nick; - this.host = host; - this.user = user; - this.server = server; - getServer().addUser(this); - } - - public String toString() { - return String.format("%s!%s@%s", nick, user, host); - } - - /** - * Gets the mask of this user. - * - * @return the mask of the user - */ - public Mask getMask() { - return new Mask(getNick(), - getUser() == null || getUser().isEmpty() ? "*" : getUser(), - getHost() == null || getHost().isEmpty() ? "*" : getHost()); - } - - public void sendMessage(final String message) { - server.sendRaw(String.format("PRIVMSG %s :%s", nick, message)); - } - - public void sendNotice(final String notice) { - server.sendNotice(new Notice(notice, null, nick, server)); - } - - public String getName() { - return nick; - } - - /** - * Gets the nick of this user. - * - * @return the nick of the user - */ - public String getNick() { - return nick; - } - - /** - * Gets the host of the user. - * - * @return the users host. - */ - public String getHost() { - return host; - } - - /** - * Gets the username of this user. - * - * @return the username of this user - */ - public String getUser() { - return user; - } - - /** - * Gets the server this user is on - * - * @return the server this user is on - */ - public Server getServer() { - return server; - } - - /** - * Returns whether the user is identified. Some servers will not send this - * mode for users that are. - * - * @return whether the user is identified. - */ - public boolean isIdentified() { - return identified; - } - - /** - * Sets whether the user is identified. - * - * @param identified returns true if they are identified, false otherwise. - */ - public void setIdentified(boolean identified) { - this.identified = identified; - } - - /** - * Returns whether the user is away. - * - * @return whether the user is away. - */ - public boolean isAway() { - return away; - } - - /** - * Sets whether the user is away. - * - * @param away returns true if they are away, false otherwise. - */ - public void setAway(boolean away) { - this.away = away; - } - - /** - * Returns whether the user is a server operator. - * - * @return whether the user is a server operator. - */ - public boolean isOper() { - return oper; - } - - /** - * Sets whether the user is a server operator. - * - * @param oper returns true if they are an operator, false otherwise. - */ - public void setOper(boolean oper) { - this.oper = oper; - } - - public void setRealName(String realName) { - this.realName = realName; - } - - public String getRealName() { - return realName; - } - - public boolean equals(final Object o) { - if (!(o instanceof ServerUser)) - return false; - else { - ServerUser other = (ServerUser) o; - - return other != null && other.getNick().equalsIgnoreCase(nick); - } - } - - @Override - public int hashCode() { - return (getNick().hashCode() | getHost().hashCode() | getUser() - .hashCode()) & 0xfffffff; - } - - public void requestWhois() { - getServer().sendRaw("WHOIS " + getName()); - getServer().addWhoisWaiting(this); - } - -} diff --git a/src/api/com/speed/irc/types/Whois.java b/src/api/com/speed/irc/types/Whois.java deleted file mode 100644 index be7fdb3..0000000 --- a/src/api/com/speed/irc/types/Whois.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.speed.irc.types; - -import com.speed.irc.connection.Server; -import com.speed.irc.util.Numerics; - -import java.util.Collection; -import java.util.Collections; - -/** - * Represents a collection of WHOIS replies. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class Whois { - private Collection whois; - private Channel[] channels; - private ServerUser user; - private Server server; - - public Whois(final Collection whois, final Server server) { - this.whois = whois; - this.server = server; - parse(); - - } - - public ServerUser getUser() { - return user; - } - - public Channel[] getChannels() { - return channels; - } - - public Server getServer() { - return server; - } - - private void parse() { - for (RawMessage m : whois) { - if (user == null) { - user = server.getUser(m.getRaw().split(" ")[3]); - } - if (m.getCommand().equals(Numerics.WHOIS_CHANNELS)) { - String[] channels = m.getRaw().split(" :", 2)[1].split(" "); - this.channels = new Channel[channels.length]; - for (int i = 0; i < channels.length; i++) { - String name = channels[i]; - String mode = ""; - if (name.charAt(0) != '#') { - mode += name.charAt(0); - name = name.substring(1); - } - Channel c = new Channel(name, server); - if (c.getUser(user.getNick()) == null) { - c.addChannelUser(new ChannelUser(user.getNick(), mode, - user.getUser(), user.getHost(), c)); - } else { - ChannelUser cu = c.getUser(user.getNick()); - cu.addMode(mode.charAt(0)); - } - this.channels[i] = c; - } - } else if (m.getCommand().equals(Numerics.WHOIS_NAME)) { - String msg = m.getRaw(); - String[] parts = msg.split(" "); - String nick = parts[3]; - String user = parts[4]; - String host = parts[5]; - String realName = msg.split(" :", 2)[1]; - this.user = new ServerUser(nick, host, user, server); - this.user.setRealName(realName); - } - } - } - - public Collection getMessages() { - return Collections.unmodifiableCollection(whois); - } - -} diff --git a/src/api/com/speed/irc/util/ControlCodeFormatter.java b/src/api/com/speed/irc/util/ControlCodeFormatter.java deleted file mode 100644 index 8f60a6c..0000000 --- a/src/api/com/speed/irc/util/ControlCodeFormatter.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.speed.irc.util; - -import java.awt.*; - -/** - * Formats messages with control codes, using a specified 'format' character. - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public class ControlCodeFormatter { - public static final char UNICODE_COLOUR = '\u0003'; - public static final char UNICODE_BOLD = '\u0002'; - public static final char UNICODE_UNDERLINE = '\u001F'; - - private static char format_character = '$'; - - private char formatChar; - - public ControlCodeFormatter() { - formatChar = '$'; - } - - public ControlCodeFormatter(final char format_char) { - formatChar = format_char; - } - - public enum Colour { - WHITE, BLACK, NAVY_BLUE, GREEN, RED, CRIMSON_RED, MAGENTA, BROWN, YELLOW, LIME, TEAL, AQUA, ROYAL_BLUE, PINK, DARK_GREY, LIGHT_GREY; - public static final Color[] COLORS = new Color[]{Color.WHITE, - Color.BLACK, new Color(0x000080), Color.GREEN, Color.RED, - new Color(0xE8000D), Color.MAGENTA, new Color(0x8b4513), - Color.YELLOW, new Color(0x32cd32), new Color(0x008080), - new Color(0x00FFFF), new Color(0x4169e1), Color.PINK, - Color.DARK_GRAY, Color.LIGHT_GRAY}; - } - - /** - * Sets the default character to be replaced with colour control code in - * {@link #format(String, Colour...)} - * - * @param c the new format character - */ - public void setFormatChar(final char c) { - formatChar = c; - } - - /** - * Gets the default character to be replaced with colour control code in - * {@link #format(String, Colour...)} - * - * @return the format character - */ - public char getFormatChar() { - return formatChar; - } - - /** - * Sets the default character to be replaced with colour control code in - * {@link #format(String, Colour...)} - * - * @param c the new format character - * @deprecated Use the instance instead {@link #setFormatChar(char)} - */ - public static void setFormatCharacter(final char c) { - format_character = c; - } - - /** - * Gets the default character to be replaced with colour control code in - * {@link #format(String, Colour...)} - * - * @return the format character - * @deprecated Use the instance instead {@link #getFormatChar()} - */ - public static char getFormatCharacter() { - return format_character; - } - - /** - * Formats the string with the colours specified. Default format character - * is '$' and any format character is escaped using '\'. - * - * @param s The string to be formatted. - * @param colours The colours to format the string with. - * @return the formatted string - */ - public String formatString(final String s, final Colour... colours) { - final StringBuilder builder = new StringBuilder(); - if (colours.length == 0) - return s; - int replaced = 0; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (replaced >= colours.length) { - if (c == '\\' && s.charAt(i + 1) == formatChar) { - builder.append(formatChar); - i++; - } else { - builder.append(c); - } - continue; - } else if (c == formatChar) { - if (i != 0 && s.charAt(i - 1) == '\\') { - builder.deleteCharAt(builder.lastIndexOf("\\")); - builder.append(c); - continue; - } - builder.append(UNICODE_COLOUR).append(colours[replaced++].ordinal()); - - } else { - builder.append(c); - } - } - return builder.toString() + ControlCodeFormatter.UNICODE_COLOUR; - } - - /** - * Formats the string with the colours specified. Default format character - * is '$' and any format character is escaped using '\'. - *

- * Will be retained for fast formatting using the default char $ - * - * @param s The string to be formatted. - * @param colours The colours to format the string with. - * @return the formatted string - */ - public static String format(final String s, final Colour... colours) { - final StringBuilder builder = new StringBuilder(); - if (colours.length == 0) - return s; - int replaced = 0; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (replaced >= colours.length) { - if (c == '\\' && s.charAt(i + 1) == format_character) { - builder.append(format_character); - i++; - } else { - builder.append(c); - } - continue; - } else if (c == format_character) { - if (i != 0) { - if (s.charAt(i - 1) == '\\') { - builder.deleteCharAt(builder.lastIndexOf("\\")); - builder.append(c); - continue; - } - } - builder.append(UNICODE_COLOUR).append(colours[replaced++].ordinal()); - - } else { - builder.append(c); - } - } - return builder.toString() + ControlCodeFormatter.UNICODE_COLOUR; - } -} diff --git a/src/api/com/speed/irc/util/Numerics.java b/src/api/com/speed/irc/util/Numerics.java deleted file mode 100755 index ffe2300..0000000 --- a/src/api/com/speed/irc/util/Numerics.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.speed.irc.util; - -/** - * Stores IRC numerics used by the API internal classes. Numerics are stored as - * strings to allow easy comparison. (numerics are parsed as strings) - *

- * This file is part of Speed's IRC API. - *

- * Speed's IRC API is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - *

- * Speed's IRC API is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - *

- * You should have received a copy of the GNU Lesser General Public License - * along with Speed's IRC API. If not, see . - * - * @author Shivam Mistry - */ -public interface Numerics { - String WHO_RESPONSE = "352"; - String WHO_END = "315"; - String CHANNEL_NAMES = "353"; - String CHANNEL_TOPIC = "332", CHANNEL_TOPIC_SET = "333"; - String CHANNEL_NAMES_END = "366"; - String SERVER_SUPPORT = "005"; - String NOT_AN_OPERATOR = "482"; - String CHANNEL_MODES = "324"; - String CHANNEL_IS_FULL = "471", INVITE_ONLY_CHANNEL = "473", - BANNED_FROM_CHANNEL = "474", BAD_CHANNEL_KEY = "475", - BAD_CHANNEL_MASK = "476"; - // whois numerics - String WHOIS_NAME = "311", WHOIS_CHANNELS = "319", WHOIS_SERVER = "312", - WHOIS_OPERATOR = "313", WHOIS_IDLE = "317"; - String WHOIS_END = "318"; - String[] WHOIS = new String[]{WHOIS_NAME, WHOIS_CHANNELS, WHOIS_SERVER, - WHOIS_OPERATOR, WHOIS_IDLE, WHOIS_END}; -}