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