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.ChannelJoined;
37 import net.pterodactylus.irc.event.ChannelMessageReceived;
38 import net.pterodactylus.irc.event.ConnectionEstablished;
39 import net.pterodactylus.irc.event.DccSendReceived;
40 import net.pterodactylus.irc.util.MessageCleaner;
41 import net.pterodactylus.irc.util.RandomNickname;
42 import net.pterodactylus.xdcc.core.event.BotAdded;
43 import net.pterodactylus.xdcc.core.event.CoreStarted;
44 import net.pterodactylus.xdcc.data.Bot;
45 import net.pterodactylus.xdcc.data.Channel;
46 import net.pterodactylus.xdcc.data.Download;
47 import net.pterodactylus.xdcc.data.Network;
48 import net.pterodactylus.xdcc.data.Pack;
49 import net.pterodactylus.xdcc.data.Server;
51 import com.google.common.base.Optional;
52 import com.google.common.collect.HashBasedTable;
53 import com.google.common.collect.ImmutableSet;
54 import com.google.common.collect.Lists;
55 import com.google.common.collect.Maps;
56 import com.google.common.collect.Sets;
57 import com.google.common.collect.Table;
58 import com.google.common.eventbus.EventBus;
59 import com.google.common.eventbus.Subscribe;
60 import com.google.common.util.concurrent.AbstractIdleService;
61 import com.google.inject.Inject;
64 * The core of XDCC Downloader.
66 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
68 public class Core extends AbstractIdleService {
71 private static final Logger logger = Logger.getLogger(Core.class.getName());
74 private final EventBus eventBus;
76 /** The temporary directory to download files to. */
77 private final String temporaryDirectory;
79 /** The directory to move finished downloads to. */
80 private final String finalDirectory;
82 /** The channels that should be monitored. */
83 private final Collection<Channel> channels = Sets.newHashSet();
85 /** The channels that are currentlymonitored. */
86 private final Collection<Channel> joinedChannels = Sets.newHashSet();
88 /** The channels that are joined but not configured. */
89 private final Collection<Channel> extraChannels = Sets.newHashSet();
91 /** The current network connections. */
92 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
94 /** The currently known bots. */
95 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
97 /** The current downloads. */
98 private final Map<String, Download> downloads = Maps.newHashMap();
100 /** The current DCC receivers. */
101 private final Collection<DccReceiver> dccReceivers = Sets.newHashSet();
104 * Creates a new core.
108 * @param temporaryDirectory
109 * The directory to download files to
110 * @param finalDirectory
111 * The directory to move finished files to
114 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
115 this.eventBus = eventBus;
116 this.temporaryDirectory = temporaryDirectory;
117 this.finalDirectory = finalDirectory;
125 * Returns all configured channels. Due to various circumstances, configured
126 * channels might not actually be joined.
128 * @return All configured channels
130 public Collection<Channel> channels() {
131 return ImmutableSet.copyOf(channels);
135 * Returns all currently joined channels.
137 * @return All currently joined channels
139 public Collection<Channel> joinedChannels() {
140 return ImmutableSet.copyOf(joinedChannels);
144 * Returns all currently joined channels that are not configured.
146 * @return All currently joined but not configured channels
148 public Collection<Channel> extraChannels() {
149 return ImmutableSet.copyOf(extraChannels);
153 * Returns all currently known bots.
155 * @return All currently known bots
157 public Collection<Bot> bots() {
158 return networkBots.values();
162 * Returns the currently active DCC receivers.
164 * @return The currently active DCC receivers
166 public Collection<DccReceiver> dccReceivers() {
175 * Adds a channel to monitor.
178 * The channel to monitor
180 public void addChannel(Channel channel) {
181 channels.add(channel);
185 * Fetches the given pack from the given bot.
188 * The bot to fetch the pack from
192 public void fetch(Bot bot, Pack pack) {
193 Connection connection = networkConnections.get(bot.network());
194 if (connection == null) {
198 Download download = new Download(bot, pack);
199 downloads.put(pack.name(), download);
202 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
203 } catch (IOException ioe1) {
204 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
209 // ABSTRACTIDLESERVICE METHODS
213 protected void startUp() {
214 for (Channel channel : channels) {
215 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
216 if (!networkConnections.containsKey(channel.network())) {
217 /* select a random server. */
218 List<Server> servers = Lists.newArrayList(channel.network().servers());
219 Server server = servers.get((int) (Math.random() * servers.size()));
220 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
221 connection.username(RandomNickname.get()).realName(RandomNickname.get());
222 networkConnections.put(channel.network(), connection);
227 /* notify listeners. */
228 eventBus.post(new CoreStarted(this));
232 protected void shutDown() {
240 * If a connection to a network has been established, the channels associated
241 * with this network are joined.
243 * @param connectionEstablished
244 * The connection established event
247 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
249 /* get network for connection. */
250 Optional<Network> network = getNetwork(connectionEstablished.connection());
253 if (!network.isPresent()) {
257 /* join all channels on this network. */
258 for (Channel channel : channels) {
259 if (channel.network().equals(network.get())) {
261 connectionEstablished.connection().joinChannel(channel.name());
262 } catch (IOException ioe1) {
263 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
270 * Shows a message when a channel was joined by us.
272 * @param channelJoined
273 * The channel joined event
276 public void channelJoined(ChannelJoined channelJoined) {
277 if (channelJoined.connection().isSource(channelJoined.client())) {
278 Optional<Network> network = getNetwork(channelJoined.connection());
279 if (!network.isPresent()) {
283 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
284 if (!channel.isPresent()) {
285 /* it’s an extra channel. */
286 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
287 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
291 joinedChannels.add(channel.get());
292 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
297 * If a message on a channel is received, it is parsed for pack information
298 * with is then added to a bot.
300 * @param channelMessageReceived
301 * The channel message received event
304 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
305 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
306 if (!message.startsWith("#")) {
307 /* most probably not a pack announcement. */
311 Optional<Network> network = getNetwork(channelMessageReceived.connection());
312 if (!network.isPresent()) {
313 /* message for unknown connection? */
317 /* parse pack information. */
318 Optional<Pack> pack = parsePack(message);
319 if (!pack.isPresent()) {
324 synchronized (networkBots) {
325 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
326 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
327 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
328 eventBus.post(new BotAdded(bot));
330 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
335 bot.addPack(pack.get());
336 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
340 * Starts a DCC download.
342 * @param dccSendReceived
346 public void dccSendReceived(DccSendReceived dccSendReceived) {
347 logger.info(String.format("Starting download of %s.", dccSendReceived.filename()));
349 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
350 OutputStream fileOutputStream = new FileOutputStream(outputFile);
351 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
352 dccReceivers.add(dccReceiver);
354 } catch (FileNotFoundException fnfe1) {
355 logger.log(Level.WARNING, "Could not open file for download!", fnfe1);
364 * Searches all current connections for the given connection, returning the
365 * associated network.
368 * The connection to get the network for
369 * @return The network belonging to the connection, or {@link
372 private Optional<Network> getNetwork(Connection connection) {
373 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
374 if (networkConnectionEntry.getValue().equals(connection)) {
375 return Optional.of(networkConnectionEntry.getKey());
378 return Optional.absent();
382 * Returns the configured channel for the given network and name.
385 * The network the channel is located on
387 * The name of the channel
388 * @return The configured channel, or {@link Optional#absent()} if no
389 * configured channel matching the given network and name was found
391 public Optional<Channel> getChannel(Network network, String channelName) {
392 for (Channel channel : channels) {
393 if (channel.network().equals(network) && (channel.name().equals(channelName))) {
394 return Optional.of(channel);
397 return Optional.absent();
401 * Parses {@link Pack} information from the given message.
404 * The message to parse pack information from
405 * @return The parsed pack, or {@link Optional#absent()} if the message could
406 * not be parsed into a pack
408 private Optional<Pack> parsePack(String message) {
409 int squareOpen = message.indexOf('[');
410 int squareClose = message.indexOf(']', squareOpen);
411 if ((squareOpen == -1) && (squareClose == -1)) {
412 return Optional.absent();
414 String packSize = message.substring(squareOpen + 1, squareClose);
415 String packName = message.substring(message.lastIndexOf(' ') + 1);
416 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
417 return Optional.of(new Pack(packIndex, packSize, packName));