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