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