2 * XdccDownloader - Core.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.xdcc.core;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
29 import net.pterodactylus.irc.Connection;
30 import net.pterodactylus.irc.ConnectionBuilder;
31 import net.pterodactylus.irc.event.ChannelMessageReceived;
32 import net.pterodactylus.irc.event.ConnectionEstablished;
33 import net.pterodactylus.irc.util.MessageCleaner;
34 import net.pterodactylus.irc.util.RandomNickname;
35 import net.pterodactylus.xdcc.core.event.BotAdded;
36 import net.pterodactylus.xdcc.core.event.CoreStarted;
37 import net.pterodactylus.xdcc.data.Bot;
38 import net.pterodactylus.xdcc.data.Channel;
39 import net.pterodactylus.xdcc.data.Network;
40 import net.pterodactylus.xdcc.data.Pack;
41 import net.pterodactylus.xdcc.data.Server;
43 import com.beust.jcommander.internal.Maps;
44 import com.beust.jcommander.internal.Sets;
45 import com.google.common.base.Optional;
46 import com.google.common.collect.HashBasedTable;
47 import com.google.common.collect.Lists;
48 import com.google.common.collect.Table;
49 import com.google.common.eventbus.EventBus;
50 import com.google.common.eventbus.Subscribe;
51 import com.google.common.util.concurrent.AbstractIdleService;
52 import com.google.inject.Inject;
55 * The core of XDCC Downloader.
57 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59 public class Core extends AbstractIdleService {
62 private static final Logger logger = Logger.getLogger(Core.class.getName());
65 private final EventBus eventBus;
67 /** The channels that should be monitored. */
68 private final Collection<Channel> channels = Sets.newHashSet();
70 /** The current network connections. */
71 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
73 /** The currently known bots. */
74 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
83 public Core(EventBus eventBus) {
84 this.eventBus = eventBus;
92 * Returns all currently known bots.
94 * @return All currently known bots
96 public Collection<Bot> bots() {
97 return networkBots.values();
105 * Adds a channel to monitor.
108 * The channel to monitor
110 public void addChannel(Channel channel) {
111 channels.add(channel);
115 // ABSTRACTIDLESERVICE METHODS
119 protected void startUp() {
120 for (Channel channel : channels) {
121 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
122 if (!networkConnections.containsKey(channel.network())) {
123 /* select a random server. */
124 List<Server> servers = Lists.newArrayList(channel.network().servers());
125 Server server = servers.get((int) (Math.random() * servers.size()));
126 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
127 connection.username(RandomNickname.get()).realName(RandomNickname.get());
128 networkConnections.put(channel.network(), connection);
133 /* notify listeners. */
134 eventBus.post(new CoreStarted(this));
138 protected void shutDown() {
146 * If a connection to a network has been established, the channels associated
147 * with this network are joined.
149 * @param connectionEstablished
150 * The connection established event
153 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
155 /* get network for connection. */
156 Optional<Network> network = getNetwork(connectionEstablished.connection());
159 if (!network.isPresent()) {
163 /* join all channels on this network. */
164 for (Channel channel : channels) {
165 if (channel.network().equals(network.get())) {
167 connectionEstablished.connection().joinChannel(channel.name());
168 } catch (IOException ioe1) {
169 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
176 * If a message on a channel is received, it is parsed for pack information
177 * with is then added to a bot.
179 * @param channelMessageReceived
180 * The channel message received event
183 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
184 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
185 if (!message.startsWith("#")) {
186 /* most probably not a pack announcement. */
190 Optional<Network> network = getNetwork(channelMessageReceived.connection());
191 if (!network.isPresent()) {
192 /* message for unknown connection? */
196 /* parse pack information. */
197 Optional<Pack> pack = parsePack(message);
198 if (!pack.isPresent()) {
203 synchronized (networkBots) {
204 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
205 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
206 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
207 eventBus.post(new BotAdded(bot));
209 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
214 bot.addPack(pack.get());
215 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
223 * Searches all current connections for the given connection, returning the
224 * associated network.
227 * The connection to get the network for
228 * @return The network belonging to the connection, or {@link
231 private Optional<Network> getNetwork(Connection connection) {
232 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
233 if (networkConnectionEntry.getValue().equals(connection)) {
234 return Optional.of(networkConnectionEntry.getKey());
237 return Optional.absent();
241 * Parses {@link Pack} information from the given message.
244 * The message to parse pack information from
245 * @return The parsed pack, or {@link Optional#absent()} if the message could
246 * not be parsed into a pack
248 private Optional<Pack> parsePack(String message) {
249 int squareOpen = message.indexOf('[');
250 int squareClose = message.indexOf(']', squareOpen);
251 if ((squareOpen == -1) && (squareClose == -1)) {
252 return Optional.absent();
254 String packSize = message.substring(squareOpen + 1, squareClose);
255 String packName = message.substring(message.lastIndexOf(' ') + 1);
256 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
257 return Optional.of(new Pack(packIndex, packSize, packName));