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