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