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