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;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
39 import net.pterodactylus.irc.Connection;
40 import net.pterodactylus.irc.ConnectionBuilder;
41 import net.pterodactylus.irc.DccReceiver;
42 import net.pterodactylus.irc.event.ChannelJoined;
43 import net.pterodactylus.irc.event.ChannelLeft;
44 import net.pterodactylus.irc.event.ChannelMessageReceived;
45 import net.pterodactylus.irc.event.ClientQuit;
46 import net.pterodactylus.irc.event.ConnectionClosed;
47 import net.pterodactylus.irc.event.ConnectionEstablished;
48 import net.pterodactylus.irc.event.ConnectionFailed;
49 import net.pterodactylus.irc.event.DccAcceptReceived;
50 import net.pterodactylus.irc.event.DccDownloadFailed;
51 import net.pterodactylus.irc.event.DccDownloadFinished;
52 import net.pterodactylus.irc.event.DccSendReceived;
53 import net.pterodactylus.irc.event.NicknameChanged;
54 import net.pterodactylus.irc.event.PrivateMessageReceived;
55 import net.pterodactylus.irc.event.PrivateNoticeReceived;
56 import net.pterodactylus.irc.event.ReplyReceived;
57 import net.pterodactylus.irc.util.RandomNickname;
58 import net.pterodactylus.xdcc.core.event.BotAdded;
59 import net.pterodactylus.xdcc.core.event.CoreStarted;
60 import net.pterodactylus.xdcc.core.event.DownloadFailed;
61 import net.pterodactylus.xdcc.core.event.DownloadFinished;
62 import net.pterodactylus.xdcc.core.event.DownloadStarted;
63 import net.pterodactylus.xdcc.core.event.GenericError;
64 import net.pterodactylus.xdcc.core.event.GenericMessage;
65 import net.pterodactylus.xdcc.core.event.MessageReceived;
66 import net.pterodactylus.xdcc.data.Bot;
67 import net.pterodactylus.xdcc.data.Channel;
68 import net.pterodactylus.xdcc.data.Download;
69 import net.pterodactylus.xdcc.data.Network;
70 import net.pterodactylus.xdcc.data.Pack;
71 import net.pterodactylus.xdcc.data.Server;
73 import com.google.common.base.Function;
74 import com.google.common.base.Optional;
75 import com.google.common.base.Predicate;
76 import com.google.common.collect.FluentIterable;
77 import com.google.common.collect.HashBasedTable;
78 import com.google.common.collect.HashMultimap;
79 import com.google.common.collect.ImmutableList;
80 import com.google.common.collect.ImmutableSet;
81 import com.google.common.collect.Lists;
82 import com.google.common.collect.Maps;
83 import com.google.common.collect.Multimap;
84 import com.google.common.collect.Sets;
85 import com.google.common.collect.Table;
86 import com.google.common.eventbus.EventBus;
87 import com.google.common.eventbus.Subscribe;
88 import com.google.common.io.Closeables;
89 import com.google.common.util.concurrent.AbstractExecutionThreadService;
90 import com.google.inject.Inject;
93 * The core of XDCC Downloader.
95 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
97 public class Core extends AbstractExecutionThreadService {
100 private static final Logger logger = Logger.getLogger(Core.class.getName());
102 /** The event bus. */
103 private final EventBus eventBus;
105 /** The temporary directory to download files to. */
106 private final String temporaryDirectory;
108 /** The directory to move finished downloads to. */
109 private final String finalDirectory;
111 /** The channels that should be monitored. */
112 private final Collection<Channel> channels = Sets.newHashSet();
114 /** The channels that are currentlymonitored. */
115 private final Collection<Channel> joinedChannels = Sets.newHashSet();
117 /** The channels that are joined but not configured. */
118 private final Collection<Channel> extraChannels = Sets.newHashSet();
120 /** The current network connections. */
121 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
123 /** The currently known bots. */
124 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
126 /** The current downloads. */
127 private final Multimap<String, Download> downloads = HashMultimap.create();
129 /** The current DCC receivers. */
130 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
133 * Creates a new core.
137 * @param temporaryDirectory
138 * The directory to download files to
139 * @param finalDirectory
140 * The directory to move finished files to
143 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
144 this.eventBus = eventBus;
145 this.temporaryDirectory = temporaryDirectory;
146 this.finalDirectory = finalDirectory;
154 * Returns all currently known connections.
156 * @return All currently known connections
158 public Collection<Connection> connections() {
159 return networkConnections.values();
163 * Returns all defined networks.
165 * @return All defined networks
167 public Collection<Network> networks() {
168 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
172 * Returns all connected networks.
174 * @return All connected networks
176 public Collection<Network> connectedNetworks() {
177 return Lists.newArrayList(Optional.presentInstances(FluentIterable.from(networkConnections.values()).transform(new Function<Connection, Optional<Network>>() {
179 public Optional<Network> apply(Connection connection) {
180 return getNetwork(connection);
186 * Returns all configured channels. Due to various circumstances, configured
187 * channels might not actually be joined.
189 * @return All configured channels
191 public Collection<Channel> channels() {
192 return ImmutableSet.copyOf(channels);
196 * Returns all currently joined channels.
198 * @return All currently joined channels
200 public Collection<Channel> joinedChannels() {
201 return ImmutableSet.copyOf(joinedChannels);
205 * Returns all currently joined channels that are not configured.
207 * @return All currently joined but not configured channels
209 public Collection<Channel> extraChannels() {
210 return ImmutableSet.copyOf(extraChannels);
214 * Returns all currently known bots.
216 * @return All currently known bots
218 public Collection<Bot> bots() {
219 return networkBots.values();
223 * Returns all currently running downloads.
225 * @return All currently running downloads
227 public Collection<Download> downloads() {
228 return downloads.values();
236 * Adds a channel to monitor.
239 * The channel to monitor
241 public void addChannel(Channel channel) {
242 channels.add(channel);
246 * Fetches the given pack from the given bot.
249 * The bot to fetch the pack from
253 public void fetch(Bot bot, Pack pack) {
254 Connection connection = networkConnections.get(bot.network());
255 if (connection == null) {
259 /* check if we are already downloading the file? */
260 if (downloads.containsKey(pack.name())) {
261 Collection<Download> packDownloads = downloads.get(pack.name());
262 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
263 if (!runningDownloads.isEmpty()) {
264 Download download = runningDownloads.iterator().next();
265 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
268 StringBuilder bots = new StringBuilder();
269 for (Download download : packDownloads) {
270 if (bots.length() > 0) {
273 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
275 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
278 Download download = new Download(bot, pack);
279 downloads.put(pack.name(), download);
282 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
283 } catch (IOException ioe1) {
284 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
289 * Cancels the download of the given pack from the given bot.
292 * The bot the pack is being downloaded from
294 * The pack being downloaded
296 public void cancelDownload(Bot bot, Pack pack) {
297 Optional<Download> download = getDownload(pack, bot);
298 if (!download.isPresent()) {
302 /* get connection. */
303 Connection connection = networkConnections.get(bot.network());
304 if (connection == null) {
305 /* request for unknown network? */
309 /* stop the DCC receiver. */
310 if (download.get().dccReceiver() != null) {
311 download.get().dccReceiver().stop();
313 /* remove download if it hasn’t started yet. */
314 downloads.remove(pack.name(), download.get());
317 /* remove the request from the bot, too. */
319 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
320 } catch (IOException ioe1) {
321 logger.log(Level.WARNING, String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
326 * Closes the given connection.
329 * The connection to close
331 public void closeConnection(Connection connection) {
334 } catch (IOException ioe1) {
340 // ABSTRACTIDLESERVICE METHODS
344 protected void startUp() {
345 for (Channel channel : channels) {
346 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
347 connectNetwork(channel.network());
350 /* notify listeners. */
351 eventBus.post(new CoreStarted(this));
355 protected void run() throws Exception {
356 while (isRunning()) {
358 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
359 } catch (InterruptedException ie1) {
363 /* find channels that should be monitored but are not. */
364 for (Channel channel : channels) {
365 if (joinedChannels.contains(channel)) {
369 connectNetwork(channel.network());
370 Connection connection = networkConnections.get(channel.network());
371 if (connection.established()) {
372 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
374 connection.joinChannel(channel.name());
375 } catch (IOException ioe1) {
376 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
384 protected void shutDown() {
392 * Starts a new connection for the given network if no such connection exists
396 * The network to connect to
398 private void connectNetwork(Network network) {
399 if (!networkConnections.containsKey(network)) {
400 /* select a random server. */
401 List<Server> servers = Lists.newArrayList(network.servers());
402 if (servers.isEmpty()) {
403 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
406 Server server = servers.get((int) (Math.random() * servers.size()));
407 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
408 connection.username(RandomNickname.get()).realName(RandomNickname.get());
409 networkConnections.put(network, connection);
415 * Removes the given connection and all its channels and bots.
418 * The connection to remove
420 private void removeConnection(Connection connection) {
421 Optional<Network> network = getNetwork(connection);
422 if (!network.isPresent()) {
426 /* find all channels that need to be removed. */
427 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
428 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
429 Channel joinedChannel = channelIterator.next();
430 if (!joinedChannel.network().equals(network.get())) {
434 channelIterator.remove();
438 /* now remove all bots for that network. */
439 Map<String, Bot> bots = networkBots.row(network.get());
440 int botCount = bots.size();
442 for (Bot bot : bots.values()) {
443 packCount += bot.packs().size();
446 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
448 /* now remove the network. */
449 networkConnections.remove(network.get());
457 * If a connection to a network has been established, the channels associated
458 * with this network are joined.
460 * @param connectionEstablished
461 * The connection established event
464 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
466 /* get network for connection. */
467 Optional<Network> network = getNetwork(connectionEstablished.connection());
470 if (!network.isPresent()) {
471 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
475 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
477 /* join all channels on this network. */
478 for (Channel channel : channels) {
479 if (channel.network().equals(network.get())) {
481 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
482 connectionEstablished.connection().joinChannel(channel.name());
483 } catch (IOException ioe1) {
484 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
491 * Remove all data stored for a network if the connection is closed.
493 * @param connectionClosed
494 * The connection closed event
497 public void connectionClosed(ConnectionClosed connectionClosed) {
498 removeConnection(connectionClosed.connection());
502 * Remove all data stored for a network if the connection fails.
504 * @param connectionFailed
505 * The connection failed event
508 public void connectionFailed(ConnectionFailed connectionFailed) {
509 removeConnection(connectionFailed.connection());
513 * Shows a message when a channel was joined by us.
515 * @param channelJoined
516 * The channel joined event
519 public void channelJoined(ChannelJoined channelJoined) {
520 if (channelJoined.connection().isSource(channelJoined.client())) {
521 Optional<Network> network = getNetwork(channelJoined.connection());
522 if (!network.isPresent()) {
526 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
527 if (!channel.isPresent()) {
528 /* it’s an extra channel. */
529 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
530 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
534 joinedChannels.add(channel.get());
535 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
540 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
543 * The channel left event
546 public void channelLeft(ChannelLeft channelLeft) {
547 Optional<Network> network = getNetwork(channelLeft.connection());
548 if (!network.isPresent()) {
552 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
554 /* maybe it was us? */
555 if (channelLeft.connection().isSource(channelLeft.client())) {
556 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
557 if (!channel.isPresent()) {
558 /* maybe it was an extra channel? */
559 channel = getExtraChannel(network.get(), channelLeft.channel());
560 if (!channel.isPresent()) {
561 /* okay, whatever. */
565 extraChannels.remove(channel);
567 channels.remove(channel.get());
570 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
576 networkBots.remove(network.get(), channelLeft.client().nick().get());
580 * Removes a client (which may be a bot) from the table of known bots.
583 * The client quit event
586 public void clientQuit(ClientQuit clientQuit) {
587 Optional<Network> network = getNetwork(clientQuit.connection());
588 if (!network.isPresent()) {
592 networkBots.remove(network.get(), clientQuit.client().nick().get());
596 * If the nickname of a bit changes, remove it from the old name and store it
597 * under the new name.
599 * @param nicknameChanged
600 * The nickname changed event
603 public void nicknameChanged(NicknameChanged nicknameChanged) {
604 Optional<Network> network = getNetwork(nicknameChanged.connection());
605 if (!network.isPresent()) {
609 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
614 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
618 * If a message on a channel is received, it is parsed for pack information
619 * with is then added to a bot.
621 * @param channelMessageReceived
622 * The channel message received event
625 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
626 String message = getDefaultInstance().clean(channelMessageReceived.message());
627 if (!message.startsWith("#")) {
628 /* most probably not a pack announcement. */
632 Optional<Network> network = getNetwork(channelMessageReceived.connection());
633 if (!network.isPresent()) {
634 /* message for unknown connection? */
638 /* parse pack information. */
639 Optional<Pack> pack = parsePack(message);
640 if (!pack.isPresent()) {
645 synchronized (networkBots) {
646 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
647 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
648 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
649 eventBus.post(new BotAdded(bot));
651 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
656 bot.addPack(pack.get());
657 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
661 * Forward all private messages to every console.
663 * @param privateMessageReceived
664 * The private message recevied event
667 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
668 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
672 * Sends a message to all console when a notice was received.
674 * @param privateNoticeReceived
675 * The notice received event
678 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
679 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
680 if (!network.isPresent()) {
684 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
688 * Starts a DCC download.
690 * @param dccSendReceived
694 public void dccSendReceived(final DccSendReceived dccSendReceived) {
695 final Optional<Network> network = getNetwork(dccSendReceived.connection());
696 if (!network.isPresent()) {
700 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
701 if (packDownloads.isEmpty()) {
702 /* unknown download, ignore. */
706 /* check if it’s already downloading. */
707 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
708 if (!runningDownloads.isEmpty()) {
709 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
713 /* locate the correct download. */
714 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
717 public boolean apply(Download download) {
718 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
722 /* we did not request this download. */
723 if (requestedDownload.isEmpty()) {
727 Download download = requestedDownload.iterator().next();
729 /* check if the file already exists. */
730 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
731 if (outputFile.exists()) {
732 long existingFileSize = outputFile.length();
734 /* file already complete? */
735 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
736 /* file is apparently already complete. just move it. */
737 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
738 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
740 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
743 /* remove download. */
744 downloads.removeAll(download.pack().name());
748 /* file not complete yet, DCC resume it. */
750 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
751 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
752 } catch (IOException ioe1) {
753 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
759 /* file does not exist, start the download. */
761 OutputStream fileOutputStream = new FileOutputStream(outputFile);
762 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
763 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
764 dccReceivers.add(dccReceiver);
766 eventBus.post(new DownloadStarted(download));
767 } catch (FileNotFoundException fnfe1) {
768 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
773 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
774 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
775 if (!network.isPresent()) {
779 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
780 if (packDownloads.isEmpty()) {
781 /* unknown download, ignore. */
785 /* check if it’s already downloading. */
786 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
787 if (!runningDownloads.isEmpty()) {
788 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
792 /* locate the correct download. */
793 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
796 public boolean apply(Download download) {
797 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
801 /* we did not request this download. */
802 if (requestedDownload.isEmpty()) {
806 Download download = requestedDownload.iterator().next();
809 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
810 if (outputFile.length() != dccAcceptReceived.position()) {
811 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
812 logger.log(Level.WARNING, String.format("Download %s from %s: have %d bytes but wants to resume from %d!", dccAcceptReceived.filename(), dccAcceptReceived.source(), outputFile.length(), dccAcceptReceived.position()));
814 downloads.removeAll(download.pack().name());
817 OutputStream outputStream = new FileOutputStream(outputFile, true);
818 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
819 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
820 dccReceivers.add(dccReceiver);
822 eventBus.post(new DownloadStarted(download));
823 } catch (FileNotFoundException fnfe1) {
828 * Closes the output stream of the download and moves the file to the final
831 * @param dccDownloadFinished
832 * The DCC download finished event
835 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
837 /* locate the correct download. */
838 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
839 if (requestedDownload.isEmpty()) {
840 /* this seems wrong. */
841 logger.warning("Download finished but could not be located.");
844 Download download = requestedDownload.iterator().next();
847 download.outputStream().close();
848 File file = new File(download.filename());
849 file.renameTo(new File(finalDirectory, download.pack().name()));
850 eventBus.post(new DownloadFinished(download));
851 dccReceivers.remove(dccDownloadFinished.dccReceiver());
852 downloads.removeAll(download.pack().name());
853 } catch (IOException ioe1) {
854 /* TODO - handle all the errors. */
855 logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
860 * Closes the output stream and notifies all listeners of the failure.
862 * @param dccDownloadFailed
863 * The DCC download failed event
866 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
868 /* locate the correct download. */
869 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
870 if (requestedDownload.isEmpty()) {
871 /* this seems wrong. */
872 logger.warning("Download finished but could not be located.");
875 Download download = requestedDownload.iterator().next();
878 Closeables.close(download.outputStream(), true);
879 eventBus.post(new DownloadFailed(download));
880 dccReceivers.remove(dccDownloadFailed.dccReceiver());
881 downloads.removeAll(download.pack().name());
882 } catch (IOException ioe1) {
883 /* swallow silently. */
888 public void replyReceived(ReplyReceived replyReceived) {
889 logger.log(Level.FINEST, String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
897 * Returns the download of the given pack from the given bot.
900 * The pack being downloaded
902 * The bot the pack is being downloaded from
903 * @return The download, or {@link Optional#absent()} if the download could not
906 private Optional<Download> getDownload(Pack pack, Bot bot) {
907 if (!downloads.containsKey(pack.name())) {
908 return Optional.absent();
910 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
911 if (download.bot().equals(bot)) {
912 return Optional.of(download);
915 return Optional.absent();
919 * Searches all current connections for the given connection, returning the
920 * associated network.
923 * The connection to get the network for
924 * @return The network belonging to the connection, or {@link
927 private Optional<Network> getNetwork(Connection connection) {
928 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
929 if (networkConnectionEntry.getValue().equals(connection)) {
930 return Optional.of(networkConnectionEntry.getKey());
933 return Optional.absent();
937 * Returns the configured channel for the given network and name.
940 * The network the channel is located on
942 * The name of the channel
943 * @return The configured channel, or {@link Optional#absent()} if no
944 * configured channel matching the given network and name was found
946 public Optional<Channel> getChannel(Network network, String channelName) {
947 for (Channel channel : channels) {
948 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
949 return Optional.of(channel);
952 return Optional.absent();
956 * Returns the extra channel for the given network and name.
959 * The network the channel is located on
961 * The name of the channel
962 * @return The extra channel, or {@link Optional#absent()} if no extra channel
963 * matching the given network and name was found
965 public Optional<Channel> getExtraChannel(Network network, String channelName) {
966 for (Channel channel : extraChannels) {
967 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
968 return Optional.of(channel);
971 return Optional.absent();
975 * Parses {@link Pack} information from the given message.
978 * The message to parse pack information from
979 * @return The parsed pack, or {@link Optional#absent()} if the message could
980 * not be parsed into a pack
982 private Optional<Pack> parsePack(String message) {
983 int squareOpen = message.indexOf('[');
984 int squareClose = message.indexOf(']', squareOpen);
985 if ((squareOpen == -1) && (squareClose == -1)) {
986 return Optional.absent();
988 String packSize = message.substring(squareOpen + 1, squareClose);
989 String packName = message.substring(message.lastIndexOf(' ') + 1);
990 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
991 return Optional.of(new Pack(packIndex, packSize, packName));