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;
21 import java.io.FileNotFoundException;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStream;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
33 import net.pterodactylus.irc.Connection;
34 import net.pterodactylus.irc.ConnectionBuilder;
35 import net.pterodactylus.irc.DccReceiver;
36 import net.pterodactylus.irc.event.ChannelMessageReceived;
37 import net.pterodactylus.irc.event.ConnectionEstablished;
38 import net.pterodactylus.irc.event.DccSendReceived;
39 import net.pterodactylus.irc.util.MessageCleaner;
40 import net.pterodactylus.irc.util.RandomNickname;
41 import net.pterodactylus.xdcc.core.event.BotAdded;
42 import net.pterodactylus.xdcc.core.event.CoreStarted;
43 import net.pterodactylus.xdcc.data.Bot;
44 import net.pterodactylus.xdcc.data.Channel;
45 import net.pterodactylus.xdcc.data.Network;
46 import net.pterodactylus.xdcc.data.Pack;
47 import net.pterodactylus.xdcc.data.Server;
49 import com.google.common.base.Optional;
50 import com.google.common.collect.HashBasedTable;
51 import com.google.common.collect.Lists;
52 import com.google.common.collect.Maps;
53 import com.google.common.collect.Sets;
54 import com.google.common.collect.Table;
55 import com.google.common.eventbus.EventBus;
56 import com.google.common.eventbus.Subscribe;
57 import com.google.common.util.concurrent.AbstractIdleService;
58 import com.google.inject.Inject;
61 * The core of XDCC Downloader.
63 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
65 public class Core extends AbstractIdleService {
68 private static final Logger logger = Logger.getLogger(Core.class.getName());
71 private final EventBus eventBus;
73 /** The channels that should be monitored. */
74 private final Collection<Channel> channels = Sets.newHashSet();
76 /** The current network connections. */
77 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
79 /** The currently known bots. */
80 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
82 /** The current DCC receivers. */
83 private final Collection<DccReceiver> dccReceivers = Sets.newHashSet();
92 public Core(EventBus eventBus) {
93 this.eventBus = eventBus;
101 * Returns all currently known bots.
103 * @return All currently known bots
105 public Collection<Bot> bots() {
106 return networkBots.values();
110 * Returns the currently active DCC receivers.
112 * @return The currently active DCC receivers
114 public Collection<DccReceiver> dccReceivers() {
123 * Adds a channel to monitor.
126 * The channel to monitor
128 public void addChannel(Channel channel) {
129 channels.add(channel);
133 * Fetches the given pack from the given bot.
136 * The bot to fetch the pack from
140 public void fetch(Bot bot, Pack pack) {
141 Connection connection = networkConnections.get(bot.network());
142 if (connection == null) {
147 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
148 } catch (IOException ioe1) {
149 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
154 // ABSTRACTIDLESERVICE METHODS
158 protected void startUp() {
159 for (Channel channel : channels) {
160 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
161 if (!networkConnections.containsKey(channel.network())) {
162 /* select a random server. */
163 List<Server> servers = Lists.newArrayList(channel.network().servers());
164 Server server = servers.get((int) (Math.random() * servers.size()));
165 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
166 connection.username(RandomNickname.get()).realName(RandomNickname.get());
167 networkConnections.put(channel.network(), connection);
172 /* notify listeners. */
173 eventBus.post(new CoreStarted(this));
177 protected void shutDown() {
185 * If a connection to a network has been established, the channels associated
186 * with this network are joined.
188 * @param connectionEstablished
189 * The connection established event
192 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
194 /* get network for connection. */
195 Optional<Network> network = getNetwork(connectionEstablished.connection());
198 if (!network.isPresent()) {
202 /* join all channels on this network. */
203 for (Channel channel : channels) {
204 if (channel.network().equals(network.get())) {
206 connectionEstablished.connection().joinChannel(channel.name());
207 } catch (IOException ioe1) {
208 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
215 * If a message on a channel is received, it is parsed for pack information
216 * with is then added to a bot.
218 * @param channelMessageReceived
219 * The channel message received event
222 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
223 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
224 if (!message.startsWith("#")) {
225 /* most probably not a pack announcement. */
229 Optional<Network> network = getNetwork(channelMessageReceived.connection());
230 if (!network.isPresent()) {
231 /* message for unknown connection? */
235 /* parse pack information. */
236 Optional<Pack> pack = parsePack(message);
237 if (!pack.isPresent()) {
242 synchronized (networkBots) {
243 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
244 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
245 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
246 eventBus.post(new BotAdded(bot));
248 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
253 bot.addPack(pack.get());
254 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
258 * Starts a DCC download.
260 * @param dccSendReceived
264 public void dccSendReceived(DccSendReceived dccSendReceived) {
265 logger.info(String.format("Starting download of %s.", dccSendReceived.filename()));
267 OutputStream fileOutputStream = new FileOutputStream(new File("/home/bombe/Temp", dccSendReceived.filename()));
268 DccReceiver dccReceiver = new DccReceiver(dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
269 dccReceivers.add(dccReceiver);
271 } catch (FileNotFoundException fnfe1) {
272 logger.log(Level.WARNING, "Could not open file for download!", fnfe1);
281 * Searches all current connections for the given connection, returning the
282 * associated network.
285 * The connection to get the network for
286 * @return The network belonging to the connection, or {@link
289 private Optional<Network> getNetwork(Connection connection) {
290 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
291 if (networkConnectionEntry.getValue().equals(connection)) {
292 return Optional.of(networkConnectionEntry.getKey());
295 return Optional.absent();
299 * Parses {@link Pack} information from the given message.
302 * The message to parse pack information from
303 * @return The parsed pack, or {@link Optional#absent()} if the message could
304 * not be parsed into a pack
306 private Optional<Pack> parsePack(String message) {
307 int squareOpen = message.indexOf('[');
308 int squareClose = message.indexOf(']', squareOpen);
309 if ((squareOpen == -1) && (squareClose == -1)) {
310 return Optional.absent();
312 String packSize = message.substring(squareOpen + 1, squareClose);
313 String packName = message.substring(message.lastIndexOf(' ') + 1);
314 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
315 return Optional.of(new Pack(packIndex, packSize, packName));