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.Download.FILTER_RUNNING;
23 import java.io.FileNotFoundException;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.io.OutputStream;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.Map.Entry;
33 import java.util.concurrent.TimeUnit;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
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.MessageCleaner;
56 import net.pterodactylus.irc.util.RandomNickname;
57 import net.pterodactylus.xdcc.core.event.BotAdded;
58 import net.pterodactylus.xdcc.core.event.CoreStarted;
59 import net.pterodactylus.xdcc.core.event.DownloadFailed;
60 import net.pterodactylus.xdcc.core.event.DownloadFinished;
61 import net.pterodactylus.xdcc.core.event.DownloadStarted;
62 import net.pterodactylus.xdcc.core.event.GenericError;
63 import net.pterodactylus.xdcc.core.event.GenericMessage;
64 import net.pterodactylus.xdcc.core.event.MessageReceived;
65 import net.pterodactylus.xdcc.data.Bot;
66 import net.pterodactylus.xdcc.data.Channel;
67 import net.pterodactylus.xdcc.data.Download;
68 import net.pterodactylus.xdcc.data.Network;
69 import net.pterodactylus.xdcc.data.Pack;
70 import net.pterodactylus.xdcc.data.Server;
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;
91 * The core of XDCC Downloader.
93 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
95 public class Core extends AbstractExecutionThreadService {
98 private static final Logger logger = Logger.getLogger(Core.class.getName());
100 /** The event bus. */
101 private final EventBus eventBus;
103 /** The temporary directory to download files to. */
104 private final String temporaryDirectory;
106 /** The directory to move finished downloads to. */
107 private final String finalDirectory;
109 /** The channels that should be monitored. */
110 private final Collection<Channel> channels = Sets.newHashSet();
112 /** The channels that are currentlymonitored. */
113 private final Collection<Channel> joinedChannels = Sets.newHashSet();
115 /** The channels that are joined but not configured. */
116 private final Collection<Channel> extraChannels = Sets.newHashSet();
118 /** The current network connections. */
119 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
121 /** The currently known bots. */
122 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
124 /** The current downloads. */
125 private final Multimap<String, Download> downloads = HashMultimap.create();
127 /** The current DCC receivers. */
128 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
131 * Creates a new core.
135 * @param temporaryDirectory
136 * The directory to download files to
137 * @param finalDirectory
138 * The directory to move finished files to
141 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
142 this.eventBus = eventBus;
143 this.temporaryDirectory = temporaryDirectory;
144 this.finalDirectory = finalDirectory;
152 * Returns all currently known connections.
154 * @return All currently known connections
156 public Collection<Connection> connections() {
157 return networkConnections.values();
161 * Returns all configured channels. Due to various circumstances, configured
162 * channels might not actually be joined.
164 * @return All configured channels
166 public Collection<Channel> channels() {
167 return ImmutableSet.copyOf(channels);
171 * Returns all currently joined channels.
173 * @return All currently joined channels
175 public Collection<Channel> joinedChannels() {
176 return ImmutableSet.copyOf(joinedChannels);
180 * Returns all currently joined channels that are not configured.
182 * @return All currently joined but not configured channels
184 public Collection<Channel> extraChannels() {
185 return ImmutableSet.copyOf(extraChannels);
189 * Returns all currently known bots.
191 * @return All currently known bots
193 public Collection<Bot> bots() {
194 return networkBots.values();
198 * Returns all currently running downloads.
200 * @return All currently running downloads
202 public Collection<Download> downloads() {
203 return downloads.values();
211 * Adds a channel to monitor.
214 * The channel to monitor
216 public void addChannel(Channel channel) {
217 channels.add(channel);
221 * Fetches the given pack from the given bot.
224 * The bot to fetch the pack from
228 public void fetch(Bot bot, Pack pack) {
229 Connection connection = networkConnections.get(bot.network());
230 if (connection == null) {
234 /* check if we are already downloading the file? */
235 if (downloads.containsKey(pack.name())) {
236 Collection<Download> packDownloads = downloads.get(pack.name());
237 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
238 if (!runningDownloads.isEmpty()) {
239 Download download = runningDownloads.iterator().next();
240 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
243 StringBuilder bots = new StringBuilder();
244 for (Download download : packDownloads) {
245 if (bots.length() > 0) {
248 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
250 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
253 Download download = new Download(bot, pack);
254 downloads.put(pack.name(), download);
257 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
258 } catch (IOException ioe1) {
259 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
264 * Cancels the download of the given pack from the given bot.
267 * The bot the pack is being downloaded from
269 * The pack being downloaded
271 public void cancelDownload(Bot bot, Pack pack) {
272 Optional<Download> download = getDownload(pack, bot);
273 if (!download.isPresent()) {
277 /* get connection. */
278 Connection connection = networkConnections.get(bot.network());
279 if (connection == null) {
280 /* request for unknown network? */
284 /* remove download. */
285 downloads.remove(pack.name(), download.get());
287 /* stop the DCC receiver. */
288 if (download.get().dccReceiver() != null) {
289 download.get().dccReceiver().stop();
292 /* remove the request from the bot, too. */
294 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
295 } catch (IOException ioe1) {
296 logger.log(Level.WARNING, String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
301 * Closes the given connection.
304 * The connection to close
306 public void closeConnection(Connection connection) {
309 } catch (IOException ioe1) {
315 // ABSTRACTIDLESERVICE METHODS
319 protected void startUp() {
320 for (Channel channel : channels) {
321 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
322 connectNetwork(channel.network());
325 /* notify listeners. */
326 eventBus.post(new CoreStarted(this));
330 protected void run() throws Exception {
331 while (isRunning()) {
333 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
334 } catch (InterruptedException ie1) {
338 /* find channels that should be monitored but are not. */
339 for (Channel channel : channels) {
340 if (joinedChannels.contains(channel)) {
344 connectNetwork(channel.network());
345 Connection connection = networkConnections.get(channel.network());
346 if (connection.established()) {
347 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
349 connection.joinChannel(channel.name());
350 } catch (IOException ioe1) {
351 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
359 protected void shutDown() {
367 * Starts a new connection for the given network if no such connection exists
371 * The network to connect to
373 private void connectNetwork(Network network) {
374 if (!networkConnections.containsKey(network)) {
375 /* select a random server. */
376 List<Server> servers = Lists.newArrayList(network.servers());
377 if (servers.isEmpty()) {
378 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
381 Server server = servers.get((int) (Math.random() * servers.size()));
382 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
383 connection.username(RandomNickname.get()).realName(RandomNickname.get());
384 networkConnections.put(network, connection);
390 * Removes the given connection and all its channels and bots.
393 * The connection to remove
395 private void removeConnection(Connection connection) {
396 Optional<Network> network = getNetwork(connection);
397 if (!network.isPresent()) {
401 /* find all channels that need to be removed. */
402 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
403 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
404 Channel joinedChannel = channelIterator.next();
405 if (!joinedChannel.network().equals(network.get())) {
409 channelIterator.remove();
413 /* now remove all bots for that network. */
414 Map<String, Bot> bots = networkBots.row(network.get());
415 int botCount = bots.size();
417 for (Bot bot : bots.values()) {
418 packCount += bot.packs().size();
421 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
423 /* now remove the network. */
424 networkConnections.remove(network.get());
432 * If a connection to a network has been established, the channels associated
433 * with this network are joined.
435 * @param connectionEstablished
436 * The connection established event
439 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
441 /* get network for connection. */
442 Optional<Network> network = getNetwork(connectionEstablished.connection());
445 if (!network.isPresent()) {
446 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
450 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
452 /* join all channels on this network. */
453 for (Channel channel : channels) {
454 if (channel.network().equals(network.get())) {
456 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
457 connectionEstablished.connection().joinChannel(channel.name());
458 } catch (IOException ioe1) {
459 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
466 * Remove all data stored for a network if the connection is closed.
468 * @param connectionClosed
469 * The connection closed event
472 public void connectionClosed(ConnectionClosed connectionClosed) {
473 removeConnection(connectionClosed.connection());
477 * Remove all data stored for a network if the connection fails.
479 * @param connectionFailed
480 * The connection failed event
482 public void connectionFailed(ConnectionFailed connectionFailed) {
483 removeConnection(connectionFailed.connection());
487 * Shows a message when a channel was joined by us.
489 * @param channelJoined
490 * The channel joined event
493 public void channelJoined(ChannelJoined channelJoined) {
494 if (channelJoined.connection().isSource(channelJoined.client())) {
495 Optional<Network> network = getNetwork(channelJoined.connection());
496 if (!network.isPresent()) {
500 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
501 if (!channel.isPresent()) {
502 /* it’s an extra channel. */
503 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
504 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
508 joinedChannels.add(channel.get());
509 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
514 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
517 * The channel left event
520 public void channelLeft(ChannelLeft channelLeft) {
521 Optional<Network> network = getNetwork(channelLeft.connection());
522 if (!network.isPresent()) {
526 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
528 /* maybe it was us? */
529 if (channelLeft.connection().isSource(channelLeft.client())) {
530 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
531 if (!channel.isPresent()) {
532 /* maybe it was an extra channel? */
533 channel = getExtraChannel(network.get(), channelLeft.channel());
534 if (!channel.isPresent()) {
535 /* okay, whatever. */
539 extraChannels.remove(channel);
541 channels.remove(channel.get());
544 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
550 Bot removedBot = networkBots.remove(network.get(), channelLeft.client().nick().get());
551 if (removedBot != null) {
552 eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
557 * Removes a client (which may be a bot) from the table of known bots.
560 * The client quit event
563 public void clientQuit(ClientQuit clientQuit) {
564 Optional<Network> network = getNetwork(clientQuit.connection());
565 if (!network.isPresent()) {
569 Bot removedBot = networkBots.remove(network.get(), clientQuit.client().nick().get());
570 if (removedBot != null) {
571 eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
576 * If the nickname of a bit changes, remove it from the old name and store it
577 * under the new name.
579 * @param nicknameChanged
580 * The nickname changed event
583 public void nicknameChanged(NicknameChanged nicknameChanged) {
584 Optional<Network> network = getNetwork(nicknameChanged.connection());
585 if (!network.isPresent()) {
589 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
594 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
598 * If a message on a channel is received, it is parsed for pack information
599 * with is then added to a bot.
601 * @param channelMessageReceived
602 * The channel message received event
605 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
606 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
607 if (!message.startsWith("#")) {
608 /* most probably not a pack announcement. */
612 Optional<Network> network = getNetwork(channelMessageReceived.connection());
613 if (!network.isPresent()) {
614 /* message for unknown connection? */
618 /* parse pack information. */
619 Optional<Pack> pack = parsePack(message);
620 if (!pack.isPresent()) {
625 synchronized (networkBots) {
626 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
627 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
628 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
629 eventBus.post(new BotAdded(bot));
631 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
636 bot.addPack(pack.get());
637 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
641 * Forward all private messages to every console.
643 * @param privateMessageReceived
644 * The private message recevied event
647 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
648 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
652 * Sends a message to all console when a notice was received.
654 * @param privateNoticeReceived
655 * The notice received event
658 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
659 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
660 if (!network.isPresent()) {
664 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
668 * Starts a DCC download.
670 * @param dccSendReceived
674 public void dccSendReceived(final DccSendReceived dccSendReceived) {
675 final Optional<Network> network = getNetwork(dccSendReceived.connection());
676 if (!network.isPresent()) {
680 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
681 if (packDownloads.isEmpty()) {
682 /* unknown download, ignore. */
686 /* check if it’s already downloading. */
687 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
688 if (!runningDownloads.isEmpty()) {
689 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
693 /* locate the correct download. */
694 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
697 public boolean apply(Download download) {
698 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
702 /* we did not request this download. */
703 if (requestedDownload.isEmpty()) {
707 Download download = requestedDownload.iterator().next();
709 /* check if the file already exists. */
710 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
711 if (outputFile.exists()) {
712 long existingFileSize = outputFile.length();
714 /* file already complete? */
715 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
716 /* file is apparently already complete. just move it. */
717 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
718 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
720 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
723 /* remove download. */
724 downloads.removeAll(download.pack().name());
728 /* file not complete yet, DCC resume it. */
730 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
731 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
732 } catch (IOException ioe1) {
733 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
739 /* file does not exist, start the download. */
741 OutputStream fileOutputStream = new FileOutputStream(outputFile);
742 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
743 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
744 dccReceivers.add(dccReceiver);
746 eventBus.post(new DownloadStarted(download));
747 } catch (FileNotFoundException fnfe1) {
748 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
753 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
754 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
755 if (!network.isPresent()) {
759 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
760 if (packDownloads.isEmpty()) {
761 /* unknown download, ignore. */
765 /* check if it’s already downloading. */
766 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
767 if (!runningDownloads.isEmpty()) {
768 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
772 /* locate the correct download. */
773 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
776 public boolean apply(Download download) {
777 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
781 /* we did not request this download. */
782 if (requestedDownload.isEmpty()) {
786 Download download = requestedDownload.iterator().next();
789 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
790 if (outputFile.length() != dccAcceptReceived.position()) {
791 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
792 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()));
794 downloads.removeAll(download.pack().name());
797 OutputStream outputStream = new FileOutputStream(outputFile, true);
798 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
799 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
800 dccReceivers.add(dccReceiver);
802 eventBus.post(new DownloadStarted(download));
803 } catch (FileNotFoundException fnfe1) {
808 * Closes the output stream of the download and moves the file to the final
811 * @param dccDownloadFinished
812 * The DCC download finished event
815 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
817 /* locate the correct download. */
818 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
819 if (requestedDownload.isEmpty()) {
820 /* this seems wrong. */
821 logger.warning("Download finished but could not be located.");
824 Download download = requestedDownload.iterator().next();
827 download.outputStream().close();
828 File file = new File(download.filename());
829 file.renameTo(new File(finalDirectory, download.pack().name()));
830 eventBus.post(new DownloadFinished(download));
831 dccReceivers.remove(dccDownloadFinished.dccReceiver());
832 downloads.removeAll(download.pack().name());
833 } catch (IOException ioe1) {
834 /* TODO - handle all the errors. */
835 logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
840 * Closes the output stream and notifies all listeners of the failure.
842 * @param dccDownloadFailed
843 * The DCC download failed event
846 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
848 /* locate the correct download. */
849 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
850 if (requestedDownload.isEmpty()) {
851 /* this seems wrong. */
852 logger.warning("Download finished but could not be located.");
855 Download download = requestedDownload.iterator().next();
858 Closeables.close(download.outputStream(), true);
859 eventBus.post(new DownloadFailed(download));
860 dccReceivers.remove(dccDownloadFailed.dccReceiver());
861 downloads.removeAll(download.pack().name());
862 } catch (IOException ioe1) {
863 /* swallow silently. */
868 public void replyReceived(ReplyReceived replyReceived) {
869 logger.log(Level.FINEST, String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
877 * Returns the download of the given pack from the given bot.
880 * The pack being downloaded
882 * The bot the pack is being downloaded from
883 * @return The download, or {@link Optional#absent()} if the download could not
886 private Optional<Download> getDownload(Pack pack, Bot bot) {
887 if (!downloads.containsKey(pack.name())) {
888 return Optional.absent();
890 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
891 if (download.bot().equals(bot)) {
892 return Optional.of(download);
895 return Optional.absent();
899 * Searches all current connections for the given connection, returning the
900 * associated network.
903 * The connection to get the network for
904 * @return The network belonging to the connection, or {@link
907 private Optional<Network> getNetwork(Connection connection) {
908 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
909 if (networkConnectionEntry.getValue().equals(connection)) {
910 return Optional.of(networkConnectionEntry.getKey());
913 return Optional.absent();
917 * Returns the configured channel for the given network and name.
920 * The network the channel is located on
922 * The name of the channel
923 * @return The configured channel, or {@link Optional#absent()} if no
924 * configured channel matching the given network and name was found
926 public Optional<Channel> getChannel(Network network, String channelName) {
927 for (Channel channel : channels) {
928 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
929 return Optional.of(channel);
932 return Optional.absent();
936 * Returns the extra channel for the given network and name.
939 * The network the channel is located on
941 * The name of the channel
942 * @return The extra channel, or {@link Optional#absent()} if no extra channel
943 * matching the given network and name was found
945 public Optional<Channel> getExtraChannel(Network network, String channelName) {
946 for (Channel channel : extraChannels) {
947 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
948 return Optional.of(channel);
951 return Optional.absent();
955 * Parses {@link Pack} information from the given message.
958 * The message to parse pack information from
959 * @return The parsed pack, or {@link Optional#absent()} if the message could
960 * not be parsed into a pack
962 private Optional<Pack> parsePack(String message) {
963 int squareOpen = message.indexOf('[');
964 int squareClose = message.indexOf(']', squareOpen);
965 if ((squareOpen == -1) && (squareClose == -1)) {
966 return Optional.absent();
968 String packSize = message.substring(squareOpen + 1, squareClose);
969 String packName = message.substring(message.lastIndexOf(' ') + 1);
970 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
971 return Optional.of(new Pack(packIndex, packSize, packName));