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.xdcc.data.Channel.TO_NETWORK;
21 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
24 import java.io.FileNotFoundException;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.OutputStream;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.concurrent.TimeUnit;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
38 import net.pterodactylus.irc.Connection;
39 import net.pterodactylus.irc.ConnectionBuilder;
40 import net.pterodactylus.irc.DccReceiver;
41 import net.pterodactylus.irc.event.ChannelJoined;
42 import net.pterodactylus.irc.event.ChannelLeft;
43 import net.pterodactylus.irc.event.ChannelMessageReceived;
44 import net.pterodactylus.irc.event.ClientQuit;
45 import net.pterodactylus.irc.event.ConnectionClosed;
46 import net.pterodactylus.irc.event.ConnectionEstablished;
47 import net.pterodactylus.irc.event.ConnectionFailed;
48 import net.pterodactylus.irc.event.DccAcceptReceived;
49 import net.pterodactylus.irc.event.DccDownloadFailed;
50 import net.pterodactylus.irc.event.DccDownloadFinished;
51 import net.pterodactylus.irc.event.DccSendReceived;
52 import net.pterodactylus.irc.event.NicknameChanged;
53 import net.pterodactylus.irc.event.PrivateMessageReceived;
54 import net.pterodactylus.irc.event.PrivateNoticeReceived;
55 import net.pterodactylus.irc.event.ReplyReceived;
56 import net.pterodactylus.irc.util.MessageCleaner;
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.Optional;
74 import com.google.common.base.Predicate;
75 import com.google.common.collect.FluentIterable;
76 import com.google.common.collect.HashBasedTable;
77 import com.google.common.collect.HashMultimap;
78 import com.google.common.collect.ImmutableList;
79 import com.google.common.collect.ImmutableSet;
80 import com.google.common.collect.Lists;
81 import com.google.common.collect.Maps;
82 import com.google.common.collect.Multimap;
83 import com.google.common.collect.Sets;
84 import com.google.common.collect.Table;
85 import com.google.common.eventbus.EventBus;
86 import com.google.common.eventbus.Subscribe;
87 import com.google.common.io.Closeables;
88 import com.google.common.util.concurrent.AbstractExecutionThreadService;
89 import com.google.inject.Inject;
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 configured channels. Due to various circumstances, configured
172 * channels might not actually be joined.
174 * @return All configured channels
176 public Collection<Channel> channels() {
177 return ImmutableSet.copyOf(channels);
181 * Returns all currently joined channels.
183 * @return All currently joined channels
185 public Collection<Channel> joinedChannels() {
186 return ImmutableSet.copyOf(joinedChannels);
190 * Returns all currently joined channels that are not configured.
192 * @return All currently joined but not configured channels
194 public Collection<Channel> extraChannels() {
195 return ImmutableSet.copyOf(extraChannels);
199 * Returns all currently known bots.
201 * @return All currently known bots
203 public Collection<Bot> bots() {
204 return networkBots.values();
208 * Returns all currently running downloads.
210 * @return All currently running downloads
212 public Collection<Download> downloads() {
213 return downloads.values();
221 * Adds a channel to monitor.
224 * The channel to monitor
226 public void addChannel(Channel channel) {
227 channels.add(channel);
231 * Fetches the given pack from the given bot.
234 * The bot to fetch the pack from
238 public void fetch(Bot bot, Pack pack) {
239 Connection connection = networkConnections.get(bot.network());
240 if (connection == null) {
244 /* check if we are already downloading the file? */
245 if (downloads.containsKey(pack.name())) {
246 Collection<Download> packDownloads = downloads.get(pack.name());
247 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
248 if (!runningDownloads.isEmpty()) {
249 Download download = runningDownloads.iterator().next();
250 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
253 StringBuilder bots = new StringBuilder();
254 for (Download download : packDownloads) {
255 if (bots.length() > 0) {
258 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
260 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
263 Download download = new Download(bot, pack);
264 downloads.put(pack.name(), download);
267 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
268 } catch (IOException ioe1) {
269 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
274 * Cancels the download of the given pack from the given bot.
277 * The bot the pack is being downloaded from
279 * The pack being downloaded
281 public void cancelDownload(Bot bot, Pack pack) {
282 Optional<Download> download = getDownload(pack, bot);
283 if (!download.isPresent()) {
287 /* get connection. */
288 Connection connection = networkConnections.get(bot.network());
289 if (connection == null) {
290 /* request for unknown network? */
294 /* stop the DCC receiver. */
295 if (download.get().dccReceiver() != null) {
296 download.get().dccReceiver().stop();
298 /* remove download if it hasn’t started yet. */
299 downloads.remove(pack.name(), download.get());
302 /* remove the request from the bot, too. */
304 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
305 } catch (IOException ioe1) {
306 logger.log(Level.WARNING, String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
311 * Closes the given connection.
314 * The connection to close
316 public void closeConnection(Connection connection) {
319 } catch (IOException ioe1) {
325 // ABSTRACTIDLESERVICE METHODS
329 protected void startUp() {
330 for (Channel channel : channels) {
331 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
332 connectNetwork(channel.network());
335 /* notify listeners. */
336 eventBus.post(new CoreStarted(this));
340 protected void run() throws Exception {
341 while (isRunning()) {
343 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
344 } catch (InterruptedException ie1) {
348 /* find channels that should be monitored but are not. */
349 for (Channel channel : channels) {
350 if (joinedChannels.contains(channel)) {
354 connectNetwork(channel.network());
355 Connection connection = networkConnections.get(channel.network());
356 if (connection.established()) {
357 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
359 connection.joinChannel(channel.name());
360 } catch (IOException ioe1) {
361 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
369 protected void shutDown() {
377 * Starts a new connection for the given network if no such connection exists
381 * The network to connect to
383 private void connectNetwork(Network network) {
384 if (!networkConnections.containsKey(network)) {
385 /* select a random server. */
386 List<Server> servers = Lists.newArrayList(network.servers());
387 if (servers.isEmpty()) {
388 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
391 Server server = servers.get((int) (Math.random() * servers.size()));
392 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
393 connection.username(RandomNickname.get()).realName(RandomNickname.get());
394 networkConnections.put(network, connection);
400 * Removes the given connection and all its channels and bots.
403 * The connection to remove
405 private void removeConnection(Connection connection) {
406 Optional<Network> network = getNetwork(connection);
407 if (!network.isPresent()) {
411 /* find all channels that need to be removed. */
412 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
413 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
414 Channel joinedChannel = channelIterator.next();
415 if (!joinedChannel.network().equals(network.get())) {
419 channelIterator.remove();
423 /* now remove all bots for that network. */
424 Map<String, Bot> bots = networkBots.row(network.get());
425 int botCount = bots.size();
427 for (Bot bot : bots.values()) {
428 packCount += bot.packs().size();
431 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
433 /* now remove the network. */
434 networkConnections.remove(network.get());
442 * If a connection to a network has been established, the channels associated
443 * with this network are joined.
445 * @param connectionEstablished
446 * The connection established event
449 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
451 /* get network for connection. */
452 Optional<Network> network = getNetwork(connectionEstablished.connection());
455 if (!network.isPresent()) {
456 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
460 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
462 /* join all channels on this network. */
463 for (Channel channel : channels) {
464 if (channel.network().equals(network.get())) {
466 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
467 connectionEstablished.connection().joinChannel(channel.name());
468 } catch (IOException ioe1) {
469 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
476 * Remove all data stored for a network if the connection is closed.
478 * @param connectionClosed
479 * The connection closed event
482 public void connectionClosed(ConnectionClosed connectionClosed) {
483 removeConnection(connectionClosed.connection());
487 * Remove all data stored for a network if the connection fails.
489 * @param connectionFailed
490 * The connection failed event
492 public void connectionFailed(ConnectionFailed connectionFailed) {
493 removeConnection(connectionFailed.connection());
497 * Shows a message when a channel was joined by us.
499 * @param channelJoined
500 * The channel joined event
503 public void channelJoined(ChannelJoined channelJoined) {
504 if (channelJoined.connection().isSource(channelJoined.client())) {
505 Optional<Network> network = getNetwork(channelJoined.connection());
506 if (!network.isPresent()) {
510 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
511 if (!channel.isPresent()) {
512 /* it’s an extra channel. */
513 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
514 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
518 joinedChannels.add(channel.get());
519 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
524 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
527 * The channel left event
530 public void channelLeft(ChannelLeft channelLeft) {
531 Optional<Network> network = getNetwork(channelLeft.connection());
532 if (!network.isPresent()) {
536 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
538 /* maybe it was us? */
539 if (channelLeft.connection().isSource(channelLeft.client())) {
540 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
541 if (!channel.isPresent()) {
542 /* maybe it was an extra channel? */
543 channel = getExtraChannel(network.get(), channelLeft.channel());
544 if (!channel.isPresent()) {
545 /* okay, whatever. */
549 extraChannels.remove(channel);
551 channels.remove(channel.get());
554 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
560 networkBots.remove(network.get(), channelLeft.client().nick().get());
564 * Removes a client (which may be a bot) from the table of known bots.
567 * The client quit event
570 public void clientQuit(ClientQuit clientQuit) {
571 Optional<Network> network = getNetwork(clientQuit.connection());
572 if (!network.isPresent()) {
576 networkBots.remove(network.get(), clientQuit.client().nick().get());
580 * If the nickname of a bit changes, remove it from the old name and store it
581 * under the new name.
583 * @param nicknameChanged
584 * The nickname changed event
587 public void nicknameChanged(NicknameChanged nicknameChanged) {
588 Optional<Network> network = getNetwork(nicknameChanged.connection());
589 if (!network.isPresent()) {
593 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
598 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
602 * If a message on a channel is received, it is parsed for pack information
603 * with is then added to a bot.
605 * @param channelMessageReceived
606 * The channel message received event
609 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
610 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
611 if (!message.startsWith("#")) {
612 /* most probably not a pack announcement. */
616 Optional<Network> network = getNetwork(channelMessageReceived.connection());
617 if (!network.isPresent()) {
618 /* message for unknown connection? */
622 /* parse pack information. */
623 Optional<Pack> pack = parsePack(message);
624 if (!pack.isPresent()) {
629 synchronized (networkBots) {
630 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
631 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
632 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
633 eventBus.post(new BotAdded(bot));
635 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
640 bot.addPack(pack.get());
641 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
645 * Forward all private messages to every console.
647 * @param privateMessageReceived
648 * The private message recevied event
651 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
652 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
656 * Sends a message to all console when a notice was received.
658 * @param privateNoticeReceived
659 * The notice received event
662 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
663 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
664 if (!network.isPresent()) {
668 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
672 * Starts a DCC download.
674 * @param dccSendReceived
678 public void dccSendReceived(final DccSendReceived dccSendReceived) {
679 final Optional<Network> network = getNetwork(dccSendReceived.connection());
680 if (!network.isPresent()) {
684 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
685 if (packDownloads.isEmpty()) {
686 /* unknown download, ignore. */
690 /* check if it’s already downloading. */
691 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
692 if (!runningDownloads.isEmpty()) {
693 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
697 /* locate the correct download. */
698 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
701 public boolean apply(Download download) {
702 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
706 /* we did not request this download. */
707 if (requestedDownload.isEmpty()) {
711 Download download = requestedDownload.iterator().next();
713 /* check if the file already exists. */
714 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
715 if (outputFile.exists()) {
716 long existingFileSize = outputFile.length();
718 /* file already complete? */
719 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
720 /* file is apparently already complete. just move it. */
721 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
722 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
724 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
727 /* remove download. */
728 downloads.removeAll(download.pack().name());
732 /* file not complete yet, DCC resume it. */
734 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
735 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
736 } catch (IOException ioe1) {
737 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
743 /* file does not exist, start the download. */
745 OutputStream fileOutputStream = new FileOutputStream(outputFile);
746 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
747 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
748 dccReceivers.add(dccReceiver);
750 eventBus.post(new DownloadStarted(download));
751 } catch (FileNotFoundException fnfe1) {
752 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
757 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
758 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
759 if (!network.isPresent()) {
763 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
764 if (packDownloads.isEmpty()) {
765 /* unknown download, ignore. */
769 /* check if it’s already downloading. */
770 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
771 if (!runningDownloads.isEmpty()) {
772 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
776 /* locate the correct download. */
777 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
780 public boolean apply(Download download) {
781 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
785 /* we did not request this download. */
786 if (requestedDownload.isEmpty()) {
790 Download download = requestedDownload.iterator().next();
793 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
794 if (outputFile.length() != dccAcceptReceived.position()) {
795 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
796 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()));
798 downloads.removeAll(download.pack().name());
801 OutputStream outputStream = new FileOutputStream(outputFile, true);
802 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
803 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
804 dccReceivers.add(dccReceiver);
806 eventBus.post(new DownloadStarted(download));
807 } catch (FileNotFoundException fnfe1) {
812 * Closes the output stream of the download and moves the file to the final
815 * @param dccDownloadFinished
816 * The DCC download finished event
819 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
821 /* locate the correct download. */
822 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
823 if (requestedDownload.isEmpty()) {
824 /* this seems wrong. */
825 logger.warning("Download finished but could not be located.");
828 Download download = requestedDownload.iterator().next();
831 download.outputStream().close();
832 File file = new File(download.filename());
833 file.renameTo(new File(finalDirectory, download.pack().name()));
834 eventBus.post(new DownloadFinished(download));
835 dccReceivers.remove(dccDownloadFinished.dccReceiver());
836 downloads.removeAll(download.pack().name());
837 } catch (IOException ioe1) {
838 /* TODO - handle all the errors. */
839 logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
844 * Closes the output stream and notifies all listeners of the failure.
846 * @param dccDownloadFailed
847 * The DCC download failed event
850 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
852 /* locate the correct download. */
853 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
854 if (requestedDownload.isEmpty()) {
855 /* this seems wrong. */
856 logger.warning("Download finished but could not be located.");
859 Download download = requestedDownload.iterator().next();
862 Closeables.close(download.outputStream(), true);
863 eventBus.post(new DownloadFailed(download));
864 dccReceivers.remove(dccDownloadFailed.dccReceiver());
865 downloads.removeAll(download.pack().name());
866 } catch (IOException ioe1) {
867 /* swallow silently. */
872 public void replyReceived(ReplyReceived replyReceived) {
873 logger.log(Level.FINEST, String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
881 * Returns the download of the given pack from the given bot.
884 * The pack being downloaded
886 * The bot the pack is being downloaded from
887 * @return The download, or {@link Optional#absent()} if the download could not
890 private Optional<Download> getDownload(Pack pack, Bot bot) {
891 if (!downloads.containsKey(pack.name())) {
892 return Optional.absent();
894 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
895 if (download.bot().equals(bot)) {
896 return Optional.of(download);
899 return Optional.absent();
903 * Searches all current connections for the given connection, returning the
904 * associated network.
907 * The connection to get the network for
908 * @return The network belonging to the connection, or {@link
911 private Optional<Network> getNetwork(Connection connection) {
912 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
913 if (networkConnectionEntry.getValue().equals(connection)) {
914 return Optional.of(networkConnectionEntry.getKey());
917 return Optional.absent();
921 * Returns the configured channel for the given network and name.
924 * The network the channel is located on
926 * The name of the channel
927 * @return The configured channel, or {@link Optional#absent()} if no
928 * configured channel matching the given network and name was found
930 public Optional<Channel> getChannel(Network network, String channelName) {
931 for (Channel channel : channels) {
932 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
933 return Optional.of(channel);
936 return Optional.absent();
940 * Returns the extra channel for the given network and name.
943 * The network the channel is located on
945 * The name of the channel
946 * @return The extra channel, or {@link Optional#absent()} if no extra channel
947 * matching the given network and name was found
949 public Optional<Channel> getExtraChannel(Network network, String channelName) {
950 for (Channel channel : extraChannels) {
951 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
952 return Optional.of(channel);
955 return Optional.absent();
959 * Parses {@link Pack} information from the given message.
962 * The message to parse pack information from
963 * @return The parsed pack, or {@link Optional#absent()} if the message could
964 * not be parsed into a pack
966 private Optional<Pack> parsePack(String message) {
967 int squareOpen = message.indexOf('[');
968 int squareClose = message.indexOf(']', squareOpen);
969 if ((squareOpen == -1) && (squareClose == -1)) {
970 return Optional.absent();
972 String packSize = message.substring(squareOpen + 1, squareClose);
973 String packName = message.substring(message.lastIndexOf(' ') + 1);
974 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
975 return Optional.of(new Pack(packIndex, packSize, packName));