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