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.DccDownloadFailed;
40 import net.pterodactylus.irc.event.DccDownloadFinished;
41 import net.pterodactylus.irc.event.DccSendReceived;
42 import net.pterodactylus.irc.event.PrivateMessageReceived;
43 import net.pterodactylus.irc.util.MessageCleaner;
44 import net.pterodactylus.irc.util.RandomNickname;
45 import net.pterodactylus.xdcc.core.event.BotAdded;
46 import net.pterodactylus.xdcc.core.event.CoreStarted;
47 import net.pterodactylus.xdcc.core.event.DownloadFailed;
48 import net.pterodactylus.xdcc.core.event.DownloadFinished;
49 import net.pterodactylus.xdcc.core.event.DownloadStarted;
50 import net.pterodactylus.xdcc.core.event.MessageReceived;
51 import net.pterodactylus.xdcc.data.Bot;
52 import net.pterodactylus.xdcc.data.Channel;
53 import net.pterodactylus.xdcc.data.Download;
54 import net.pterodactylus.xdcc.data.Network;
55 import net.pterodactylus.xdcc.data.Pack;
56 import net.pterodactylus.xdcc.data.Server;
58 import com.google.common.base.Optional;
59 import com.google.common.collect.HashBasedTable;
60 import com.google.common.collect.ImmutableSet;
61 import com.google.common.collect.Lists;
62 import com.google.common.collect.Maps;
63 import com.google.common.collect.Sets;
64 import com.google.common.collect.Table;
65 import com.google.common.eventbus.EventBus;
66 import com.google.common.eventbus.Subscribe;
67 import com.google.common.io.Closeables;
68 import com.google.common.util.concurrent.AbstractIdleService;
69 import com.google.inject.Inject;
72 * The core of XDCC Downloader.
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public class Core extends AbstractIdleService {
79 private static final Logger logger = Logger.getLogger(Core.class.getName());
82 private final EventBus eventBus;
84 /** The temporary directory to download files to. */
85 private final String temporaryDirectory;
87 /** The directory to move finished downloads to. */
88 private final String finalDirectory;
90 /** The channels that should be monitored. */
91 private final Collection<Channel> channels = Sets.newHashSet();
93 /** The channels that are currentlymonitored. */
94 private final Collection<Channel> joinedChannels = Sets.newHashSet();
96 /** The channels that are joined but not configured. */
97 private final Collection<Channel> extraChannels = Sets.newHashSet();
99 /** The current network connections. */
100 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
102 /** The currently known bots. */
103 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
105 /** The current downloads. */
106 private final Map<String, Download> downloads = Maps.newHashMap();
108 /** The current DCC receivers. */
109 private final Collection<DccReceiver> dccReceivers = Sets.newHashSet();
112 * Creates a new core.
116 * @param temporaryDirectory
117 * The directory to download files to
118 * @param finalDirectory
119 * The directory to move finished files to
122 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
123 this.eventBus = eventBus;
124 this.temporaryDirectory = temporaryDirectory;
125 this.finalDirectory = finalDirectory;
133 * Returns all configured channels. Due to various circumstances, configured
134 * channels might not actually be joined.
136 * @return All configured channels
138 public Collection<Channel> channels() {
139 return ImmutableSet.copyOf(channels);
143 * Returns all currently joined channels.
145 * @return All currently joined channels
147 public Collection<Channel> joinedChannels() {
148 return ImmutableSet.copyOf(joinedChannels);
152 * Returns all currently joined channels that are not configured.
154 * @return All currently joined but not configured channels
156 public Collection<Channel> extraChannels() {
157 return ImmutableSet.copyOf(extraChannels);
161 * Returns all currently known bots.
163 * @return All currently known bots
165 public Collection<Bot> bots() {
166 return networkBots.values();
170 * Returns the currently active DCC receivers.
172 * @return The currently active DCC receivers
174 public Collection<DccReceiver> dccReceivers() {
183 * Adds a channel to monitor.
186 * The channel to monitor
188 public void addChannel(Channel channel) {
189 channels.add(channel);
193 * Fetches the given pack from the given bot.
196 * The bot to fetch the pack from
200 public void fetch(Bot bot, Pack pack) {
201 Connection connection = networkConnections.get(bot.network());
202 if (connection == null) {
206 Download download = new Download(bot, pack);
207 downloads.put(pack.name(), download);
210 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
211 } catch (IOException ioe1) {
212 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
217 // ABSTRACTIDLESERVICE METHODS
221 protected void startUp() {
222 for (Channel channel : channels) {
223 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
224 if (!networkConnections.containsKey(channel.network())) {
225 /* select a random server. */
226 List<Server> servers = Lists.newArrayList(channel.network().servers());
227 Server server = servers.get((int) (Math.random() * servers.size()));
228 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
229 connection.username(RandomNickname.get()).realName(RandomNickname.get());
230 networkConnections.put(channel.network(), connection);
235 /* notify listeners. */
236 eventBus.post(new CoreStarted(this));
240 protected void shutDown() {
248 * If a connection to a network has been established, the channels associated
249 * with this network are joined.
251 * @param connectionEstablished
252 * The connection established event
255 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
257 /* get network for connection. */
258 Optional<Network> network = getNetwork(connectionEstablished.connection());
261 if (!network.isPresent()) {
265 /* join all channels on this network. */
266 for (Channel channel : channels) {
267 if (channel.network().equals(network.get())) {
269 connectionEstablished.connection().joinChannel(channel.name());
270 } catch (IOException ioe1) {
271 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
278 * Shows a message when a channel was joined by us.
280 * @param channelJoined
281 * The channel joined event
284 public void channelJoined(ChannelJoined channelJoined) {
285 if (channelJoined.connection().isSource(channelJoined.client())) {
286 Optional<Network> network = getNetwork(channelJoined.connection());
287 if (!network.isPresent()) {
291 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
292 if (!channel.isPresent()) {
293 /* it’s an extra channel. */
294 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
295 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
299 joinedChannels.add(channel.get());
300 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
305 * If a message on a channel is received, it is parsed for pack information
306 * with is then added to a bot.
308 * @param channelMessageReceived
309 * The channel message received event
312 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
313 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
314 if (!message.startsWith("#")) {
315 /* most probably not a pack announcement. */
319 Optional<Network> network = getNetwork(channelMessageReceived.connection());
320 if (!network.isPresent()) {
321 /* message for unknown connection? */
325 /* parse pack information. */
326 Optional<Pack> pack = parsePack(message);
327 if (!pack.isPresent()) {
332 synchronized (networkBots) {
333 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
334 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
335 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
336 eventBus.post(new BotAdded(bot));
338 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
343 bot.addPack(pack.get());
344 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
348 * Forward all private messages to every console.
350 * @param privateMessageReceived
351 * The private message recevied event
354 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
355 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
359 * Starts a DCC download.
361 * @param dccSendReceived
365 public void dccSendReceived(DccSendReceived dccSendReceived) {
366 Optional<Network> network = getNetwork(dccSendReceived.connection());
367 if (!network.isPresent()) {
371 Download download = downloads.get(dccSendReceived.filename());
372 if (download == null) {
373 /* unknown download, ignore. */
377 logger.info(String.format("Starting download of %s.", dccSendReceived.filename()));
379 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
380 OutputStream fileOutputStream = new FileOutputStream(outputFile);
381 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
382 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
383 dccReceivers.add(dccReceiver);
385 eventBus.post(new DownloadStarted(download));
386 } catch (FileNotFoundException fnfe1) {
387 logger.log(Level.WARNING, "Could not open file for download!", fnfe1);
392 * Closes the output stream of the download and moves the file to the final
395 * @param dccDownloadFinished
396 * The DCC download finished event
399 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
400 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
401 if (download == null) {
402 /* probably shouldn’t happen. */
407 download.outputStream().close();
408 File file = new File(download.filename());
409 file.renameTo(new File(finalDirectory, download.pack().name()));
410 eventBus.post(new DownloadFinished(download));
411 dccReceivers.remove(dccDownloadFinished.dccReceiver());
412 downloads.remove(download);
413 } catch (IOException ioe1) {
414 /* TODO - handle all the errors. */
415 logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
420 * Closes the output stream and notifies all listeners of the failure.
422 * @param dccDownloadFailed
423 * The DCC download failed event
426 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
427 Download download = downloads.get(dccDownloadFailed.dccReceiver().filename());
428 if (download == null) {
429 /* probably shouldn’t happen. */
434 Closeables.close(download.outputStream(), true);
435 eventBus.post(new DownloadFailed(download));
436 dccReceivers.remove(dccDownloadFailed.dccReceiver());
437 downloads.remove(download);
438 } catch (IOException ioe1) {
439 /* swallow silently. */
448 * Searches all current connections for the given connection, returning the
449 * associated network.
452 * The connection to get the network for
453 * @return The network belonging to the connection, or {@link
456 private Optional<Network> getNetwork(Connection connection) {
457 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
458 if (networkConnectionEntry.getValue().equals(connection)) {
459 return Optional.of(networkConnectionEntry.getKey());
462 return Optional.absent();
466 * Returns the configured channel for the given network and name.
469 * The network the channel is located on
471 * The name of the channel
472 * @return The configured channel, or {@link Optional#absent()} if no
473 * configured channel matching the given network and name was found
475 public Optional<Channel> getChannel(Network network, String channelName) {
476 for (Channel channel : channels) {
477 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
478 return Optional.of(channel);
481 return Optional.absent();
485 * Parses {@link Pack} information from the given message.
488 * The message to parse pack information from
489 * @return The parsed pack, or {@link Optional#absent()} if the message could
490 * not be parsed into a pack
492 private Optional<Pack> parsePack(String message) {
493 int squareOpen = message.indexOf('[');
494 int squareClose = message.indexOf(']', squareOpen);
495 if ((squareOpen == -1) && (squareClose == -1)) {
496 return Optional.absent();
498 String packSize = message.substring(squareOpen + 1, squareClose);
499 String packName = message.substring(message.lastIndexOf(' ') + 1);
500 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
501 return Optional.of(new Pack(packIndex, packSize, packName));