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 java.lang.System.currentTimeMillis;
22 import static java.util.concurrent.TimeUnit.HOURS;
23 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.banned;
24 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.registeredNicknamesOnly;
25 import static net.pterodactylus.irc.util.MessageCleaner.getDefaultInstance;
26 import static net.pterodactylus.xdcc.data.Channel.TO_NETWORK;
27 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
30 import java.io.FileNotFoundException;
31 import java.io.FileOutputStream;
32 import java.io.IOException;
33 import java.io.OutputStream;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.Map.Entry;
40 import java.util.concurrent.TimeUnit;
42 import net.pterodactylus.irc.Connection;
43 import net.pterodactylus.irc.ConnectionBuilder;
44 import net.pterodactylus.irc.DccReceiver;
45 import net.pterodactylus.irc.event.ChannelJoined;
46 import net.pterodactylus.irc.event.ChannelLeft;
47 import net.pterodactylus.irc.event.ChannelMessageReceived;
48 import net.pterodactylus.irc.event.ChannelNotJoined;
49 import net.pterodactylus.irc.event.ClientQuit;
50 import net.pterodactylus.irc.event.ConnectionClosed;
51 import net.pterodactylus.irc.event.ConnectionEstablished;
52 import net.pterodactylus.irc.event.ConnectionFailed;
53 import net.pterodactylus.irc.event.DccAcceptReceived;
54 import net.pterodactylus.irc.event.DccDownloadFailed;
55 import net.pterodactylus.irc.event.DccDownloadFinished;
56 import net.pterodactylus.irc.event.DccSendReceived;
57 import net.pterodactylus.irc.event.KickedFromChannel;
58 import net.pterodactylus.irc.event.NicknameChanged;
59 import net.pterodactylus.irc.event.PrivateMessageReceived;
60 import net.pterodactylus.irc.event.PrivateNoticeReceived;
61 import net.pterodactylus.irc.event.ReplyReceived;
62 import net.pterodactylus.irc.util.RandomNickname;
63 import net.pterodactylus.xdcc.core.event.BotAdded;
64 import net.pterodactylus.xdcc.core.event.CoreStarted;
65 import net.pterodactylus.xdcc.core.event.DownloadFailed;
66 import net.pterodactylus.xdcc.core.event.DownloadFinished;
67 import net.pterodactylus.xdcc.core.event.DownloadStarted;
68 import net.pterodactylus.xdcc.core.event.GenericError;
69 import net.pterodactylus.xdcc.core.event.GenericMessage;
70 import net.pterodactylus.xdcc.core.event.MessageReceived;
71 import net.pterodactylus.xdcc.data.Bot;
72 import net.pterodactylus.xdcc.data.Channel;
73 import net.pterodactylus.xdcc.data.Download;
74 import net.pterodactylus.xdcc.data.Network;
75 import net.pterodactylus.xdcc.data.Pack;
76 import net.pterodactylus.xdcc.data.Server;
78 import com.google.common.base.Function;
79 import com.google.common.base.Optional;
80 import com.google.common.base.Predicate;
81 import com.google.common.collect.FluentIterable;
82 import com.google.common.collect.HashBasedTable;
83 import com.google.common.collect.HashMultimap;
84 import com.google.common.collect.ImmutableList;
85 import com.google.common.collect.ImmutableSet;
86 import com.google.common.collect.Lists;
87 import com.google.common.collect.Maps;
88 import com.google.common.collect.Multimap;
89 import com.google.common.collect.Sets;
90 import com.google.common.collect.Table;
91 import com.google.common.eventbus.EventBus;
92 import com.google.common.eventbus.Subscribe;
93 import com.google.common.io.Closeables;
94 import com.google.common.util.concurrent.AbstractExecutionThreadService;
95 import com.google.inject.Inject;
96 import org.apache.log4j.Logger;
99 * The core of XDCC Downloader.
101 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
103 public class Core extends AbstractExecutionThreadService {
106 private static final Logger logger = Logger.getLogger(Core.class.getName());
108 /** The event bus. */
109 private final EventBus eventBus;
110 private final ChannelBanManager channelBanManager =
111 new ChannelBanManager();
113 /** The temporary directory to download files to. */
114 private final String temporaryDirectory;
116 /** The directory to move finished downloads to. */
117 private final String finalDirectory;
119 /** The channels that should be monitored. */
120 private final Collection<Channel> channels = Sets.newHashSet();
122 /** The channels that are currentlymonitored. */
123 private final Collection<Channel> joinedChannels = Sets.newHashSet();
125 /** The channels that are joined but not configured. */
126 private final Collection<Channel> extraChannels = Sets.newHashSet();
128 /** The current network connections. */
129 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
131 /** The currently known bots. */
132 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
134 /** The current downloads. */
135 private final Multimap<String, Download> downloads = HashMultimap.create();
137 /** The current DCC receivers. */
138 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
141 * Creates a new core.
145 * @param temporaryDirectory
146 * The directory to download files to
147 * @param finalDirectory
148 * The directory to move finished files to
151 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
152 this.eventBus = eventBus;
153 this.temporaryDirectory = temporaryDirectory;
154 this.finalDirectory = finalDirectory;
162 * Returns all currently known connections.
164 * @return All currently known connections
166 public Collection<Connection> connections() {
167 return networkConnections.values();
171 * Returns all defined networks.
173 * @return All defined networks
175 public Collection<Network> networks() {
176 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
180 * Returns all connected networks.
182 * @return All connected networks
184 public Collection<Network> connectedNetworks() {
185 return Lists.newArrayList(Optional.presentInstances(FluentIterable.from(networkConnections.values()).transform(new Function<Connection, Optional<Network>>() {
187 public Optional<Network> apply(Connection connection) {
188 return getNetwork(connection);
194 * Returns all configured channels. Due to various circumstances, configured
195 * channels might not actually be joined.
197 * @return All configured channels
199 public Collection<Channel> channels() {
200 return ImmutableSet.copyOf(channels);
204 * Returns all currently joined channels.
206 * @return All currently joined channels
208 public Collection<Channel> joinedChannels() {
209 return ImmutableSet.copyOf(joinedChannels);
213 * Returns all currently joined channels that are not configured.
215 * @return All currently joined but not configured channels
217 public Collection<Channel> extraChannels() {
218 return ImmutableSet.copyOf(extraChannels);
222 * Returns all currently known bots.
224 * @return All currently known bots
226 public Collection<Bot> bots() {
227 return networkBots.values();
231 * Returns all currently running downloads.
233 * @return All currently running downloads
235 public Collection<Download> downloads() {
236 return downloads.values();
244 * Adds a channel to monitor.
247 * The channel to monitor
249 public void addChannel(Channel channel) {
250 channels.add(channel);
254 * Fetches the given pack from the given bot.
257 * The bot to fetch the pack from
261 public void fetch(Bot bot, Pack pack) {
262 Connection connection = networkConnections.get(bot.network());
263 if (connection == null) {
267 /* check if we are already downloading the file? */
268 if (downloads.containsKey(pack.name())) {
269 Collection<Download> packDownloads = downloads.get(pack.name());
270 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
271 if (!runningDownloads.isEmpty()) {
272 Download download = runningDownloads.iterator().next();
273 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
276 StringBuilder bots = new StringBuilder();
277 for (Download download : packDownloads) {
278 if (bots.length() > 0) {
281 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
283 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
286 Download download = new Download(bot, pack);
287 downloads.put(pack.name(), download);
290 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
291 } catch (IOException ioe1) {
292 logger.warn("Could not send message to bot!", ioe1);
297 * Cancels the download of the given pack from the given bot.
300 * The bot the pack is being downloaded from
302 * The pack being downloaded
304 public void cancelDownload(Bot bot, Pack pack) {
305 Optional<Download> download = getDownload(pack, bot);
306 if (!download.isPresent()) {
310 /* get connection. */
311 Connection connection = networkConnections.get(bot.network());
312 if (connection == null) {
313 /* request for unknown network? */
317 /* stop the DCC receiver. */
318 if (download.get().dccReceiver() != null) {
319 download.get().dccReceiver().stop();
321 /* remove download if it hasn’t started yet. */
322 downloads.remove(pack.name(), download.get());
325 /* remove the request from the bot, too. */
327 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
328 } catch (IOException ioe1) {
329 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
334 * Closes the given connection.
337 * The connection to close
339 public void closeConnection(Connection connection) {
342 } catch (IOException ioe1) {
348 // ABSTRACTIDLESERVICE METHODS
352 protected void startUp() {
353 for (Channel channel : channels) {
354 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
355 connectNetwork(channel.network());
358 /* notify listeners. */
359 eventBus.post(new CoreStarted(this));
363 protected void run() throws Exception {
364 while (isRunning()) {
366 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
367 } catch (InterruptedException ie1) {
371 /* find channels that should be monitored but are not. */
372 for (Channel channel : channels) {
373 if (joinedChannels.contains(channel)) {
377 /* are we banned from this channel? */
378 if (channelBanManager.isBanned(channel)) {
382 connectNetwork(channel.network());
383 Connection connection = networkConnections.get(channel.network());
384 if (connection.established()) {
385 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
387 connection.joinChannel(channel.name());
388 } catch (IOException ioe1) {
389 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
397 protected void shutDown() {
405 * Starts a new connection for the given network if no such connection exists
409 * The network to connect to
411 private void connectNetwork(Network network) {
412 if (!networkConnections.containsKey(network)) {
413 /* select a random server. */
414 List<Server> servers = Lists.newArrayList(network.servers());
415 if (servers.isEmpty()) {
416 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
419 Server server = servers.get((int) (Math.random() * servers.size()));
420 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
421 connection.username(RandomNickname.get()).realName(RandomNickname.get());
422 networkConnections.put(network, connection);
428 * Removes the given connection and all its channels and bots.
431 * The connection to remove
433 private void removeConnection(Connection connection) {
434 Optional<Network> network = getNetwork(connection);
435 if (!network.isPresent()) {
439 /* find all channels that need to be removed. */
440 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
441 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
442 Channel joinedChannel = channelIterator.next();
443 if (!joinedChannel.network().equals(network.get())) {
447 channelIterator.remove();
451 /* now remove all bots for that network. */
452 Map<String, Bot> bots = networkBots.row(network.get());
453 int botCount = bots.size();
455 for (Bot bot : bots.values()) {
456 packCount += bot.packs().size();
459 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
461 /* now remove the network. */
462 networkConnections.remove(network.get());
470 * If a connection to a network has been established, the channels associated
471 * with this network are joined.
473 * @param connectionEstablished
474 * The connection established event
477 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
479 /* get network for connection. */
480 Optional<Network> network = getNetwork(connectionEstablished.connection());
483 if (!network.isPresent()) {
484 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
488 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
490 /* join all channels on this network. */
491 for (Channel channel : channels) {
492 if (channel.network().equals(network.get())) {
494 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
495 connectionEstablished.connection().joinChannel(channel.name());
496 } catch (IOException ioe1) {
497 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
504 * Remove all data stored for a network if the connection is closed.
506 * @param connectionClosed
507 * The connection closed event
510 public void connectionClosed(ConnectionClosed connectionClosed) {
511 removeConnection(connectionClosed.connection());
515 * Remove all data stored for a network if the connection fails.
517 * @param connectionFailed
518 * The connection failed event
521 public void connectionFailed(ConnectionFailed connectionFailed) {
522 removeConnection(connectionFailed.connection());
526 * Shows a message when a channel was joined by us.
528 * @param channelJoined
529 * The channel joined event
532 public void channelJoined(ChannelJoined channelJoined) {
533 if (channelJoined.connection().isSource(channelJoined.client())) {
534 Optional<Network> network = getNetwork(channelJoined.connection());
535 if (!network.isPresent()) {
539 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
540 if (!channel.isPresent()) {
541 /* it’s an extra channel. */
542 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
543 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
547 channelBanManager.unban(channel.get());
548 joinedChannels.add(channel.get());
549 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
554 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
555 Optional<Network> network = getNetwork(channelNotJoined.connection());
556 if (!network.isPresent()) {
560 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
561 if (!channel.isPresent()) {
562 eventBus.post(new GenericMessage(format("Could not join %s but didn’t try to join, either.", channel.get())));
566 if (channelNotJoined.reason() == registeredNicknamesOnly) {
567 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
568 if (channel.isPresent()) {
569 eventBus.post(new GenericMessage(format("Not trying to join %s anymore.", channel.get())));
570 channels.remove(channel.get());
574 if (channelNotJoined.reason() == banned) {
575 channelBanManager.ban(channel.get());
576 eventBus.post(new GenericMessage(
577 format("Banned from %s, suspending join for day.",
582 eventBus.post(new GenericMessage(
583 format("Could not join %s: %s", channelNotJoined.channel(),
584 channelNotJoined.reason())));
588 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
591 * The channel left event
594 public void channelLeft(ChannelLeft channelLeft) {
595 Optional<Network> network = getNetwork(channelLeft.connection());
596 if (!network.isPresent()) {
600 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
602 /* maybe it was us? */
603 if (channelLeft.connection().isSource(channelLeft.client())) {
604 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
605 if (!channel.isPresent()) {
606 /* maybe it was an extra channel? */
607 channel = getExtraChannel(network.get(), channelLeft.channel());
608 if (!channel.isPresent()) {
609 /* okay, whatever. */
613 extraChannels.remove(channel);
615 channels.remove(channel.get());
618 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
624 networkBots.remove(network.get(), channelLeft.client().nick().get());
628 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
629 Optional<Network> network = getNetwork(kickedFromChannel.connection());
630 if (!network.isPresent()) {
634 /* have we been kicked? */
635 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
636 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
637 if (!channel.isPresent()) {
638 /* maybe it was an extra channel? */
639 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
640 if (!channel.isPresent()) {
641 /* okay, whatever. */
645 extraChannels.remove(channel);
647 channels.remove(channel.get());
649 eventBus.post(new GenericMessage(format(
650 "Kicked from %s by %s: %s",
651 kickedFromChannel.channel(),
652 kickedFromChannel.kicker(),
653 kickedFromChannel.reason().or("<unknown>")
658 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
659 return connection.nickname().equalsIgnoreCase(nickname);
663 * Removes a client (which may be a bot) from the table of known bots.
666 * The client quit event
669 public void clientQuit(ClientQuit clientQuit) {
670 Optional<Network> network = getNetwork(clientQuit.connection());
671 if (!network.isPresent()) {
675 networkBots.remove(network.get(), clientQuit.client().nick().get());
679 * If the nickname of a bit changes, remove it from the old name and store it
680 * under the new name.
682 * @param nicknameChanged
683 * The nickname changed event
686 public void nicknameChanged(NicknameChanged nicknameChanged) {
687 Optional<Network> network = getNetwork(nicknameChanged.connection());
688 if (!network.isPresent()) {
692 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
697 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
701 * If a message on a channel is received, it is parsed for pack information
702 * with is then added to a bot.
704 * @param channelMessageReceived
705 * The channel message received event
708 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
709 String message = getDefaultInstance().clean(channelMessageReceived.message());
710 if (!message.startsWith("#")) {
711 /* most probably not a pack announcement. */
715 Optional<Network> network = getNetwork(channelMessageReceived.connection());
716 if (!network.isPresent()) {
717 /* message for unknown connection? */
721 /* parse pack information. */
722 Optional<Pack> pack = parsePack(message);
723 if (!pack.isPresent()) {
728 synchronized (networkBots) {
729 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
730 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
731 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
732 eventBus.post(new BotAdded(bot));
734 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
739 bot.addPack(pack.get());
740 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
744 * Forward all private messages to every console.
746 * @param privateMessageReceived
747 * The private message recevied event
750 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
751 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
755 * Sends a message to all console when a notice was received.
757 * @param privateNoticeReceived
758 * The notice received event
761 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
762 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
763 if (!network.isPresent()) {
767 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
771 * Starts a DCC download.
773 * @param dccSendReceived
777 public void dccSendReceived(final DccSendReceived dccSendReceived) {
778 final Optional<Network> network = getNetwork(dccSendReceived.connection());
779 if (!network.isPresent()) {
783 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
784 if (packDownloads.isEmpty()) {
785 /* unknown download, ignore. */
789 /* check if it’s already downloading. */
790 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
791 if (!runningDownloads.isEmpty()) {
792 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
796 /* locate the correct download. */
797 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
800 public boolean apply(Download download) {
801 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
805 /* we did not request this download. */
806 if (requestedDownload.isEmpty()) {
810 Download download = requestedDownload.iterator().next();
812 /* check if the file already exists. */
813 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
814 if (outputFile.exists()) {
815 long existingFileSize = outputFile.length();
817 /* file already complete? */
818 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
819 /* file is apparently already complete. just move it. */
820 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
821 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
823 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
826 /* remove download. */
827 downloads.removeAll(download.pack().name());
831 /* file not complete yet, DCC resume it. */
833 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
834 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
835 } catch (IOException ioe1) {
836 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
842 /* file does not exist, start the download. */
844 OutputStream fileOutputStream = new FileOutputStream(outputFile);
845 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
846 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
847 dccReceivers.add(dccReceiver);
849 eventBus.post(new DownloadStarted(download));
850 } catch (FileNotFoundException fnfe1) {
851 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
856 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
857 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
858 if (!network.isPresent()) {
862 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
863 if (packDownloads.isEmpty()) {
864 /* unknown download, ignore. */
868 /* check if it’s already downloading. */
869 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
870 if (!runningDownloads.isEmpty()) {
871 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
875 /* locate the correct download. */
876 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
879 public boolean apply(Download download) {
880 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
884 /* we did not request this download. */
885 if (requestedDownload.isEmpty()) {
889 Download download = requestedDownload.iterator().next();
892 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
893 if (outputFile.length() != dccAcceptReceived.position()) {
894 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
895 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()));
897 downloads.removeAll(download.pack().name());
900 OutputStream outputStream = new FileOutputStream(outputFile, true);
901 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
902 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
903 dccReceivers.add(dccReceiver);
905 eventBus.post(new DownloadStarted(download));
906 } catch (FileNotFoundException fnfe1) {
911 * Closes the output stream of the download and moves the file to the final
914 * @param dccDownloadFinished
915 * The DCC download finished event
918 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
920 /* locate the correct download. */
921 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
922 if (requestedDownload.isEmpty()) {
923 /* this seems wrong. */
924 logger.warn("Download finished but could not be located.");
927 Download download = requestedDownload.iterator().next();
930 download.outputStream().close();
931 File file = new File(download.filename());
932 file.renameTo(new File(finalDirectory, download.pack().name()));
933 eventBus.post(new DownloadFinished(download));
934 dccReceivers.remove(dccDownloadFinished.dccReceiver());
935 downloads.removeAll(download.pack().name());
936 } catch (IOException ioe1) {
937 /* TODO - handle all the errors. */
938 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
943 * Closes the output stream and notifies all listeners of the failure.
945 * @param dccDownloadFailed
946 * The DCC download failed event
949 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
951 /* locate the correct download. */
952 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
953 if (requestedDownload.isEmpty()) {
954 /* this seems wrong. */
955 logger.warn("Download finished but could not be located.");
958 Download download = requestedDownload.iterator().next();
961 Closeables.close(download.outputStream(), true);
962 eventBus.post(new DownloadFailed(download));
963 dccReceivers.remove(dccDownloadFailed.dccReceiver());
964 downloads.removeAll(download.pack().name());
965 } catch (IOException ioe1) {
966 /* swallow silently. */
971 public void replyReceived(ReplyReceived replyReceived) {
972 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
980 * Returns the download of the given pack from the given bot.
983 * The pack being downloaded
985 * The bot the pack is being downloaded from
986 * @return The download, or {@link Optional#absent()} if the download could not
989 private Optional<Download> getDownload(Pack pack, Bot bot) {
990 if (!downloads.containsKey(pack.name())) {
991 return Optional.absent();
993 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
994 if (download.bot().equals(bot)) {
995 return Optional.of(download);
998 return Optional.absent();
1002 * Searches all current connections for the given connection, returning the
1003 * associated network.
1006 * The connection to get the network for
1007 * @return The network belonging to the connection, or {@link
1008 * Optional#absent()}
1010 private Optional<Network> getNetwork(Connection connection) {
1011 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1012 if (networkConnectionEntry.getValue().equals(connection)) {
1013 return Optional.of(networkConnectionEntry.getKey());
1016 return Optional.absent();
1020 * Returns the configured channel for the given network and name.
1023 * The network the channel is located on
1024 * @param channelName
1025 * The name of the channel
1026 * @return The configured channel, or {@link Optional#absent()} if no
1027 * configured channel matching the given network and name was found
1029 public Optional<Channel> getChannel(Network network, String channelName) {
1030 for (Channel channel : channels) {
1031 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1032 return Optional.of(channel);
1035 return Optional.absent();
1039 * Returns the extra channel for the given network and name.
1042 * The network the channel is located on
1043 * @param channelName
1044 * The name of the channel
1045 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1046 * matching the given network and name was found
1048 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1049 for (Channel channel : extraChannels) {
1050 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1051 return Optional.of(channel);
1054 return Optional.absent();
1058 * Parses {@link Pack} information from the given message.
1061 * The message to parse pack information from
1062 * @return The parsed pack, or {@link Optional#absent()} if the message could
1063 * not be parsed into a pack
1065 private Optional<Pack> parsePack(String message) {
1066 int squareOpen = message.indexOf('[');
1067 int squareClose = message.indexOf(']', squareOpen);
1068 if ((squareOpen == -1) && (squareClose == -1)) {
1069 return Optional.absent();
1071 String packSize = message.substring(squareOpen + 1, squareClose);
1072 String packName = message.substring(message.lastIndexOf(' ') + 1);
1073 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1074 return Optional.of(new Pack(packIndex, packSize, packName));