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