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