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