d875a5b21d2f0cb5ef38db28b10a37a203b7fea3
[xudocci.git] / src / main / java / net / pterodactylus / xdcc / core / Core.java
1 /*
2  * XdccDownloader - Core.java - Copyright © 2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.xdcc.core;
19
20 import static net.pterodactylus.irc.util.MessageCleaner.getDefaultInstance;
21 import static net.pterodactylus.xdcc.data.Channel.TO_NETWORK;
22 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
23
24 import java.io.File;
25 import java.io.FileNotFoundException;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.OutputStream;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.concurrent.TimeUnit;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38
39 import net.pterodactylus.irc.Connection;
40 import net.pterodactylus.irc.ConnectionBuilder;
41 import net.pterodactylus.irc.DccReceiver;
42 import net.pterodactylus.irc.event.ChannelJoined;
43 import net.pterodactylus.irc.event.ChannelLeft;
44 import net.pterodactylus.irc.event.ChannelMessageReceived;
45 import net.pterodactylus.irc.event.ClientQuit;
46 import net.pterodactylus.irc.event.ConnectionClosed;
47 import net.pterodactylus.irc.event.ConnectionEstablished;
48 import net.pterodactylus.irc.event.ConnectionFailed;
49 import net.pterodactylus.irc.event.DccAcceptReceived;
50 import net.pterodactylus.irc.event.DccDownloadFailed;
51 import net.pterodactylus.irc.event.DccDownloadFinished;
52 import net.pterodactylus.irc.event.DccSendReceived;
53 import net.pterodactylus.irc.event.NicknameChanged;
54 import net.pterodactylus.irc.event.PrivateMessageReceived;
55 import net.pterodactylus.irc.event.PrivateNoticeReceived;
56 import net.pterodactylus.irc.event.ReplyReceived;
57 import net.pterodactylus.irc.util.RandomNickname;
58 import net.pterodactylus.xdcc.core.event.BotAdded;
59 import net.pterodactylus.xdcc.core.event.CoreStarted;
60 import net.pterodactylus.xdcc.core.event.DownloadFailed;
61 import net.pterodactylus.xdcc.core.event.DownloadFinished;
62 import net.pterodactylus.xdcc.core.event.DownloadStarted;
63 import net.pterodactylus.xdcc.core.event.GenericError;
64 import net.pterodactylus.xdcc.core.event.GenericMessage;
65 import net.pterodactylus.xdcc.core.event.MessageReceived;
66 import net.pterodactylus.xdcc.data.Bot;
67 import net.pterodactylus.xdcc.data.Channel;
68 import net.pterodactylus.xdcc.data.Download;
69 import net.pterodactylus.xdcc.data.Network;
70 import net.pterodactylus.xdcc.data.Pack;
71 import net.pterodactylus.xdcc.data.Server;
72
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
92 /**
93  * The core of XDCC Downloader.
94  *
95  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
96  */
97 public class Core extends AbstractExecutionThreadService {
98
99         /** The logger. */
100         private static final Logger logger = Logger.getLogger(Core.class.getName());
101
102         /** The event bus. */
103         private final EventBus eventBus;
104
105         /** The temporary directory to download files to. */
106         private final String temporaryDirectory;
107
108         /** The directory to move finished downloads to. */
109         private final String finalDirectory;
110
111         /** The channels that should be monitored. */
112         private final Collection<Channel> channels = Sets.newHashSet();
113
114         /** The channels that are currentlymonitored. */
115         private final Collection<Channel> joinedChannels = Sets.newHashSet();
116
117         /** The channels that are joined but not configured. */
118         private final Collection<Channel> extraChannels = Sets.newHashSet();
119
120         /** The current network connections. */
121         private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
122
123         /** The currently known bots. */
124         private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
125
126         /** The current downloads. */
127         private final Multimap<String, Download> downloads = HashMultimap.create();
128
129         /** The current DCC receivers. */
130         private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
131
132         /**
133          * Creates a new core.
134          *
135          * @param eventBus
136          *              The event bus
137          * @param temporaryDirectory
138          *              The directory to download files to
139          * @param finalDirectory
140          *              The directory to move finished files to
141          */
142         @Inject
143         public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
144                 this.eventBus = eventBus;
145                 this.temporaryDirectory = temporaryDirectory;
146                 this.finalDirectory = finalDirectory;
147         }
148
149         //
150         // ACCESSORS
151         //
152
153         /**
154          * Returns all currently known connections.
155          *
156          * @return All currently known connections
157          */
158         public Collection<Connection> connections() {
159                 return networkConnections.values();
160         }
161
162         /**
163          * Returns all defined networks.
164          *
165          * @return All defined networks
166          */
167         public Collection<Network> networks() {
168                 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
169         }
170
171         /**
172          * Returns all connected networks.
173          *
174          * @return All connected networks
175          */
176         public Collection<Network> connectedNetworks() {
177                 return Lists.newArrayList(Optional.presentInstances(FluentIterable.from(networkConnections.values()).transform(new Function<Connection, Optional<Network>>() {
178                         @Override
179                         public Optional<Network> apply(Connection connection) {
180                                 return getNetwork(connection);
181                         }
182                 })));
183         }
184
185         /**
186          * Returns all configured channels. Due to various circumstances, configured
187          * channels might not actually be joined.
188          *
189          * @return All configured channels
190          */
191         public Collection<Channel> channels() {
192                 return ImmutableSet.copyOf(channels);
193         }
194
195         /**
196          * Returns all currently joined channels.
197          *
198          * @return All currently joined channels
199          */
200         public Collection<Channel> joinedChannels() {
201                 return ImmutableSet.copyOf(joinedChannels);
202         }
203
204         /**
205          * Returns all currently joined channels that are not configured.
206          *
207          * @return All currently joined but not configured channels
208          */
209         public Collection<Channel> extraChannels() {
210                 return ImmutableSet.copyOf(extraChannels);
211         }
212
213         /**
214          * Returns all currently known bots.
215          *
216          * @return All currently known bots
217          */
218         public Collection<Bot> bots() {
219                 return networkBots.values();
220         }
221
222         /**
223          * Returns all currently running downloads.
224          *
225          * @return All currently running downloads
226          */
227         public Collection<Download> downloads() {
228                 return downloads.values();
229         }
230
231         //
232         // ACTIONS
233         //
234
235         /**
236          * Adds a channel to monitor.
237          *
238          * @param channel
239          *              The channel to monitor
240          */
241         public void addChannel(Channel channel) {
242                 channels.add(channel);
243         }
244
245         /**
246          * Fetches the given pack from the given bot.
247          *
248          * @param bot
249          *              The bot to fetch the pack from
250          * @param pack
251          *              The pack to fetch
252          */
253         public void fetch(Bot bot, Pack pack) {
254                 Connection connection = networkConnections.get(bot.network());
255                 if (connection == null) {
256                         return;
257                 }
258
259                 /* check if we are already downloading the file? */
260                 if (downloads.containsKey(pack.name())) {
261                         Collection<Download> packDownloads = downloads.get(pack.name());
262                         Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
263                         if (!runningDownloads.isEmpty()) {
264                                 Download download = runningDownloads.iterator().next();
265                                 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
266                                 return;
267                         }
268                         StringBuilder bots = new StringBuilder();
269                         for (Download download : packDownloads) {
270                                 if (bots.length() > 0) {
271                                         bots.append(", ");
272                                 }
273                                 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
274                         }
275                         eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
276                 }
277
278                 Download download = new Download(bot, pack);
279                 downloads.put(pack.name(), download);
280
281                 try {
282                         connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
283                 } catch (IOException ioe1) {
284                         logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
285                 }
286         }
287
288         /**
289          * Cancels the download of the given pack from the given bot.
290          *
291          * @param bot
292          *              The bot the pack is being downloaded from
293          * @param pack
294          *              The pack being downloaded
295          */
296         public void cancelDownload(Bot bot, Pack pack) {
297                 Optional<Download> download = getDownload(pack, bot);
298                 if (!download.isPresent()) {
299                         return;
300                 }
301
302                 /* get connection. */
303                 Connection connection = networkConnections.get(bot.network());
304                 if (connection == null) {
305                         /* request for unknown network? */
306                         return;
307                 }
308
309                 /* stop the DCC receiver. */
310                 if (download.get().dccReceiver() != null) {
311                         download.get().dccReceiver().stop();
312                 } else {
313                         /* remove download if it hasn’t started yet. */
314                         downloads.remove(pack.name(), download.get());
315                 }
316
317                 /* remove the request from the bot, too. */
318                 try {
319                         connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
320                 } catch (IOException ioe1) {
321                         logger.log(Level.WARNING, String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
322                 }
323         }
324
325         /**
326          * Closes the given connection.
327          *
328          * @param connection
329          *              The connection to close
330          */
331         public void closeConnection(Connection connection) {
332                 try {
333                         connection.close();
334                 } catch (IOException ioe1) {
335                         /* TODO */
336                 }
337         }
338
339         //
340         // ABSTRACTIDLESERVICE METHODS
341         //
342
343         @Override
344         protected void startUp() {
345                 for (Channel channel : channels) {
346                         logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
347                         connectNetwork(channel.network());
348                 }
349
350                 /* notify listeners. */
351                 eventBus.post(new CoreStarted(this));
352         }
353
354         @Override
355         protected void run() throws Exception {
356                 while (isRunning()) {
357                         try {
358                                 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
359                         } catch (InterruptedException ie1) {
360                                 /* ignore. */
361                         }
362
363                         /* find channels that should be monitored but are not. */
364                         for (Channel channel : channels) {
365                                 if (joinedChannels.contains(channel)) {
366                                         continue;
367                                 }
368
369                                 connectNetwork(channel.network());
370                                 Connection connection = networkConnections.get(channel.network());
371                                 if (connection.established()) {
372                                         eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
373                                         try {
374                                                 connection.joinChannel(channel.name());
375                                         } catch (IOException ioe1) {
376                                                 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
377                                         }
378                                 }
379                         }
380                 }
381         }
382
383         @Override
384         protected void shutDown() {
385         }
386
387         //
388         // PRIVATE METHODS
389         //
390
391         /**
392          * Starts a new connection for the given network if no such connection exists
393          * already.
394          *
395          * @param network
396          *              The network to connect to
397          */
398         private void connectNetwork(Network network) {
399                 if (!networkConnections.containsKey(network)) {
400                                 /* select a random server. */
401                         List<Server> servers = Lists.newArrayList(network.servers());
402                         if (servers.isEmpty()) {
403                                 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
404                                 return;
405                         }
406                         Server server = servers.get((int) (Math.random() * servers.size()));
407                         Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
408                         connection.username(RandomNickname.get()).realName(RandomNickname.get());
409                         networkConnections.put(network, connection);
410                         connection.start();
411                 }
412         }
413
414         /**
415          * Removes the given connection and all its channels and bots.
416          *
417          * @param connection
418          *              The connection to remove
419          */
420         private void removeConnection(Connection connection) {
421                 Optional<Network> network = getNetwork(connection);
422                 if (!network.isPresent()) {
423                         return;
424                 }
425
426                 /* find all channels that need to be removed. */
427                 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
428                         for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
429                                 Channel joinedChannel = channelIterator.next();
430                                 if (!joinedChannel.network().equals(network.get())) {
431                                         continue;
432                                 }
433
434                                 channelIterator.remove();
435                         }
436                 }
437
438                 /* now remove all bots for that network. */
439                 Map<String, Bot> bots = networkBots.row(network.get());
440                 int botCount = bots.size();
441                 int packCount = 0;
442                 for (Bot bot : bots.values()) {
443                         packCount += bot.packs().size();
444                 }
445                 bots.clear();
446                 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
447
448                 /* now remove the network. */
449                 networkConnections.remove(network.get());
450         }
451
452         //
453         // EVENT HANDLERS
454         //
455
456         /**
457          * If a connection to a network has been established, the channels associated
458          * with this network are joined.
459          *
460          * @param connectionEstablished
461          *              The connection established event
462          */
463         @Subscribe
464         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
465
466                 /* get network for connection. */
467                 Optional<Network> network = getNetwork(connectionEstablished.connection());
468
469                 /* found network? */
470                 if (!network.isPresent()) {
471                         eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
472                         return;
473                 }
474
475                 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
476
477                 /* join all channels on this network. */
478                 for (Channel channel : channels) {
479                         if (channel.network().equals(network.get())) {
480                                 try {
481                                         eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
482                                         connectionEstablished.connection().joinChannel(channel.name());
483                                 } catch (IOException ioe1) {
484                                         logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
485                                 }
486                         }
487                 }
488         }
489
490         /**
491          * Remove all data stored for a network if the connection is closed.
492          *
493          * @param connectionClosed
494          *              The connection closed event
495          */
496         @Subscribe
497         public void connectionClosed(ConnectionClosed connectionClosed) {
498                 removeConnection(connectionClosed.connection());
499         }
500
501         /**
502          * Remove all data stored for a network if the connection fails.
503          *
504          * @param connectionFailed
505          *              The connection failed event
506          */
507         @Subscribe
508         public void connectionFailed(ConnectionFailed connectionFailed) {
509                 removeConnection(connectionFailed.connection());
510         }
511
512         /**
513          * Shows a message when a channel was joined by us.
514          *
515          * @param channelJoined
516          *              The channel joined event
517          */
518         @Subscribe
519         public void channelJoined(ChannelJoined channelJoined) {
520                 if (channelJoined.connection().isSource(channelJoined.client())) {
521                         Optional<Network> network = getNetwork(channelJoined.connection());
522                         if (!network.isPresent()) {
523                                 return;
524                         }
525
526                         Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
527                         if (!channel.isPresent()) {
528                                 /* it’s an extra channel. */
529                                 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
530                                 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
531                                 return;
532                         }
533
534                         joinedChannels.add(channel.get());
535                         logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
536                 }
537         }
538
539         /**
540          * Removes bots that leave a channel, or channels when it’s us that’s leaving.
541          *
542          * @param channelLeft
543          *              The channel left event
544          */
545         @Subscribe
546         public void channelLeft(ChannelLeft channelLeft) {
547                 Optional<Network> network = getNetwork(channelLeft.connection());
548                 if (!network.isPresent()) {
549                         return;
550                 }
551
552                 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
553                 if (bot == null) {
554                         /* maybe it was us? */
555                         if (channelLeft.connection().isSource(channelLeft.client())) {
556                                 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
557                                 if (!channel.isPresent()) {
558                                         /* maybe it was an extra channel? */
559                                         channel = getExtraChannel(network.get(), channelLeft.channel());
560                                         if (!channel.isPresent()) {
561                                                 /* okay, whatever. */
562                                                 return;
563                                         }
564
565                                         extraChannels.remove(channel);
566                                 } else {
567                                         channels.remove(channel.get());
568                                 }
569
570                                 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
571                         }
572
573                         return;
574                 }
575
576                 networkBots.remove(network.get(), channelLeft.client().nick().get());
577         }
578
579         /**
580          * Removes a client (which may be a bot) from the table of known bots.
581          *
582          * @param clientQuit
583          *              The client quit event
584          */
585         @Subscribe
586         public void clientQuit(ClientQuit clientQuit) {
587                 Optional<Network> network = getNetwork(clientQuit.connection());
588                 if (!network.isPresent()) {
589                         return;
590                 }
591
592                 networkBots.remove(network.get(), clientQuit.client().nick().get());
593         }
594
595         /**
596          * If the nickname of a bit changes, remove it from the old name and store it
597          * under the new name.
598          *
599          * @param nicknameChanged
600          *              The nickname changed event
601          */
602         @Subscribe
603         public void nicknameChanged(NicknameChanged nicknameChanged) {
604                 Optional<Network> network = getNetwork(nicknameChanged.connection());
605                 if (!network.isPresent()) {
606                         return;
607                 }
608
609                 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
610                 if (bot == null) {
611                         return;
612                 }
613
614                 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
615         }
616
617         /**
618          * If a message on a channel is received, it is parsed for pack information
619          * with is then added to a bot.
620          *
621          * @param channelMessageReceived
622          *              The channel message received event
623          */
624         @Subscribe
625         public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
626                 String message = getDefaultInstance().clean(channelMessageReceived.message());
627                 if (!message.startsWith("#")) {
628                         /* most probably not a pack announcement. */
629                         return;
630                 }
631
632                 Optional<Network> network = getNetwork(channelMessageReceived.connection());
633                 if (!network.isPresent()) {
634                         /* message for unknown connection? */
635                         return;
636                 }
637
638                 /* parse pack information. */
639                 Optional<Pack> pack = parsePack(message);
640                 if (!pack.isPresent()) {
641                         return;
642                 }
643
644                 Bot bot;
645                 synchronized (networkBots) {
646                         if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
647                                 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
648                                 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
649                                 eventBus.post(new BotAdded(bot));
650                         } else {
651                                 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
652                         }
653                 }
654
655                 /* add pack. */
656                 bot.addPack(pack.get());
657                 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
658         }
659
660         /**
661          * Forward all private messages to every console.
662          *
663          * @param privateMessageReceived
664          *              The private message recevied event
665          */
666         @Subscribe
667         public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
668                 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
669         }
670
671         /**
672          * Sends a message to all console when a notice was received.
673          *
674          * @param privateNoticeReceived
675          *              The notice received event
676          */
677         @Subscribe
678         public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
679                 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
680                 if (!network.isPresent()) {
681                         return;
682                 }
683
684                 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
685         }
686
687         /**
688          * Starts a DCC download.
689          *
690          * @param dccSendReceived
691          *              The DCC SEND event
692          */
693         @Subscribe
694         public void dccSendReceived(final DccSendReceived dccSendReceived) {
695                 final Optional<Network> network = getNetwork(dccSendReceived.connection());
696                 if (!network.isPresent()) {
697                         return;
698                 }
699
700                 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
701                 if (packDownloads.isEmpty()) {
702                         /* unknown download, ignore. */
703                         return;
704                 }
705
706                 /* check if it’s already downloading. */
707                 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
708                 if (!runningDownloads.isEmpty()) {
709                         eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
710                         return;
711                 }
712
713                 /* locate the correct download. */
714                 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
715
716                         @Override
717                         public boolean apply(Download download) {
718                                 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
719                         }
720                 }).toSet();
721
722                 /* we did not request this download. */
723                 if (requestedDownload.isEmpty()) {
724                         return;
725                 }
726
727                 Download download = requestedDownload.iterator().next();
728
729                 /* check if the file already exists. */
730                 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
731                 if (outputFile.exists()) {
732                         long existingFileSize = outputFile.length();
733
734                         /* file already complete? */
735                         if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
736                                 /* file is apparently already complete. just move it. */
737                                 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
738                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
739                                 } else {
740                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
741                                 }
742
743                                 /* remove download. */
744                                 downloads.removeAll(download.pack().name());
745                                 return;
746                         }
747
748                         /* file not complete yet, DCC resume it. */
749                         try {
750                                 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
751                                 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
752                         } catch (IOException ioe1) {
753                                 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
754                         }
755
756                         return;
757                 }
758
759                 /* file does not exist, start the download. */
760                 try {
761                         OutputStream fileOutputStream = new FileOutputStream(outputFile);
762                         DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
763                         download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
764                         dccReceivers.add(dccReceiver);
765                         dccReceiver.start();
766                         eventBus.post(new DownloadStarted(download));
767                 } catch (FileNotFoundException fnfe1) {
768                         eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
769                 }
770         }
771
772         @Subscribe
773         public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
774                 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
775                 if (!network.isPresent()) {
776                         return;
777                 }
778
779                 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
780                 if (packDownloads.isEmpty()) {
781                         /* unknown download, ignore. */
782                         return;
783                 }
784
785                 /* check if it’s already downloading. */
786                 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
787                 if (!runningDownloads.isEmpty()) {
788                         eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
789                         return;
790                 }
791
792                 /* locate the correct download. */
793                 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
794
795                         @Override
796                         public boolean apply(Download download) {
797                                 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
798                         }
799                 }).toSet();
800
801                 /* we did not request this download. */
802                 if (requestedDownload.isEmpty()) {
803                         return;
804                 }
805
806                 Download download = requestedDownload.iterator().next();
807
808                 try {
809                         File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
810                         if (outputFile.length() != dccAcceptReceived.position()) {
811                                 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
812                                 logger.log(Level.WARNING, String.format("Download %s from %s: have %d bytes but wants to resume from %d!", dccAcceptReceived.filename(), dccAcceptReceived.source(), outputFile.length(), dccAcceptReceived.position()));
813
814                                 downloads.removeAll(download.pack().name());
815                                 return;
816                         }
817                         OutputStream outputStream = new FileOutputStream(outputFile, true);
818                         DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
819                         download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
820                         dccReceivers.add(dccReceiver);
821                         dccReceiver.start();
822                         eventBus.post(new DownloadStarted(download));
823                 } catch (FileNotFoundException fnfe1) {
824                 }
825         }
826
827         /**
828          * Closes the output stream of the download and moves the file to the final
829          * location.
830          *
831          * @param dccDownloadFinished
832          *              The DCC download finished event
833          */
834         @Subscribe
835         public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
836
837                 /* locate the correct download. */
838                 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
839                 if (requestedDownload.isEmpty()) {
840                         /* this seems wrong. */
841                         logger.warning("Download finished but could not be located.");
842                         return;
843                 }
844                 Download download = requestedDownload.iterator().next();
845
846                 try {
847                         download.outputStream().close();
848                         File file = new File(download.filename());
849                         file.renameTo(new File(finalDirectory, download.pack().name()));
850                         eventBus.post(new DownloadFinished(download));
851                         dccReceivers.remove(dccDownloadFinished.dccReceiver());
852                         downloads.removeAll(download.pack().name());
853                 } catch (IOException ioe1) {
854                         /* TODO - handle all the errors. */
855                         logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
856                 }
857         }
858
859         /**
860          * Closes the output stream and notifies all listeners of the failure.
861          *
862          * @param dccDownloadFailed
863          *              The DCC download failed event
864          */
865         @Subscribe
866         public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
867
868                 /* locate the correct download. */
869                 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
870                 if (requestedDownload.isEmpty()) {
871                         /* this seems wrong. */
872                         logger.warning("Download finished but could not be located.");
873                         return;
874                 }
875                 Download download = requestedDownload.iterator().next();
876
877                 try {
878                         Closeables.close(download.outputStream(), true);
879                         eventBus.post(new DownloadFailed(download));
880                         dccReceivers.remove(dccDownloadFailed.dccReceiver());
881                         downloads.removeAll(download.pack().name());
882                 } catch (IOException ioe1) {
883                         /* swallow silently. */
884                 }
885         }
886
887         @Subscribe
888         public void replyReceived(ReplyReceived replyReceived) {
889                 logger.log(Level.FINEST, String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
890         }
891
892         //
893         // PRIVATE METHODS
894         //
895
896         /**
897          * Returns the download of the given pack from the given bot.
898          *
899          * @param pack
900          *              The pack being downloaded
901          * @param bot
902          *              The bot the pack is being downloaded from
903          * @return The download, or {@link Optional#absent()} if the download could not
904          *         be found
905          */
906         private Optional<Download> getDownload(Pack pack, Bot bot) {
907                 if (!downloads.containsKey(pack.name())) {
908                         return Optional.absent();
909                 }
910                 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
911                         if (download.bot().equals(bot)) {
912                                 return Optional.of(download);
913                         }
914                 }
915                 return Optional.absent();
916         }
917
918         /**
919          * Searches all current connections for the given connection, returning the
920          * associated network.
921          *
922          * @param connection
923          *              The connection to get the network for
924          * @return The network belonging to the connection, or {@link
925          *         Optional#absent()}
926          */
927         private Optional<Network> getNetwork(Connection connection) {
928                 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
929                         if (networkConnectionEntry.getValue().equals(connection)) {
930                                 return Optional.of(networkConnectionEntry.getKey());
931                         }
932                 }
933                 return Optional.absent();
934         }
935
936         /**
937          * Returns the configured channel for the given network and name.
938          *
939          * @param network
940          *              The network the channel is located on
941          * @param channelName
942          *              The name of the channel
943          * @return The configured channel, or {@link Optional#absent()} if no
944          *         configured channel matching the given network and name was found
945          */
946         public Optional<Channel> getChannel(Network network, String channelName) {
947                 for (Channel channel : channels) {
948                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
949                                 return Optional.of(channel);
950                         }
951                 }
952                 return Optional.absent();
953         }
954
955         /**
956          * Returns the extra channel for the given network and name.
957          *
958          * @param network
959          *              The network the channel is located on
960          * @param channelName
961          *              The name of the channel
962          * @return The extra channel, or {@link Optional#absent()} if no extra channel
963          *         matching the given network and name was found
964          */
965         public Optional<Channel> getExtraChannel(Network network, String channelName) {
966                 for (Channel channel : extraChannels) {
967                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
968                                 return Optional.of(channel);
969                         }
970                 }
971                 return Optional.absent();
972         }
973
974         /**
975          * Parses {@link Pack} information from the given message.
976          *
977          * @param message
978          *              The message to parse pack information from
979          * @return The parsed pack, or {@link Optional#absent()} if the message could
980          *         not be parsed into a pack
981          */
982         private Optional<Pack> parsePack(String message) {
983                 int squareOpen = message.indexOf('[');
984                 int squareClose = message.indexOf(']', squareOpen);
985                 if ((squareOpen == -1) && (squareClose == -1)) {
986                         return Optional.absent();
987                 }
988                 String packSize = message.substring(squareOpen + 1, squareClose);
989                 String packName = message.substring(message.lastIndexOf(' ') + 1);
990                 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
991                 return Optional.of(new Pack(packIndex, packSize, packName));
992         }
993
994 }