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 static net.pterodactylus.irc.util.MessageCleaner.getDefaultInstance;
21 import static net.pterodactylus.xdcc.data.Channel.TO_NETWORK;
22 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
25 import java.io.FileNotFoundException;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.OutputStream;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Iterator;
32 import java.util.List;
34 import java.util.Map.Entry;
35 import java.util.concurrent.TimeUnit;
37 import net.pterodactylus.irc.Connection;
38 import net.pterodactylus.irc.ConnectionBuilder;
39 import net.pterodactylus.irc.DccReceiver;
40 import net.pterodactylus.irc.event.ChannelJoined;
41 import net.pterodactylus.irc.event.ChannelLeft;
42 import net.pterodactylus.irc.event.ChannelMessageReceived;
43 import net.pterodactylus.irc.event.ClientQuit;
44 import net.pterodactylus.irc.event.ConnectionClosed;
45 import net.pterodactylus.irc.event.ConnectionEstablished;
46 import net.pterodactylus.irc.event.ConnectionFailed;
47 import net.pterodactylus.irc.event.DccAcceptReceived;
48 import net.pterodactylus.irc.event.DccDownloadFailed;
49 import net.pterodactylus.irc.event.DccDownloadFinished;
50 import net.pterodactylus.irc.event.DccSendReceived;
51 import net.pterodactylus.irc.event.NicknameChanged;
52 import net.pterodactylus.irc.event.PrivateMessageReceived;
53 import net.pterodactylus.irc.event.PrivateNoticeReceived;
54 import net.pterodactylus.irc.event.ReplyReceived;
55 import net.pterodactylus.irc.util.RandomNickname;
56 import net.pterodactylus.xdcc.core.event.BotAdded;
57 import net.pterodactylus.xdcc.core.event.CoreStarted;
58 import net.pterodactylus.xdcc.core.event.DownloadFailed;
59 import net.pterodactylus.xdcc.core.event.DownloadFinished;
60 import net.pterodactylus.xdcc.core.event.DownloadStarted;
61 import net.pterodactylus.xdcc.core.event.GenericError;
62 import net.pterodactylus.xdcc.core.event.GenericMessage;
63 import net.pterodactylus.xdcc.core.event.MessageReceived;
64 import net.pterodactylus.xdcc.data.Bot;
65 import net.pterodactylus.xdcc.data.Channel;
66 import net.pterodactylus.xdcc.data.Download;
67 import net.pterodactylus.xdcc.data.Network;
68 import net.pterodactylus.xdcc.data.Pack;
69 import net.pterodactylus.xdcc.data.Server;
71 import com.google.common.base.Function;
72 import com.google.common.base.Optional;
73 import com.google.common.base.Predicate;
74 import com.google.common.collect.FluentIterable;
75 import com.google.common.collect.HashBasedTable;
76 import com.google.common.collect.HashMultimap;
77 import com.google.common.collect.ImmutableList;
78 import com.google.common.collect.ImmutableSet;
79 import com.google.common.collect.Lists;
80 import com.google.common.collect.Maps;
81 import com.google.common.collect.Multimap;
82 import com.google.common.collect.Sets;
83 import com.google.common.collect.Table;
84 import com.google.common.eventbus.EventBus;
85 import com.google.common.eventbus.Subscribe;
86 import com.google.common.io.Closeables;
87 import com.google.common.util.concurrent.AbstractExecutionThreadService;
88 import com.google.inject.Inject;
89 import org.apache.log4j.Logger;
92 * The core of XDCC Downloader.
94 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
96 public class Core extends AbstractExecutionThreadService {
99 private static final Logger logger = Logger.getLogger(Core.class.getName());
101 /** The event bus. */
102 private final EventBus eventBus;
104 /** The temporary directory to download files to. */
105 private final String temporaryDirectory;
107 /** The directory to move finished downloads to. */
108 private final String finalDirectory;
110 /** The channels that should be monitored. */
111 private final Collection<Channel> channels = Sets.newHashSet();
113 /** The channels that are currentlymonitored. */
114 private final Collection<Channel> joinedChannels = Sets.newHashSet();
116 /** The channels that are joined but not configured. */
117 private final Collection<Channel> extraChannels = Sets.newHashSet();
119 /** The current network connections. */
120 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
122 /** The currently known bots. */
123 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
125 /** The current downloads. */
126 private final Multimap<String, Download> downloads = HashMultimap.create();
128 /** The current DCC receivers. */
129 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
132 * Creates a new core.
136 * @param temporaryDirectory
137 * The directory to download files to
138 * @param finalDirectory
139 * The directory to move finished files to
142 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
143 this.eventBus = eventBus;
144 this.temporaryDirectory = temporaryDirectory;
145 this.finalDirectory = finalDirectory;
153 * Returns all currently known connections.
155 * @return All currently known connections
157 public Collection<Connection> connections() {
158 return networkConnections.values();
162 * Returns all defined networks.
164 * @return All defined networks
166 public Collection<Network> networks() {
167 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
171 * Returns all connected networks.
173 * @return All connected networks
175 public Collection<Network> connectedNetworks() {
176 return Lists.newArrayList(Optional.presentInstances(FluentIterable.from(networkConnections.values()).transform(new Function<Connection, Optional<Network>>() {
178 public Optional<Network> apply(Connection connection) {
179 return getNetwork(connection);
185 * Returns all configured channels. Due to various circumstances, configured
186 * channels might not actually be joined.
188 * @return All configured channels
190 public Collection<Channel> channels() {
191 return ImmutableSet.copyOf(channels);
195 * Returns all currently joined channels.
197 * @return All currently joined channels
199 public Collection<Channel> joinedChannels() {
200 return ImmutableSet.copyOf(joinedChannels);
204 * Returns all currently joined channels that are not configured.
206 * @return All currently joined but not configured channels
208 public Collection<Channel> extraChannels() {
209 return ImmutableSet.copyOf(extraChannels);
213 * Returns all currently known bots.
215 * @return All currently known bots
217 public Collection<Bot> bots() {
218 return networkBots.values();
222 * Returns all currently running downloads.
224 * @return All currently running downloads
226 public Collection<Download> downloads() {
227 return downloads.values();
235 * Adds a channel to monitor.
238 * The channel to monitor
240 public void addChannel(Channel channel) {
241 channels.add(channel);
245 * Fetches the given pack from the given bot.
248 * The bot to fetch the pack from
252 public void fetch(Bot bot, Pack pack) {
253 Connection connection = networkConnections.get(bot.network());
254 if (connection == null) {
258 /* check if we are already downloading the file? */
259 if (downloads.containsKey(pack.name())) {
260 Collection<Download> packDownloads = downloads.get(pack.name());
261 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
262 if (!runningDownloads.isEmpty()) {
263 Download download = runningDownloads.iterator().next();
264 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
267 StringBuilder bots = new StringBuilder();
268 for (Download download : packDownloads) {
269 if (bots.length() > 0) {
272 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
274 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
277 Download download = new Download(bot, pack);
278 downloads.put(pack.name(), download);
281 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
282 } catch (IOException ioe1) {
283 logger.warn("Could not send message to bot!", ioe1);
288 * Cancels the download of the given pack from the given bot.
291 * The bot the pack is being downloaded from
293 * The pack being downloaded
295 public void cancelDownload(Bot bot, Pack pack) {
296 Optional<Download> download = getDownload(pack, bot);
297 if (!download.isPresent()) {
301 /* get connection. */
302 Connection connection = networkConnections.get(bot.network());
303 if (connection == null) {
304 /* request for unknown network? */
308 /* stop the DCC receiver. */
309 if (download.get().dccReceiver() != null) {
310 download.get().dccReceiver().stop();
312 /* remove download if it hasn’t started yet. */
313 downloads.remove(pack.name(), download.get());
316 /* remove the request from the bot, too. */
318 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
319 } catch (IOException ioe1) {
320 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
325 * Closes the given connection.
328 * The connection to close
330 public void closeConnection(Connection connection) {
333 } catch (IOException ioe1) {
339 // ABSTRACTIDLESERVICE METHODS
343 protected void startUp() {
344 for (Channel channel : channels) {
345 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
346 connectNetwork(channel.network());
349 /* notify listeners. */
350 eventBus.post(new CoreStarted(this));
354 protected void run() throws Exception {
355 while (isRunning()) {
357 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
358 } catch (InterruptedException ie1) {
362 /* find channels that should be monitored but are not. */
363 for (Channel channel : channels) {
364 if (joinedChannels.contains(channel)) {
368 connectNetwork(channel.network());
369 Connection connection = networkConnections.get(channel.network());
370 if (connection.established()) {
371 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
373 connection.joinChannel(channel.name());
374 } catch (IOException ioe1) {
375 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
383 protected void shutDown() {
391 * Starts a new connection for the given network if no such connection exists
395 * The network to connect to
397 private void connectNetwork(Network network) {
398 if (!networkConnections.containsKey(network)) {
399 /* select a random server. */
400 List<Server> servers = Lists.newArrayList(network.servers());
401 if (servers.isEmpty()) {
402 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
405 Server server = servers.get((int) (Math.random() * servers.size()));
406 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
407 connection.username(RandomNickname.get()).realName(RandomNickname.get());
408 networkConnections.put(network, connection);
414 * Removes the given connection and all its channels and bots.
417 * The connection to remove
419 private void removeConnection(Connection connection) {
420 Optional<Network> network = getNetwork(connection);
421 if (!network.isPresent()) {
425 /* find all channels that need to be removed. */
426 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
427 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
428 Channel joinedChannel = channelIterator.next();
429 if (!joinedChannel.network().equals(network.get())) {
433 channelIterator.remove();
437 /* now remove all bots for that network. */
438 Map<String, Bot> bots = networkBots.row(network.get());
439 int botCount = bots.size();
441 for (Bot bot : bots.values()) {
442 packCount += bot.packs().size();
445 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
447 /* now remove the network. */
448 networkConnections.remove(network.get());
456 * If a connection to a network has been established, the channels associated
457 * with this network are joined.
459 * @param connectionEstablished
460 * The connection established event
463 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
465 /* get network for connection. */
466 Optional<Network> network = getNetwork(connectionEstablished.connection());
469 if (!network.isPresent()) {
470 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
474 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
476 /* join all channels on this network. */
477 for (Channel channel : channels) {
478 if (channel.network().equals(network.get())) {
480 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
481 connectionEstablished.connection().joinChannel(channel.name());
482 } catch (IOException ioe1) {
483 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
490 * Remove all data stored for a network if the connection is closed.
492 * @param connectionClosed
493 * The connection closed event
496 public void connectionClosed(ConnectionClosed connectionClosed) {
497 removeConnection(connectionClosed.connection());
501 * Remove all data stored for a network if the connection fails.
503 * @param connectionFailed
504 * The connection failed event
507 public void connectionFailed(ConnectionFailed connectionFailed) {
508 removeConnection(connectionFailed.connection());
512 * Shows a message when a channel was joined by us.
514 * @param channelJoined
515 * The channel joined event
518 public void channelJoined(ChannelJoined channelJoined) {
519 if (channelJoined.connection().isSource(channelJoined.client())) {
520 Optional<Network> network = getNetwork(channelJoined.connection());
521 if (!network.isPresent()) {
525 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
526 if (!channel.isPresent()) {
527 /* it’s an extra channel. */
528 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
529 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
533 joinedChannels.add(channel.get());
534 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
539 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
542 * The channel left event
545 public void channelLeft(ChannelLeft channelLeft) {
546 Optional<Network> network = getNetwork(channelLeft.connection());
547 if (!network.isPresent()) {
551 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
553 /* maybe it was us? */
554 if (channelLeft.connection().isSource(channelLeft.client())) {
555 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
556 if (!channel.isPresent()) {
557 /* maybe it was an extra channel? */
558 channel = getExtraChannel(network.get(), channelLeft.channel());
559 if (!channel.isPresent()) {
560 /* okay, whatever. */
564 extraChannels.remove(channel);
566 channels.remove(channel.get());
569 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
575 networkBots.remove(network.get(), channelLeft.client().nick().get());
579 * Removes a client (which may be a bot) from the table of known bots.
582 * The client quit event
585 public void clientQuit(ClientQuit clientQuit) {
586 Optional<Network> network = getNetwork(clientQuit.connection());
587 if (!network.isPresent()) {
591 networkBots.remove(network.get(), clientQuit.client().nick().get());
595 * If the nickname of a bit changes, remove it from the old name and store it
596 * under the new name.
598 * @param nicknameChanged
599 * The nickname changed event
602 public void nicknameChanged(NicknameChanged nicknameChanged) {
603 Optional<Network> network = getNetwork(nicknameChanged.connection());
604 if (!network.isPresent()) {
608 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
613 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
617 * If a message on a channel is received, it is parsed for pack information
618 * with is then added to a bot.
620 * @param channelMessageReceived
621 * The channel message received event
624 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
625 String message = getDefaultInstance().clean(channelMessageReceived.message());
626 if (!message.startsWith("#")) {
627 /* most probably not a pack announcement. */
631 Optional<Network> network = getNetwork(channelMessageReceived.connection());
632 if (!network.isPresent()) {
633 /* message for unknown connection? */
637 /* parse pack information. */
638 Optional<Pack> pack = parsePack(message);
639 if (!pack.isPresent()) {
644 synchronized (networkBots) {
645 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
646 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
647 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
648 eventBus.post(new BotAdded(bot));
650 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
655 bot.addPack(pack.get());
656 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
660 * Forward all private messages to every console.
662 * @param privateMessageReceived
663 * The private message recevied event
666 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
667 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
671 * Sends a message to all console when a notice was received.
673 * @param privateNoticeReceived
674 * The notice received event
677 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
678 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
679 if (!network.isPresent()) {
683 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
687 * Starts a DCC download.
689 * @param dccSendReceived
693 public void dccSendReceived(final DccSendReceived dccSendReceived) {
694 final Optional<Network> network = getNetwork(dccSendReceived.connection());
695 if (!network.isPresent()) {
699 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
700 if (packDownloads.isEmpty()) {
701 /* unknown download, ignore. */
705 /* check if it’s already downloading. */
706 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
707 if (!runningDownloads.isEmpty()) {
708 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
712 /* locate the correct download. */
713 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
716 public boolean apply(Download download) {
717 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
721 /* we did not request this download. */
722 if (requestedDownload.isEmpty()) {
726 Download download = requestedDownload.iterator().next();
728 /* check if the file already exists. */
729 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
730 if (outputFile.exists()) {
731 long existingFileSize = outputFile.length();
733 /* file already complete? */
734 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
735 /* file is apparently already complete. just move it. */
736 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
737 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
739 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
742 /* remove download. */
743 downloads.removeAll(download.pack().name());
747 /* file not complete yet, DCC resume it. */
749 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
750 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
751 } catch (IOException ioe1) {
752 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
758 /* file does not exist, start the download. */
760 OutputStream fileOutputStream = new FileOutputStream(outputFile);
761 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
762 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
763 dccReceivers.add(dccReceiver);
765 eventBus.post(new DownloadStarted(download));
766 } catch (FileNotFoundException fnfe1) {
767 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
772 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
773 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
774 if (!network.isPresent()) {
778 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
779 if (packDownloads.isEmpty()) {
780 /* unknown download, ignore. */
784 /* check if it’s already downloading. */
785 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
786 if (!runningDownloads.isEmpty()) {
787 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
791 /* locate the correct download. */
792 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
795 public boolean apply(Download download) {
796 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
800 /* we did not request this download. */
801 if (requestedDownload.isEmpty()) {
805 Download download = requestedDownload.iterator().next();
808 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
809 if (outputFile.length() != dccAcceptReceived.position()) {
810 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
811 logger.warn(String.format("Download %s from %s: have %d bytes but wants to resume from %d!", dccAcceptReceived.filename(), dccAcceptReceived.source(), outputFile.length(), dccAcceptReceived.position()));
813 downloads.removeAll(download.pack().name());
816 OutputStream outputStream = new FileOutputStream(outputFile, true);
817 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
818 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
819 dccReceivers.add(dccReceiver);
821 eventBus.post(new DownloadStarted(download));
822 } catch (FileNotFoundException fnfe1) {
827 * Closes the output stream of the download and moves the file to the final
830 * @param dccDownloadFinished
831 * The DCC download finished event
834 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
836 /* locate the correct download. */
837 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
838 if (requestedDownload.isEmpty()) {
839 /* this seems wrong. */
840 logger.warn("Download finished but could not be located.");
843 Download download = requestedDownload.iterator().next();
846 download.outputStream().close();
847 File file = new File(download.filename());
848 file.renameTo(new File(finalDirectory, download.pack().name()));
849 eventBus.post(new DownloadFinished(download));
850 dccReceivers.remove(dccDownloadFinished.dccReceiver());
851 downloads.removeAll(download.pack().name());
852 } catch (IOException ioe1) {
853 /* TODO - handle all the errors. */
854 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
859 * Closes the output stream and notifies all listeners of the failure.
861 * @param dccDownloadFailed
862 * The DCC download failed event
865 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
867 /* locate the correct download. */
868 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
869 if (requestedDownload.isEmpty()) {
870 /* this seems wrong. */
871 logger.warn("Download finished but could not be located.");
874 Download download = requestedDownload.iterator().next();
877 Closeables.close(download.outputStream(), true);
878 eventBus.post(new DownloadFailed(download));
879 dccReceivers.remove(dccDownloadFailed.dccReceiver());
880 downloads.removeAll(download.pack().name());
881 } catch (IOException ioe1) {
882 /* swallow silently. */
887 public void replyReceived(ReplyReceived replyReceived) {
888 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
896 * Returns the download of the given pack from the given bot.
899 * The pack being downloaded
901 * The bot the pack is being downloaded from
902 * @return The download, or {@link Optional#absent()} if the download could not
905 private Optional<Download> getDownload(Pack pack, Bot bot) {
906 if (!downloads.containsKey(pack.name())) {
907 return Optional.absent();
909 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
910 if (download.bot().equals(bot)) {
911 return Optional.of(download);
914 return Optional.absent();
918 * Searches all current connections for the given connection, returning the
919 * associated network.
922 * The connection to get the network for
923 * @return The network belonging to the connection, or {@link
926 private Optional<Network> getNetwork(Connection connection) {
927 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
928 if (networkConnectionEntry.getValue().equals(connection)) {
929 return Optional.of(networkConnectionEntry.getKey());
932 return Optional.absent();
936 * Returns the configured channel for the given network and name.
939 * The network the channel is located on
941 * The name of the channel
942 * @return The configured channel, or {@link Optional#absent()} if no
943 * configured channel matching the given network and name was found
945 public Optional<Channel> getChannel(Network network, String channelName) {
946 for (Channel channel : channels) {
947 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
948 return Optional.of(channel);
951 return Optional.absent();
955 * Returns the extra channel for the given network and name.
958 * The network the channel is located on
960 * The name of the channel
961 * @return The extra channel, or {@link Optional#absent()} if no extra channel
962 * matching the given network and name was found
964 public Optional<Channel> getExtraChannel(Network network, String channelName) {
965 for (Channel channel : extraChannels) {
966 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
967 return Optional.of(channel);
970 return Optional.absent();
974 * Parses {@link Pack} information from the given message.
977 * The message to parse pack information from
978 * @return The parsed pack, or {@link Optional#absent()} if the message could
979 * not be parsed into a pack
981 private Optional<Pack> parsePack(String message) {
982 int squareOpen = message.indexOf('[');
983 int squareClose = message.indexOf(']', squareOpen);
984 if ((squareOpen == -1) && (squareClose == -1)) {
985 return Optional.absent();
987 String packSize = message.substring(squareOpen + 1, squareClose);
988 String packName = message.substring(message.lastIndexOf(' ') + 1);
989 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
990 return Optional.of(new Pack(packIndex, packSize, packName));