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