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 java.lang.String.format;
21 import static net.pterodactylus.irc.util.MessageCleaner.getDefaultInstance;
22 import static net.pterodactylus.xdcc.data.Channel.TO_NETWORK;
23 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
26 import java.io.FileNotFoundException;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.io.OutputStream;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.Iterator;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.concurrent.TimeUnit;
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.KickedFromChannel;
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;
91 import org.apache.log4j.Logger;
94 * The core of XDCC Downloader.
96 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
98 public class Core extends AbstractExecutionThreadService {
101 private static final Logger logger = Logger.getLogger(Core.class.getName());
103 /** The event bus. */
104 private final EventBus eventBus;
106 /** The temporary directory to download files to. */
107 private final String temporaryDirectory;
109 /** The directory to move finished downloads to. */
110 private final String finalDirectory;
112 /** The channels that should be monitored. */
113 private final Collection<Channel> channels = Sets.newHashSet();
115 /** The channels that are currentlymonitored. */
116 private final Collection<Channel> joinedChannels = Sets.newHashSet();
118 /** The channels that are joined but not configured. */
119 private final Collection<Channel> extraChannels = Sets.newHashSet();
121 /** The current network connections. */
122 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
124 /** The currently known bots. */
125 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
127 /** The current downloads. */
128 private final Multimap<String, Download> downloads = HashMultimap.create();
130 /** The current DCC receivers. */
131 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
134 * Creates a new core.
138 * @param temporaryDirectory
139 * The directory to download files to
140 * @param finalDirectory
141 * The directory to move finished files to
144 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
145 this.eventBus = eventBus;
146 this.temporaryDirectory = temporaryDirectory;
147 this.finalDirectory = finalDirectory;
155 * Returns all currently known connections.
157 * @return All currently known connections
159 public Collection<Connection> connections() {
160 return networkConnections.values();
164 * Returns all defined networks.
166 * @return All defined networks
168 public Collection<Network> networks() {
169 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
173 * Returns all connected networks.
175 * @return All connected networks
177 public Collection<Network> connectedNetworks() {
178 return Lists.newArrayList(Optional.presentInstances(FluentIterable.from(networkConnections.values()).transform(new Function<Connection, Optional<Network>>() {
180 public Optional<Network> apply(Connection connection) {
181 return getNetwork(connection);
187 * Returns all configured channels. Due to various circumstances, configured
188 * channels might not actually be joined.
190 * @return All configured channels
192 public Collection<Channel> channels() {
193 return ImmutableSet.copyOf(channels);
197 * Returns all currently joined channels.
199 * @return All currently joined channels
201 public Collection<Channel> joinedChannels() {
202 return ImmutableSet.copyOf(joinedChannels);
206 * Returns all currently joined channels that are not configured.
208 * @return All currently joined but not configured channels
210 public Collection<Channel> extraChannels() {
211 return ImmutableSet.copyOf(extraChannels);
215 * Returns all currently known bots.
217 * @return All currently known bots
219 public Collection<Bot> bots() {
220 return networkBots.values();
224 * Returns all currently running downloads.
226 * @return All currently running downloads
228 public Collection<Download> downloads() {
229 return downloads.values();
237 * Adds a channel to monitor.
240 * The channel to monitor
242 public void addChannel(Channel channel) {
243 channels.add(channel);
247 * Fetches the given pack from the given bot.
250 * The bot to fetch the pack from
254 public void fetch(Bot bot, Pack pack) {
255 Connection connection = networkConnections.get(bot.network());
256 if (connection == null) {
260 /* check if we are already downloading the file? */
261 if (downloads.containsKey(pack.name())) {
262 Collection<Download> packDownloads = downloads.get(pack.name());
263 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
264 if (!runningDownloads.isEmpty()) {
265 Download download = runningDownloads.iterator().next();
266 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
269 StringBuilder bots = new StringBuilder();
270 for (Download download : packDownloads) {
271 if (bots.length() > 0) {
274 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
276 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
279 Download download = new Download(bot, pack);
280 downloads.put(pack.name(), download);
283 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
284 } catch (IOException ioe1) {
285 logger.warn("Could not send message to bot!", ioe1);
290 * Cancels the download of the given pack from the given bot.
293 * The bot the pack is being downloaded from
295 * The pack being downloaded
297 public void cancelDownload(Bot bot, Pack pack) {
298 Optional<Download> download = getDownload(pack, bot);
299 if (!download.isPresent()) {
303 /* get connection. */
304 Connection connection = networkConnections.get(bot.network());
305 if (connection == null) {
306 /* request for unknown network? */
310 /* stop the DCC receiver. */
311 if (download.get().dccReceiver() != null) {
312 download.get().dccReceiver().stop();
314 /* remove download if it hasn’t started yet. */
315 downloads.remove(pack.name(), download.get());
318 /* remove the request from the bot, too. */
320 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
321 } catch (IOException ioe1) {
322 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
327 * Closes the given connection.
330 * The connection to close
332 public void closeConnection(Connection connection) {
335 } catch (IOException ioe1) {
341 // ABSTRACTIDLESERVICE METHODS
345 protected void startUp() {
346 for (Channel channel : channels) {
347 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
348 connectNetwork(channel.network());
351 /* notify listeners. */
352 eventBus.post(new CoreStarted(this));
356 protected void run() throws Exception {
357 while (isRunning()) {
359 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
360 } catch (InterruptedException ie1) {
364 /* find channels that should be monitored but are not. */
365 for (Channel channel : channels) {
366 if (joinedChannels.contains(channel)) {
370 connectNetwork(channel.network());
371 Connection connection = networkConnections.get(channel.network());
372 if (connection.established()) {
373 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
375 connection.joinChannel(channel.name());
376 } catch (IOException ioe1) {
377 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
385 protected void shutDown() {
393 * Starts a new connection for the given network if no such connection exists
397 * The network to connect to
399 private void connectNetwork(Network network) {
400 if (!networkConnections.containsKey(network)) {
401 /* select a random server. */
402 List<Server> servers = Lists.newArrayList(network.servers());
403 if (servers.isEmpty()) {
404 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
407 Server server = servers.get((int) (Math.random() * servers.size()));
408 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
409 connection.username(RandomNickname.get()).realName(RandomNickname.get());
410 networkConnections.put(network, connection);
416 * Removes the given connection and all its channels and bots.
419 * The connection to remove
421 private void removeConnection(Connection connection) {
422 Optional<Network> network = getNetwork(connection);
423 if (!network.isPresent()) {
427 /* find all channels that need to be removed. */
428 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
429 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
430 Channel joinedChannel = channelIterator.next();
431 if (!joinedChannel.network().equals(network.get())) {
435 channelIterator.remove();
439 /* now remove all bots for that network. */
440 Map<String, Bot> bots = networkBots.row(network.get());
441 int botCount = bots.size();
443 for (Bot bot : bots.values()) {
444 packCount += bot.packs().size();
447 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
449 /* now remove the network. */
450 networkConnections.remove(network.get());
458 * If a connection to a network has been established, the channels associated
459 * with this network are joined.
461 * @param connectionEstablished
462 * The connection established event
465 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
467 /* get network for connection. */
468 Optional<Network> network = getNetwork(connectionEstablished.connection());
471 if (!network.isPresent()) {
472 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
476 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
478 /* join all channels on this network. */
479 for (Channel channel : channels) {
480 if (channel.network().equals(network.get())) {
482 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
483 connectionEstablished.connection().joinChannel(channel.name());
484 } catch (IOException ioe1) {
485 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
492 * Remove all data stored for a network if the connection is closed.
494 * @param connectionClosed
495 * The connection closed event
498 public void connectionClosed(ConnectionClosed connectionClosed) {
499 removeConnection(connectionClosed.connection());
503 * Remove all data stored for a network if the connection fails.
505 * @param connectionFailed
506 * The connection failed event
509 public void connectionFailed(ConnectionFailed connectionFailed) {
510 removeConnection(connectionFailed.connection());
514 * Shows a message when a channel was joined by us.
516 * @param channelJoined
517 * The channel joined event
520 public void channelJoined(ChannelJoined channelJoined) {
521 if (channelJoined.connection().isSource(channelJoined.client())) {
522 Optional<Network> network = getNetwork(channelJoined.connection());
523 if (!network.isPresent()) {
527 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
528 if (!channel.isPresent()) {
529 /* it’s an extra channel. */
530 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
531 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
535 joinedChannels.add(channel.get());
536 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
541 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
542 Optional<Network> network = getNetwork(channelNotJoined.connection());
543 if (!network.isPresent()) {
547 eventBus.post(new GenericMessage(
548 format("Could not join %s/%s: %s", channelNotJoined.channel(),
549 network.get(), channelNotJoined.reason())));
553 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
556 * The channel left event
559 public void channelLeft(ChannelLeft channelLeft) {
560 Optional<Network> network = getNetwork(channelLeft.connection());
561 if (!network.isPresent()) {
565 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
567 /* maybe it was us? */
568 if (channelLeft.connection().isSource(channelLeft.client())) {
569 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
570 if (!channel.isPresent()) {
571 /* maybe it was an extra channel? */
572 channel = getExtraChannel(network.get(), channelLeft.channel());
573 if (!channel.isPresent()) {
574 /* okay, whatever. */
578 extraChannels.remove(channel);
580 channels.remove(channel.get());
583 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
589 networkBots.remove(network.get(), channelLeft.client().nick().get());
593 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
594 Optional<Network> network = getNetwork(kickedFromChannel.connection());
595 if (!network.isPresent()) {
599 /* have we been kicked? */
600 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
601 eventBus.post(new GenericMessage(format(
602 "Kicked from %s/%s by %s: %s",
603 kickedFromChannel.channel(), network.get(),
604 kickedFromChannel.kicker(),
605 kickedFromChannel.reason().or("<unknown>")
610 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
611 return connection.nickname().equalsIgnoreCase(nickname);
615 * Removes a client (which may be a bot) from the table of known bots.
618 * The client quit event
621 public void clientQuit(ClientQuit clientQuit) {
622 Optional<Network> network = getNetwork(clientQuit.connection());
623 if (!network.isPresent()) {
627 networkBots.remove(network.get(), clientQuit.client().nick().get());
631 * If the nickname of a bit changes, remove it from the old name and store it
632 * under the new name.
634 * @param nicknameChanged
635 * The nickname changed event
638 public void nicknameChanged(NicknameChanged nicknameChanged) {
639 Optional<Network> network = getNetwork(nicknameChanged.connection());
640 if (!network.isPresent()) {
644 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
649 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
653 * If a message on a channel is received, it is parsed for pack information
654 * with is then added to a bot.
656 * @param channelMessageReceived
657 * The channel message received event
660 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
661 String message = getDefaultInstance().clean(channelMessageReceived.message());
662 if (!message.startsWith("#")) {
663 /* most probably not a pack announcement. */
667 Optional<Network> network = getNetwork(channelMessageReceived.connection());
668 if (!network.isPresent()) {
669 /* message for unknown connection? */
673 /* parse pack information. */
674 Optional<Pack> pack = parsePack(message);
675 if (!pack.isPresent()) {
680 synchronized (networkBots) {
681 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
682 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
683 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
684 eventBus.post(new BotAdded(bot));
686 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
691 bot.addPack(pack.get());
692 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
696 * Forward all private messages to every console.
698 * @param privateMessageReceived
699 * The private message recevied event
702 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
703 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
707 * Sends a message to all console when a notice was received.
709 * @param privateNoticeReceived
710 * The notice received event
713 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
714 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
715 if (!network.isPresent()) {
719 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
723 * Starts a DCC download.
725 * @param dccSendReceived
729 public void dccSendReceived(final DccSendReceived dccSendReceived) {
730 final Optional<Network> network = getNetwork(dccSendReceived.connection());
731 if (!network.isPresent()) {
735 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
736 if (packDownloads.isEmpty()) {
737 /* unknown download, ignore. */
741 /* check if it’s already downloading. */
742 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
743 if (!runningDownloads.isEmpty()) {
744 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
748 /* locate the correct download. */
749 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
752 public boolean apply(Download download) {
753 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
757 /* we did not request this download. */
758 if (requestedDownload.isEmpty()) {
762 Download download = requestedDownload.iterator().next();
764 /* check if the file already exists. */
765 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
766 if (outputFile.exists()) {
767 long existingFileSize = outputFile.length();
769 /* file already complete? */
770 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
771 /* file is apparently already complete. just move it. */
772 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
773 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
775 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
778 /* remove download. */
779 downloads.removeAll(download.pack().name());
783 /* file not complete yet, DCC resume it. */
785 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
786 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
787 } catch (IOException ioe1) {
788 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
794 /* file does not exist, start the download. */
796 OutputStream fileOutputStream = new FileOutputStream(outputFile);
797 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
798 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
799 dccReceivers.add(dccReceiver);
801 eventBus.post(new DownloadStarted(download));
802 } catch (FileNotFoundException fnfe1) {
803 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
808 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
809 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
810 if (!network.isPresent()) {
814 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
815 if (packDownloads.isEmpty()) {
816 /* unknown download, ignore. */
820 /* check if it’s already downloading. */
821 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
822 if (!runningDownloads.isEmpty()) {
823 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
827 /* locate the correct download. */
828 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
831 public boolean apply(Download download) {
832 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
836 /* we did not request this download. */
837 if (requestedDownload.isEmpty()) {
841 Download download = requestedDownload.iterator().next();
844 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
845 if (outputFile.length() != dccAcceptReceived.position()) {
846 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
847 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()));
849 downloads.removeAll(download.pack().name());
852 OutputStream outputStream = new FileOutputStream(outputFile, true);
853 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
854 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
855 dccReceivers.add(dccReceiver);
857 eventBus.post(new DownloadStarted(download));
858 } catch (FileNotFoundException fnfe1) {
863 * Closes the output stream of the download and moves the file to the final
866 * @param dccDownloadFinished
867 * The DCC download finished event
870 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
872 /* locate the correct download. */
873 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
874 if (requestedDownload.isEmpty()) {
875 /* this seems wrong. */
876 logger.warn("Download finished but could not be located.");
879 Download download = requestedDownload.iterator().next();
882 download.outputStream().close();
883 File file = new File(download.filename());
884 file.renameTo(new File(finalDirectory, download.pack().name()));
885 eventBus.post(new DownloadFinished(download));
886 dccReceivers.remove(dccDownloadFinished.dccReceiver());
887 downloads.removeAll(download.pack().name());
888 } catch (IOException ioe1) {
889 /* TODO - handle all the errors. */
890 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
895 * Closes the output stream and notifies all listeners of the failure.
897 * @param dccDownloadFailed
898 * The DCC download failed event
901 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
903 /* locate the correct download. */
904 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
905 if (requestedDownload.isEmpty()) {
906 /* this seems wrong. */
907 logger.warn("Download finished but could not be located.");
910 Download download = requestedDownload.iterator().next();
913 Closeables.close(download.outputStream(), true);
914 eventBus.post(new DownloadFailed(download));
915 dccReceivers.remove(dccDownloadFailed.dccReceiver());
916 downloads.removeAll(download.pack().name());
917 } catch (IOException ioe1) {
918 /* swallow silently. */
923 public void replyReceived(ReplyReceived replyReceived) {
924 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
932 * Returns the download of the given pack from the given bot.
935 * The pack being downloaded
937 * The bot the pack is being downloaded from
938 * @return The download, or {@link Optional#absent()} if the download could not
941 private Optional<Download> getDownload(Pack pack, Bot bot) {
942 if (!downloads.containsKey(pack.name())) {
943 return Optional.absent();
945 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
946 if (download.bot().equals(bot)) {
947 return Optional.of(download);
950 return Optional.absent();
954 * Searches all current connections for the given connection, returning the
955 * associated network.
958 * The connection to get the network for
959 * @return The network belonging to the connection, or {@link
962 private Optional<Network> getNetwork(Connection connection) {
963 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
964 if (networkConnectionEntry.getValue().equals(connection)) {
965 return Optional.of(networkConnectionEntry.getKey());
968 return Optional.absent();
972 * Returns the configured channel for the given network and name.
975 * The network the channel is located on
977 * The name of the channel
978 * @return The configured channel, or {@link Optional#absent()} if no
979 * configured channel matching the given network and name was found
981 public Optional<Channel> getChannel(Network network, String channelName) {
982 for (Channel channel : channels) {
983 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
984 return Optional.of(channel);
987 return Optional.absent();
991 * Returns the extra channel for the given network and name.
994 * The network the channel is located on
996 * The name of the channel
997 * @return The extra channel, or {@link Optional#absent()} if no extra channel
998 * matching the given network and name was found
1000 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1001 for (Channel channel : extraChannels) {
1002 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1003 return Optional.of(channel);
1006 return Optional.absent();
1010 * Parses {@link Pack} information from the given message.
1013 * The message to parse pack information from
1014 * @return The parsed pack, or {@link Optional#absent()} if the message could
1015 * not be parsed into a pack
1017 private Optional<Pack> parsePack(String message) {
1018 int squareOpen = message.indexOf('[');
1019 int squareClose = message.indexOf(']', squareOpen);
1020 if ((squareOpen == -1) && (squareClose == -1)) {
1021 return Optional.absent();
1023 String packSize = message.substring(squareOpen + 1, squareClose);
1024 String packName = message.substring(message.lastIndexOf(' ') + 1);
1025 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1026 return Optional.of(new Pack(packIndex, packSize, packName));